-
Notifications
You must be signed in to change notification settings - Fork 467
/
webhook.go
222 lines (183 loc) · 5.86 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation and Dapr Contributors.
// Licensed under the MIT License.
// ------------------------------------------------------------
package webhook
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/dapr/components-contrib/bindings"
"github.com/dapr/kit/logger"
)
const (
webhookContentType = "application/json"
defaultHTTPClientTimeout = time.Second * 30
)
type DingTalkWebhook struct {
logger logger.Logger
settings Settings
httpClient *http.Client
}
type webhookResult struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
type outgoingWebhook struct {
handler func(*bindings.ReadResponse) ([]byte, error)
}
var webhooks = struct { // nolint: gochecknoglobals
sync.RWMutex
m map[string]*outgoingWebhook
}{m: make(map[string]*outgoingWebhook)}
func NewDingTalkWebhook(l logger.Logger) *DingTalkWebhook {
// See guidance on proper HTTP client settings here:
// https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779
dialer := &net.Dialer{ //nolint:exhaustivestruct
Timeout: 5 * time.Second,
}
var netTransport = &http.Transport{ //nolint:exhaustivestruct
DialContext: dialer.DialContext,
TLSHandshakeTimeout: 5 * time.Second,
}
httpClient := &http.Client{ //nolint:exhaustivestruct
Timeout: defaultHTTPClientTimeout,
Transport: netTransport,
}
return &DingTalkWebhook{ //nolint:exhaustivestruct
logger: l,
httpClient: httpClient,
}
}
// Init performs metadata parsing
func (t *DingTalkWebhook) Init(metadata bindings.Metadata) error {
var err error
if err = t.settings.Decode(metadata.Properties); err != nil {
return fmt.Errorf("dingtalk configuration error: %w", err)
}
if err = t.settings.Validate(); err != nil {
return fmt.Errorf("dingtalk configuration error: %w", err)
}
return nil
}
// Read triggers the outgoing webhook, not yet production ready
func (t *DingTalkWebhook) Read(handler func(*bindings.ReadResponse) ([]byte, error)) error {
t.logger.Debugf("dingtalk webhook: start read input binding")
webhooks.Lock()
defer webhooks.Unlock()
_, loaded := webhooks.m[t.settings.ID]
if loaded {
return fmt.Errorf("dingtalk webhook error: duplicate id %s", t.settings.ID)
}
webhooks.m[t.settings.ID] = &outgoingWebhook{handler: handler}
return nil
}
// Operations returns list of operations supported by dingtalk webhook binding
func (t *DingTalkWebhook) Operations() []bindings.OperationKind {
return []bindings.OperationKind{bindings.CreateOperation, bindings.GetOperation}
}
func (t *DingTalkWebhook) Invoke(req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) {
rst := &bindings.InvokeResponse{Metadata: map[string]string{}, Data: nil}
switch req.Operation {
case bindings.CreateOperation:
return rst, t.sendMessage(req)
case bindings.GetOperation:
return rst, t.receivedMessage(req)
case bindings.DeleteOperation, bindings.ListOperation:
return rst, fmt.Errorf("dingtalk webhook error: unsupported operation %s", req.Operation)
default:
return rst, fmt.Errorf("dingtalk webhook error: unsupported operation %s", req.Operation)
}
}
func (t *DingTalkWebhook) getOutgoingWebhook() (*outgoingWebhook, error) {
webhooks.RLock()
defer webhooks.RUnlock()
item, loaded := webhooks.m[t.settings.ID]
if !loaded {
return nil, fmt.Errorf("dingtalk webhook error: invalid component metadata.id %s", t.settings.ID)
}
return item, nil
}
func (t *DingTalkWebhook) receivedMessage(req *bindings.InvokeRequest) error {
item, err := t.getOutgoingWebhook()
if err != nil {
return err
}
in := &bindings.ReadResponse{Data: req.Data, Metadata: req.Metadata}
if _, err = item.handler(in); err != nil {
return err
}
return nil
}
func (t *DingTalkWebhook) sendMessage(req *bindings.InvokeRequest) error {
msg := req.Data
postURL, err := getPostURL(t.settings.URL, t.settings.Secret)
if err != nil {
return fmt.Errorf("dingtalk webhook error: get url failed. %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPClientTimeout)
defer cancel()
httpReq, err := http.NewRequestWithContext(ctx, "POST", postURL, bytes.NewReader(msg))
if err != nil {
return fmt.Errorf("dingtalk webhook error: new request failed. %w", err)
}
httpReq.Header.Add("Accept", webhookContentType)
httpReq.Header.Add("Content-Type", webhookContentType)
resp, err := t.httpClient.Do(httpReq)
if err != nil {
return fmt.Errorf("dingtalk webhook error: post failed. %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("dingtalk webhook error: post failed. status:%d", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("dingtalk webhook error: read body failed. %w", err)
}
var rst webhookResult
err = json.Unmarshal(data, &rst)
if err != nil {
return fmt.Errorf("dingtalk webhook error: unmarshal body failed. %w", err)
}
if rst.ErrCode != 0 {
return fmt.Errorf("dingtalk webhook error: send msg failed. %v", rst.ErrMsg)
}
return nil
}
func getPostURL(urlPath, secret string) (string, error) {
if secret == "" {
return urlPath, nil
}
timestamp := strconv.FormatInt(time.Now().Unix()*1000, 10)
sign, err := sign(secret, timestamp)
if err != nil {
return urlPath, err
}
query := url.Values{}
query.Set("timestamp", timestamp)
query.Set("sign", sign)
return urlPath + "&" + query.Encode(), nil
}
func sign(secret, timestamp string) (string, error) {
stringToSign := fmt.Sprintf("%s\n%s", timestamp, secret)
h := hmac.New(sha256.New, []byte(secret))
if _, err := io.WriteString(h, stringToSign); err != nil {
return "", fmt.Errorf("sign failed. %w", err)
}
return base64.StdEncoding.EncodeToString(h.Sum(nil)), nil
}