forked from microcks/microcks-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmicrocks_client.go
More file actions
566 lines (478 loc) · 14.7 KB
/
microcks_client.go
File metadata and controls
566 lines (478 loc) · 14.7 KB
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*
* Copyright The Microcks Authors.
*
* 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 connectors
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
errs "errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt/v4"
"github.com/microcks/microcks-cli/pkg/config"
"github.com/microcks/microcks-cli/pkg/errors"
"golang.org/x/oauth2"
)
var (
grantTypeChoices = map[string]bool{"PASSWORD": true, "CLIENT_CREDENTIALS": true, "REFRESH_TOKEN": true}
)
// MicrocksClient allows interacting with Microcks APIs
type MicrocksClient interface {
HttpClient() *http.Client
GetKeycloakURL() (string, error)
SetOAuthToken(oauthToken string)
CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string, oAuth2Context string) (string, error)
GetTestResult(testResultID string) (*TestResultSummary, error)
UploadArtifact(specificationFilePath string, mainArtifact bool) (string, error)
DownloadArtifact(artifactURL string, mainArtifact bool, secret string) (string, error)
}
// TestResultSummary represents a simple view on Microcks TestResult
type TestResultSummary struct {
ID string `json:"id"`
Version int32 `json:"version"`
TestNumber int32 `json:"testNumber"`
TestDate int64 `json:"testDate"`
TestedEndpoint string `json:"testedEndpoint"`
ServiceID string `json:"serviceId"`
ElapsedTime int32 `json:"elapsedTime"`
Success bool `json:"success"`
InProgress bool `json:"inProgress"`
}
// HeaderDTO represents an operation header passed for Test
type HeaderDTO struct {
Name string `json:"name"`
Values string `json:"values"`
}
// OAuth2ClientContext represents a test request OAuth2 client context
type OAuth2ClientContext struct {
ClientId string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
TokenURI string `json:"tokenUri"`
Username string `json:"username"`
Password string `json:"password"`
RefreshToken string `json:"refreshToken"`
GrantType string `json:"grantType"`
Scopes string `json:"scopes"`
}
type ClientOptions struct {
ServerAddr string
Context string
ConfigPath string
AuthToken string
InsecureTLS bool
Verbose bool
CaCertPaths string
ClientId string
ClientSecret string
}
type microcksClient struct {
ServerAddr string
APIURL *url.URL
AuthToken string
CertFile *tls.Certificate
InsecureTLS bool
RefreshToken string
Insecure bool
Verbose bool
httpClient *http.Client
}
func NewClient(opts ClientOptions) (MicrocksClient, error) {
var c microcksClient
localCfg, err := config.ReadLocalConfig(opts.ConfigPath)
if err != nil {
return nil, err
}
var ctxName string
if localCfg != nil {
configCtx, err := localCfg.ResolveContext(opts.Context)
if err != nil {
return nil, err
}
c.ServerAddr = configCtx.Server.Server
c.Insecure = configCtx.Server.KeycloackEnable
c.InsecureTLS = configCtx.Server.InsecureTLS
c.AuthToken = configCtx.User.AuthToken
c.RefreshToken = configCtx.User.RefreshToken
apiurl := configCtx.Server.Server
if !strings.HasSuffix(apiurl, "/api/") {
apiurl += "/api/"
}
u, err := url.Parse(apiurl)
if err != nil {
panic(err)
}
c.APIURL = u
ctxName = configCtx.Name
}
if opts.Verbose {
c.Verbose = opts.Verbose
}
if config.InsecureTLS || len(config.CaCertPaths) > 0 {
tlsConfig := config.CreateTLSConfig()
tr := &http.Transport{
TLSClientConfig: tlsConfig,
}
c.httpClient = &http.Client{Transport: tr}
} else {
c.httpClient = http.DefaultClient
}
if localCfg != nil {
err = c.refreshAuthToken(localCfg, ctxName, opts.ConfigPath)
if err != nil {
return nil, err
}
}
return &c, nil
}
func (c *microcksClient) HttpClient() *http.Client {
return c.httpClient
}
func (c *microcksClient) GetKeycloakURL() (string, error) {
// Ensure we have a correct URL for retrieving Keycloal configuration.
rel := &url.URL{Path: "keycloak/config"}
u := c.APIURL.ResolveReference(rel)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/json")
// Dump request if verbose required.
config.DumpRequestIfRequired("Microcks for getting Keycloak config", req, true)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Dump request if verbose required.
config.DumpResponseIfRequired("Microcks for getting Keycloak config", resp, true)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
var configResp map[string]interface{}
if err := json.Unmarshal(body, &configResp); err != nil {
panic(err)
}
// Retrieve auth server url and realm name.
enabled := configResp["enabled"].(bool)
authServerURL := configResp["auth-server-url"].(string)
realmName := configResp["realm"].(string)
// Return a proper URL or 'null' if Keycloak is disables.
if enabled {
return authServerURL + "/realms/" + realmName + "/", nil
}
return "null", nil
}
func (c *microcksClient) refreshAuthToken(localCfg *config.LocalConfig, ctxName, configPath string) error {
if c.RefreshToken == "" {
// If we have no refresh token, there's no point in doing anything
return nil
}
configCtx, err := localCfg.ResolveContext(ctxName)
if err != nil {
return err
}
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
var claims jwt.RegisteredClaims
_, _, err = parser.ParseUnverified(configCtx.User.AuthToken, &claims)
if err != nil {
return err
}
if claims.Valid() == nil {
// token is still valid
return nil
}
log.Printf("Auth token no longer valid. Refreshing")
auth, err := localCfg.GetAuth(configCtx.Server.Server)
if err != nil {
return err
}
authToken, refreshToken, err := c.redeemRefreshToken(*auth)
if err != nil {
return err
}
c.AuthToken = authToken
c.RefreshToken = refreshToken
localCfg.UpsertUser(config.User{
Name: ctxName,
AuthToken: authToken,
RefreshToken: refreshToken,
})
err = config.WriteLocalConfig(*localCfg, configPath)
if err != nil {
return err
}
return nil
}
func (c *microcksClient) redeemRefreshToken(auth config.Auth) (string, string, error) {
keyCloakUrl, err := c.GetKeycloakURL()
errors.CheckError(err)
kc := NewKeycloakClient(keyCloakUrl, "", "")
oauth2Conf, err := kc.GetOIDCConfig()
errors.CheckError(err)
oauth2Conf.ClientID = auth.ClientId
oauth2Conf.ClientSecret = auth.ClientSecret
httpClient := c.httpClient
ctx := oidc.ClientContext(context.Background(), httpClient)
t := &oauth2.Token{
RefreshToken: c.RefreshToken,
}
token, err := oauth2Conf.TokenSource(ctx, t).Token()
if err != nil {
return "", "", err
}
return token.AccessToken, token.RefreshToken, nil
}
// NewMicrocksClient builds a new headless MicrocksClient without any authtoken and all for general purposes
func NewMicrocksClient(apiURL string) MicrocksClient {
mc := microcksClient{}
if !strings.HasSuffix(apiURL, "/api/") {
apiURL += "/api/"
}
u, err := url.Parse(apiURL)
if err != nil {
panic(err)
}
mc.APIURL = u
if config.InsecureTLS || len(config.CaCertPaths) > 0 {
tlsConfig := config.CreateTLSConfig()
tr := &http.Transport{
TLSClientConfig: tlsConfig,
}
mc.httpClient = &http.Client{Transport: tr}
} else {
mc.httpClient = http.DefaultClient
}
return &mc
}
func (c *microcksClient) SetOAuthToken(oauthToken string) {
c.AuthToken = oauthToken
}
func (c *microcksClient) CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string, oAuth2Context string) (string, error) {
// Ensure we have a correct URL.
rel := &url.URL{Path: "tests"}
u := c.APIURL.ResolveReference(rel)
// Prepare an input string as body.
var input = "{"
input += ("\"serviceId\": \"" + serviceID + "\", ")
input += ("\"testEndpoint\": \"" + testEndpoint + "\", ")
input += ("\"runnerType\": \"" + runnerType + "\", ")
input += ("\"timeout\": " + strconv.FormatInt(timeout, 10))
if len(secretName) > 0 {
input += (", \"secretName\": \"" + secretName + "\"")
}
if len(filteredOperations) > 0 && ensureValidOperationsList(filteredOperations) {
input += (", \"filteredOperations\": " + filteredOperations)
}
if len(operationsHeaders) > 0 && ensureValidOperationsHeaders(operationsHeaders) {
input += (", \"operationsHeaders\": " + operationsHeaders)
}
if len(oAuth2Context) > 0 && ensureValieOAuth2Context(oAuth2Context) {
input += (", \"oAuth2Context\": " + oAuth2Context)
}
input += "}"
req, err := http.NewRequest("POST", u.String(), strings.NewReader(input))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
// Dump request if verbose required.
config.DumpRequestIfRequired("Microcks for creating test", req, true)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Dump response if verbose required.
config.DumpResponseIfRequired("Microcks for creating test", resp, true)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
var createTestResp map[string]interface{}
if err := json.Unmarshal(body, &createTestResp); err != nil {
panic(err)
}
testID := createTestResp["id"].(string)
return testID, err
}
func (c *microcksClient) GetTestResult(testResultID string) (*TestResultSummary, error) {
// Ensure we have a correct URL.
rel := &url.URL{Path: "tests/" + testResultID}
u := c.APIURL.ResolveReference(rel)
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
// Dump request if verbose required.
config.DumpRequestIfRequired("Microcks for getting status", req, false)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Dump response if verbose required.
config.DumpResponseIfRequired("Microcks for getting status test", resp, true)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
result := TestResultSummary{}
json.Unmarshal([]byte(body), &result)
return &result, err
}
func (c *microcksClient) UploadArtifact(specificationFilePath string, mainArtifact bool) (string, error) {
// Ensure file exists on fs.
file, err := os.Open(specificationFilePath)
if err != nil {
return "", err
}
defer file.Close()
// Create a multipart request body, reading the file.
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filepath.Base(specificationFilePath))
if err != nil {
return "", err
}
_, err = io.Copy(part, file)
if err != nil {
panic(err.Error())
}
// Add the mainArtifact flag to request.
_ = writer.WriteField("mainArtifact", strconv.FormatBool(mainArtifact))
err = writer.Close()
if err != nil {
return "", err
}
// Ensure we have a correct URL.
rel := &url.URL{Path: "artifact/upload"}
u := c.APIURL.ResolveReference(rel)
req, err := http.NewRequest("POST", u.String(), body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
// Dump request if verbose required.
config.DumpRequestIfRequired("Microcks for uploading artifact", req, true)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Dump response if verbose required.
config.DumpResponseIfRequired("Microcks for uploading artifact", resp, true)
respBody, err := io.ReadAll(resp.Body)
if err != nil {
panic(err.Error())
}
// Raise exception if not created.
if resp.StatusCode != 201 {
return "", errs.New(string(respBody))
}
return string(respBody), err
}
func (c *microcksClient) DownloadArtifact(artifactURL string, mainArtifact bool, secret string) (string, error) {
// create Multipart Form to add fields
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Add all the form fields
writer.WriteField("url", artifactURL)
writer.WriteField("mainArtifact", strconv.FormatBool(mainArtifact))
if secret != "" {
writer.WriteField("secret", secret)
}
err := writer.Close()
if err != nil {
return "", err
}
// Ensure we have a correct URL.
rel := &url.URL{Path: "artifact/download"}
u := c.APIURL.ResolveReference(rel)
req, err := http.NewRequest("POST", u.String(), body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+c.AuthToken)
// Dump request if verbose required.
config.DumpRequestIfRequired("Microcks for uploading artifact", req, true)
resp, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Dump response if verbose required.
config.DumpResponseIfRequired("Microcks for uploading artifact", resp, true)
respBody, err := io.ReadAll(req.Body)
if err != nil {
panic(err.Error())
}
// Raise exception if not created.
if resp.StatusCode != 201 {
return "", errs.New(string(respBody))
}
return string(respBody), err
}
func ensureValidOperationsList(filteredOperations string) bool {
// Unmarshal using a generic interface
var list = []string{}
err := json.Unmarshal([]byte(filteredOperations), &list)
if err != nil {
fmt.Println("Error parsing JSON in filteredOperations: ", err)
return false
}
return true
}
func ensureValidOperationsHeaders(operationsHeaders string) bool {
// Unmarshal using a generic interface
var headers = map[string][]HeaderDTO{}
err := json.Unmarshal([]byte(operationsHeaders), &headers)
if err != nil {
fmt.Println("Error parsing JSON in operationsHeaders: ", err)
return false
}
return true
}
func ensureValieOAuth2Context(oAuth2Context string) bool {
var oContext = OAuth2ClientContext{}
err := json.Unmarshal([]byte(oAuth2Context), &oContext)
if err != nil {
fmt.Println("Error parsing JSON in oAuth2Context: ", err)
return false
}
if !grantTypeChoices[oContext.GrantType] {
fmt.Println("grantType in oAuth2Context is not supported. OAuth2 is turned off.")
return false
}
return true
}