/
http.go
376 lines (322 loc) · 13.3 KB
/
http.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//
// Copyright (c) 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package transforms
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"github.com/migelankodra/application-service/v2/pkg/interfaces"
"github.com/migelankodra/application-service/v2/pkg/util"
"github.com/edgexfoundry/go-mod-core-contracts/v2/common"
)
// HTTPSender ...
type HTTPSender struct {
url string
mimeType string
persistOnError bool
continueOnSendError bool
returnInputData bool
httpHeaderName string
secretName string
secretPath string
urlFormatter StringValuesFormatter
certFile string
keyFile string
caFile string
}
// NewHTTPSender creates, initializes and returns a new instance of HTTPSender
func NewHTTPSender(url string, mimeType string, persistOnError bool) HTTPSender {
return NewHTTPSenderWithOptions(HTTPSenderOptions{
URL: url,
MimeType: mimeType,
PersistOnError: persistOnError,
})
}
// NewHTTPSenderWithSecretHeader creates, initializes and returns a new instance of HTTPSender configured to use a secret header
func NewHTTPSenderWithSecretHeader(url string, mimeType string, persistOnError bool, headerName string, secretPath string, secretName string) HTTPSender {
return NewHTTPSenderWithOptions(HTTPSenderOptions{
URL: url,
MimeType: mimeType,
PersistOnError: persistOnError,
HTTPHeaderName: headerName,
SecretPath: secretPath,
SecretName: secretName,
})
}
// NewHTTPSSender creates, initializes and returns a new instance of HTTPSender
func NewHTTPSSender(URL string, MimeType string, PersistOnError bool, CertFile string, KeyFile string, CAFile string) HTTPSender {
return HTTPSender{
url: URL,
mimeType: MimeType,
persistOnError: PersistOnError,
certFile: CertFile,
keyFile: KeyFile,
caFile: CAFile,
}
}
// NewHTTPSenderWithOptions creates, initializes and returns a new instance of HTTPSender configured with provided options
func NewHTTPSenderWithOptions(options HTTPSenderOptions) HTTPSender {
return HTTPSender{
url: options.URL,
mimeType: options.MimeType,
persistOnError: options.PersistOnError,
continueOnSendError: options.ContinueOnSendError,
returnInputData: options.ReturnInputData,
httpHeaderName: options.HTTPHeaderName,
secretName: options.SecretName,
secretPath: options.SecretPath,
urlFormatter: options.URLFormatter,
}
}
// HTTPSenderOptions contains all options available to the sender
type HTTPSenderOptions struct {
// URL of destination
URL string
// MimeType to send to destination
MimeType string
// PersistOnError enables use of store & forward loop if true
PersistOnError bool
// HTTPHeaderName to use for passing configured secret
HTTPHeaderName string
// SecretPath to search for configured secret
SecretPath string
// SecretName for configured secret
SecretName string
// URLFormatter specifies custom formatting behavior to be applied to configured URL.
// If nothing specified, default behavior is to attempt to replace placeholders in the
// form '{some-context-key}' with the values found in the context storage.
URLFormatter StringValuesFormatter
// ContinueOnSendError allows execution of subsequent chained senders after errors if true
ContinueOnSendError bool
// ReturnInputData enables chaining multiple HTTP senders if true
ReturnInputData bool
}
// HTTPPost will send data from the previous function to the specified Endpoint via http POST.
// If no previous function exists, then the event that triggered the pipeline will be used.
// An empty string for the mimetype will default to application/json.
func (sender HTTPSender) HTTPPost(ctx interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {
return sender.httpSend(ctx, data, http.MethodPost)
}
// HTTPPut will send data from the previous function to the specified Endpoint via http PUT.
// If no previous function exists, then the event that triggered the pipeline will be used.
// An empty string for the mimetype will default to application/json.
func (sender HTTPSender) HTTPPut(ctx interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {
return sender.httpSend(ctx, data, http.MethodPut)
}
func (sender HTTPSender) httpSend(ctx interfaces.AppFunctionContext, data interface{}, method string) (bool, interface{}) {
lc := ctx.LoggingClient()
lc.Debugf("HTTP Exporting in pipeline '%s'", ctx.PipelineId())
if data == nil {
// We didn't receive a result
return false, fmt.Errorf("function HTTP%s in pipeline '%s': No Data Received", method, ctx.PipelineId())
}
if sender.persistOnError && sender.continueOnSendError {
return false, fmt.Errorf("in pipeline '%s' persistOnError & continueOnSendError can not both be set to true for HTTP Export", ctx.PipelineId())
}
if sender.continueOnSendError && !sender.returnInputData {
return false, fmt.Errorf("in pipeline '%s' continueOnSendError can only be used in conjunction returnInputData for multiple HTTP Export", ctx.PipelineId())
}
if sender.mimeType == "" {
sender.mimeType = "application/json"
}
exportData, err := util.CoerceType(data)
if err != nil {
return false, err
}
usingSecrets, err := sender.determineIfUsingSecrets(ctx)
if err != nil {
return false, err
}
usingHTTPS, err := sender.determineIfUsingHTTPs(ctx)
if err != nil {
return false, err
}
fmt.Println("using https: ", usingHTTPS)
formattedUrl, err := sender.urlFormatter.invoke(sender.url, ctx, data)
if err != nil {
return false, err
}
parsedUrl, err := url.Parse(formattedUrl)
if err != nil {
return false, err
}
var client *http.Client
if usingHTTPS {
// Load Certificate Authority public keys
caCert, err := ioutil.ReadFile(sender.caFile)
if err != nil {
return false, err
}
/**
* Configuration to use Host System CertPool insted of
* an input file with CA public keys
*
* caCertPool, err := x509.SystemCertPool()
* if err != nil {
* return false, err
* }
*/
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
RootCAs: caCertPool,
GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
c, err := tls.LoadX509KeyPair(sender.certFile, sender.keyFile)
if err != nil {
lc.Error("error loading certificate: %v", err)
return nil, err
}
return &c, nil
},
VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
if len(verifiedChains) > 0 {
for _, v := range verifiedChains {
for i, cert := range v {
lc.Debug("certificate: %d", i)
lc.Debug("certificate information: %v", CertificateInfo(cert))
}
}
}
return nil
},
}
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
client = &http.Client{
Transport: transport,
}
} else {
client = &http.Client{}
}
req, err := http.NewRequest(method, parsedUrl.String(), bytes.NewReader(exportData))
if err != nil {
return false, err
}
var theSecrets map[string]string
if usingSecrets {
theSecrets, err = ctx.GetSecret(sender.secretPath, sender.secretName)
if err != nil {
return false, err
}
lc.Debugf("Setting HTTP Header '%s' with secret value from SecretStore at path='%s' & name='%s in pipeline '%s'",
sender.httpHeaderName,
sender.secretPath,
sender.secretName,
ctx.PipelineId())
req.Header.Set(sender.httpHeaderName, theSecrets[sender.secretName])
}
req.Header.Set("Content-Type", sender.mimeType)
ctx.LoggingClient().Debugf("POSTing data to %s in pipeline '%s'", sender.url, ctx.PipelineId())
response, err := client.Do(req)
// Pipeline continues if we get a 2xx response, non-2xx response may stop pipeline
if err != nil || response.StatusCode < 200 || response.StatusCode >= 300 {
if err == nil {
err = fmt.Errorf("export failed with %d HTTP status code in pipeline '%s'", response.StatusCode, ctx.PipelineId())
} else {
err = fmt.Errorf("export failed in pipeline '%s': %s", ctx.PipelineId(), err.Error())
}
// If continuing on send error then can't be persisting on error since Store and Forward retries starting
// with the function that failed and stopped the execution of the pipeline.
if !sender.continueOnSendError {
sender.setRetryData(ctx, exportData)
return false, err
}
// Continuing pipeline on error
// This is in support of sending to multiple export destinations by chaining export functions in the pipeline.
ctx.LoggingClient().Errorf("Continuing pipeline on error in pipeline '%s': %s", ctx.PipelineId(), err.Error())
// Return the input data since must have some data for the next function to operate on.
return true, data
}
ctx.LoggingClient().Debugf("Sent %d bytes of data in pipeline '%s'. Response status is %s", len(exportData), ctx.PipelineId(), response.Status)
ctx.LoggingClient().Tracef("Data exported for pipeline '%s' (%s=%s)", ctx.PipelineId(), common.CorrelationHeader, ctx.CorrelationID())
// This allows multiple HTTP Exports to be chained in the pipeline to send the same data to different destinations
// Don't need to read the response data since not going to return it so just return now.
if sender.returnInputData {
return true, data
}
defer func() { _ = response.Body.Close() }()
responseData, errReadingBody := io.ReadAll(response.Body)
if errReadingBody != nil {
// Can't have continueOnSendError=true when returnInputData=false, so no need to check for it here
sender.setRetryData(ctx, exportData)
return false, errReadingBody
}
return true, responseData
}
func (sender HTTPSender) determineIfUsingHTTPs(ctx interfaces.AppFunctionContext) (bool, error) {
if sender.certFile != "" && sender.keyFile == "" {
return false, fmt.Errorf("in pipeline '%s', certificate secret key must be provided when HTTPS is specified", ctx.PipelineId())
} else if sender.certFile == "" && sender.keyFile != "" {
return false, fmt.Errorf("in pipeline '%s', certificate public key must be provided when HTTPS is specified", ctx.PipelineId())
} else if sender.certFile == "" && sender.keyFile == "" {
return false, fmt.Errorf("in pipeline '%s', certificate public/secret key must be provided when HTTPS is specified", ctx.PipelineId())
} else if sender.certFile != "" && sender.keyFile != "" && sender.caFile == "" {
return false, fmt.Errorf("in pipeline '%s', certificate authority key list must be provied when HTTPS is specified", ctx.PipelineId())
} else if sender.certFile == "" && sender.keyFile == "" && sender.caFile == "" {
return false, nil
}
return true, nil
}
func (sender HTTPSender) determineIfUsingSecrets(ctx interfaces.AppFunctionContext) (bool, error) {
// not using secrets if both are empty
if len(sender.secretPath) == 0 && len(sender.secretName) == 0 {
if len(sender.httpHeaderName) == 0 {
return false, nil
}
return false, fmt.Errorf("in pipeline '%s', secretPath & secretName must be specified when HTTP Header Name is specified", ctx.PipelineId())
}
//check if one field but not others are provided for secrets
if len(sender.secretPath) != 0 && len(sender.secretName) == 0 {
return false, fmt.Errorf("in pipeline '%s', secretPath was specified but no secretName was provided", ctx.PipelineId())
}
if len(sender.secretName) != 0 && len(sender.secretPath) == 0 {
return false, fmt.Errorf("in pipeline '%s', HTTP Header secretName was provided but no secretPath was provided", ctx.PipelineId())
}
if len(sender.httpHeaderName) == 0 {
return false, fmt.Errorf("in pipeline '%s', HTTP Header Name required when using secrets", ctx.PipelineId())
}
// using secrets, all required fields are provided
return true, nil
}
func (sender HTTPSender) setRetryData(ctx interfaces.AppFunctionContext, exportData []byte) {
if sender.persistOnError {
ctx.SetRetryData(exportData)
}
}
func CertificateInfo(cert *x509.Certificate) string {
if cert.Subject.CommonName == cert.Issuer.CommonName {
return fmt.Sprintf("self signed certificate: %v \n", cert.Issuer.CommonName)
}
s := fmt.Sprintf("DNS Names: %v", cert.DNSNames)
s += fmt.Sprintf("Authority key ID: %v", cert.AuthorityKeyId)
s += fmt.Sprintf("Basic Constraints Valid: %v", cert.BasicConstraintsValid)
s += fmt.Sprintf("CRL Distribution Points: %v", cert.CRLDistributionPoints)
s += fmt.Sprintf("e-mail addresses: %v", cert.EmailAddresses)
s += fmt.Sprintf("Excluded DNS Domains: %v", cert.ExcludedDNSDomains)
s += fmt.Sprintf("Excluded e-mail addresses: %v", cert.ExcludedEmailAddresses)
s += fmt.Sprintf("Excluded IP ranges: %v", cert.ExcludedIPRanges)
s += fmt.Sprintf("Excluded URI Domains: %v", cert.ExcludedURIDomains)
s += fmt.Sprintf("Ext Key Usage: %v", cert.ExtKeyUsage)
s += fmt.Sprintf("Extentions: %v", cert.Extensions)
s += fmt.Sprintf("Extra extentions: %v", cert.ExtraExtensions)
return s
}