-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
511 lines (475 loc) · 12.2 KB
/
client.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package ensweb
import (
"bytes"
"crypto/ecdh"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/EnsurityTechnologies/helper/jsonutil"
"github.com/EnsurityTechnologies/logger"
"github.com/EnsurityTechnologies/uuid"
)
type AuthenticateFunc func() error
// Client : Client struct
type Client struct {
cfg *Config
log logger.Logger
address string
addr *url.URL
hc *http.Client
th TokenHelper
defaultTimeout time.Duration
token string
rtoken string
cookies []*http.Cookie
secureAPI bool
pk *ecdh.PrivateKey
publicKey string
licenseKey string
serverPublicKey string
ss string
jid string
}
type ClientOptions = func(*Client) error
func SetClientDefaultTimeout(timeout time.Duration) ClientOptions {
return func(c *Client) error {
c.defaultTimeout = timeout
return nil
}
}
func SetClientTokenHelper(th TokenHelper) ClientOptions {
return func(c *Client) error {
c.th = th
return nil
}
}
func EnableClientSecureAPI(licenseKey string) ClientOptions {
return func(c *Client) error {
c.secureAPI = true
c.licenseKey = licenseKey
key, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
c.log.Error("failed to generate private key", "err", err)
return err
}
c.pk = key
pub := c.pk.PublicKey().Bytes()
c.publicKey = base64.StdEncoding.EncodeToString(pub)
req, err := c.JSONRequest("GET", GetPublicKeyAPI, nil)
if err != nil {
c.log.Error("failed to create json request", "err", err)
return err
}
resp, err := c.Do(req)
if err != nil {
c.log.Error("failed to get server public key, failed to get response", "err", err)
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNoContent {
c.log.Error("failed to get server public key, no response from server")
return fmt.Errorf("failed to get server public key, no response from server")
}
var pr PublicKeyResponse
err = jsonutil.DecodeJSONFromReader(resp.Body, &pr)
if err != nil {
c.log.Error("failed to get server public key, json unmarshell failed", "err", err)
return err
}
c.serverPublicKey = pr.PublicKey
err = c.getSharedSecret()
if err != nil {
c.log.Error("failed to generate shared secret", "err", err)
return err
}
return nil
}
}
// NewClient : Create new client handle
func NewClient(cfg *Config, log logger.Logger, options ...ClientOptions) (Client, error) {
var address string
var tr *http.Transport
clog := log.Named("enswebclient")
if cfg.Secure {
address = fmt.Sprintf("https://%s", net.JoinHostPort(cfg.Address, cfg.Port))
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
} else {
address = fmt.Sprintf("http://%s", net.JoinHostPort(cfg.Address, cfg.Port))
tr = &http.Transport{
IdleConnTimeout: 30 * time.Second,
}
}
if cfg.EnableProxy {
url, err := url.Parse(cfg.ProxyUrl)
if err != nil {
log.Error("failed to create client, failed parse proxy url", "err", err)
return Client{}, err
}
tr.Proxy = http.ProxyURL(url)
}
hc := &http.Client{
Transport: tr,
Timeout: DefaultTimeout,
}
addr, err := url.Parse(address)
if err != nil {
clog.Error("failed to parse server address", "err", err)
return Client{}, err
}
c := Client{
cfg: cfg,
log: clog,
address: address,
addr: addr,
hc: hc,
jid: uuid.New().String(),
}
for _, op := range options {
err = op(&c)
if err != nil {
clog.Error("failed in setting the option", "err", err)
return Client{}, err
}
}
return c, nil
}
func (c *Client) SetUrl(siteUrl string) error {
var tr *http.Transport
if strings.Contains(siteUrl, "https") {
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
} else {
tr = &http.Transport{
IdleConnTimeout: 30 * time.Second,
}
}
hc := &http.Client{
Transport: tr,
Timeout: DefaultTimeout,
}
addr, err := url.Parse(siteUrl)
if err != nil {
c.log.Error("failed to parse server address", "err", err)
return err
}
c.addr = addr
c.hc = hc
c.address = siteUrl
return nil
}
func (c *Client) JSONRequest(method string, requestPath string, model interface{}) (*http.Request, error) {
var body *bytes.Buffer
if model != nil {
j, err := json.Marshal(model)
if err != nil {
return nil, err
}
body = bytes.NewBuffer(j)
} else {
body = bytes.NewBuffer(make([]byte, 0))
}
url := &url.URL{
Scheme: c.addr.Scheme,
Host: c.addr.Host,
User: c.addr.User,
Path: path.Join(c.addr.Path, requestPath),
}
req, err := http.NewRequest(method, url.RequestURI(), body)
req.Host = url.Host
req.URL.User = url.User
req.URL.Scheme = url.Scheme
req.URL.Host = url.Host
req.Header.Set("Content-Type", "application/json")
return req, err
}
func (c *Client) MultiFormRequest(method string, requestPath string, field map[string]string, files map[string]string) (*http.Request, error) {
var b bytes.Buffer
w := multipart.NewWriter(&b)
for k, v := range field {
fw, err := w.CreateFormField(k)
if err != nil {
return nil, err
}
if _, err = io.Copy(fw, strings.NewReader(v)); err != nil {
return nil, err
}
}
for k, v := range files {
fw, err := w.CreateFormFile(k, filepath.Base(v))
if err != nil {
return nil, err
}
f, err := os.Open(v)
if err != nil {
return nil, err
}
if _, err = io.Copy(fw, f); err != nil {
return nil, err
}
}
err := w.Close()
if err != nil {
return nil, err
}
url := &url.URL{
Scheme: c.addr.Scheme,
Host: c.addr.Host,
User: c.addr.User,
Path: path.Join(c.addr.Path, requestPath),
}
req, err := http.NewRequest(method, url.RequestURI(), &b)
req.Header.Set("Content-Type", w.FormDataContentType())
req.Host = url.Host
req.URL.User = url.User
req.URL.Scheme = url.Scheme
req.URL.Host = url.Host
return req, err
}
func (c *Client) SetAuthorization(req *http.Request, token string) {
var bearer = "Bearer " + token
req.Header.Set("Authorization", bearer)
}
func (c *Client) Do(req *http.Request, timeout ...time.Duration) (*http.Response, error) {
if timeout != nil {
c.hc.Timeout = timeout[0]
} else {
c.hc.Timeout = c.defaultTimeout
}
return c.hc.Do(req)
}
func (c *Client) SetCookies(cookies []*http.Cookie) {
c.cookies = cookies
}
func (c *Client) GetCookies() []*http.Cookie {
return c.cookies
}
func (c *Client) SetToken(token string) error {
if c.th != nil {
return c.th.StoreAccessToken(token)
}
c.token = token
return nil
}
func (c *Client) SetRefreshToken(token string) error {
if c.th != nil {
return c.th.StoreRefreshToken(token)
}
c.rtoken = token
return nil
}
func (c *Client) GetToken() string {
if c.th != nil {
tk, err := c.th.GetAccessToken()
if err != nil {
return "InvalidToken"
} else {
return tk
}
}
return c.token
}
func (c *Client) GetRefreshToken() string {
if c.th != nil {
tk, err := c.th.GetRefreshToken()
if err != nil {
return "InvalidToken"
} else {
return tk
}
}
return c.rtoken
}
func (c *Client) ParseMutilform(resp *http.Response, dirPath string) ([]string, map[string]string, error) {
mediatype, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil {
return nil, nil, err
}
if mediatype != "multipart/form-data" {
return nil, nil, fmt.Errorf("invalid content type %s", mediatype)
}
defer resp.Body.Close()
mr := multipart.NewReader(resp.Body, params["boundary"])
paramFiles := make([]string, 0)
paramTexts := make(map[string]string)
for {
part, err := mr.NextPart()
if err != nil {
if err != io.EOF { //io.EOF error means reading is complete
return paramFiles, paramTexts, fmt.Errorf(" error reading multipart request: %+v", err)
}
break
}
if part.FileName() != "" {
f, err := os.Create(dirPath + part.FileName())
if err != nil {
return paramFiles, paramTexts, fmt.Errorf("error in creating file %+v", err)
}
value, _ := ioutil.ReadAll(part)
f.Write(value)
f.Close()
if err != nil {
return paramFiles, paramTexts, fmt.Errorf("error reading file param %+v", err)
}
paramFiles = append(paramFiles, dirPath+part.FileName())
} else {
name := part.FormName()
buf := new(bytes.Buffer)
buf.ReadFrom(part)
paramTexts[name] = buf.String()
}
}
return paramFiles, paramTexts, nil
}
func (c *Client) getSharedSecret() error {
if c.ss != "" {
return nil
}
pb, err := base64.StdEncoding.DecodeString(c.serverPublicKey)
if err != nil {
c.log.Error("invalid pubkey, failed to decode base 64 string", "err", err)
return err
}
pub, err := ecdh.P256().NewPublicKey(pb)
if err != nil {
c.log.Error("invalid pubkey, failed to frame pubkey", "err", err)
return err
}
kb, err := c.pk.ECDH(pub)
if err != nil {
c.log.Error("failed to create shared secret", "err", err)
return err
}
ss := sha256.Sum256(kb)
c.ss = hex.EncodeToString(ss[:])
return nil
}
func (c *Client) sendJSON(method string, path string, auth bool, querry map[string]string, headers map[string]string, in interface{}, out interface{}, errout interface{}, timeout ...time.Duration) (int, error) {
var req *http.Request
var err error
if c.secureAPI {
var sd SecureData
if in != nil {
sd.Data, err = encryptModel(c.ss, in)
if err != nil {
c.log.Error("failed to encrypt input model", "err", err)
return 0, err
}
req, err = c.JSONRequest(method, path, sd)
} else {
req, err = c.JSONRequest(method, path, nil)
}
if err != nil {
c.log.Error("failed to create json request", "err", err)
return 0, err
}
reqID := RequestID{
ID: uuid.New().String(),
JourneyID: c.jid,
TS: time.Now().Unix(),
AppID: "goclient",
}
rid, err := encryptModel(c.ss, reqID)
if err != nil {
c.log.Error("failed to encrypt request model", "err", err)
return 0, err
}
req.Header.Add(RequestIDHdr, rid)
req.Header.Add(LicenseKeyHdr, c.licenseKey)
req.Header.Add(PublicKeyHdr, c.publicKey)
} else {
req, err = c.JSONRequest(method, path, in)
if err != nil {
c.log.Error("failed to create json request", "err", err)
return 0, err
}
}
if auth {
c.SetAuthorization(req, c.GetToken())
}
for k, v := range headers {
req.Header.Set(k, v)
}
if querry != nil {
q := req.URL.Query()
for k, v := range querry {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
resp, err := c.Do(req, timeout...)
if err != nil {
c.log.Error("failed to get response from the server", "err", err)
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNoContent {
return resp.StatusCode, nil
}
if resp.StatusCode == http.StatusOK || errout == nil {
if c.secureAPI {
var sd SecureData
err = jsonutil.DecodeJSONFromReader(resp.Body, &sd)
if err != nil {
c.log.Error("failed to parse json output", "err", err)
return resp.StatusCode, err
}
err = decryptModel(c.ss, sd.Data, out)
if err != nil {
c.log.Error("failed to decrypt model", "err", err)
return resp.StatusCode, err
}
} else {
err = jsonutil.DecodeJSONFromReader(resp.Body, out)
if err != nil {
c.log.Error("failed to parse json output", "err", err, "statuscode", resp.StatusCode)
return resp.StatusCode, err
}
}
} else {
err = jsonutil.DecodeJSONFromReader(resp.Body, errout)
if err != nil {
c.log.Error("failed to parse json output", "err", err, "statuscode", resp.StatusCode)
return resp.StatusCode, err
}
}
return resp.StatusCode, nil
}
func (c *Client) SendJSON(method string, path string, auth bool, querry map[string]string, headers map[string]string, in interface{}, out interface{}, errout interface{}, af AuthenticateFunc, timeout ...time.Duration) error {
statusCode, err := c.sendJSON(method, path, auth, querry, headers, in, out, errout, timeout...)
if statusCode == http.StatusUnauthorized {
c.log.Debug("unauthorized calling authenticate function")
if af != nil {
c.log.Debug("Calling authenticate function")
err = af()
if err == nil {
_, err = c.sendJSON(method, path, auth, querry, headers, in, out, errout, timeout...)
if err != nil {
return err
}
}
}
}
if err != nil {
return err
}
return nil
}