Skip to content

Commit e981289

Browse files
committed
feat: #35 Adding support for OAuth2 context transmission
Signed-off-by: Laurent Broudoux <[email protected]>
1 parent f9d2c27 commit e981289

File tree

3 files changed

+48
-5
lines changed

3 files changed

+48
-5
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ The `test` command provides additional flags for advanced usages and options:
7575
* `--caCerts=<path1,path2>` allows to specify additional certificates CRT files to add to trusted roots ones,
7676
* `--secretName='<Secret Name>'` is an optional flag specifying the name of a Secret to use for connecting endpoint,
7777
* `--filteredOperations=<JSON>` allows to filter a list of operations to launch a test for,
78-
* `--operationsHeaders=<JSON>` allows to override some operations headers for the tests to launch.
78+
* `--operationsHeaders=<JSON>` allows to override some operations headers for the tests to launch,
79+
* `--oAuth2Context=<JSON>` allows specification of an OAuth2 grant flow to execute before launching the test (starts with Microcks version `1.8.0`).
7980

8081
Overriden test operations headers is a JSON strings where 1st level keys are operation name (eg. `GET /beer`) or `globals` for header applying to all the operations of the API. Headers are specified as an array of objects defining `key` and `values` properties.
8182

@@ -88,7 +89,8 @@ $ ./microcks-cli test 'Beer Catalog API:0.9' http://localhost:9090/api/ OPEN_API
8889
--keycloakClientSecret=7deb71e8-8c80-4376-95ad-00a399ee3ca1 \
8990
--insecure --verbose --waitFor=3sec \
9091
--filteredOperations='["GET /beer", "GET /beer/{name}"]' \
91-
--operationsHeaders='{"globals": [{"name": "x-api-key", "values": "my-values"}], "GET /beer": [{"name": "x-trace-id", "values": "xcvbnsdfghjklm"}]}'
92+
--operationsHeaders='{"globals": [{"name": "x-api-key", "values": "my-values"}], "GET /beer": [{"name": "x-trace-id", "values": "xcvbnsdfghjklm"}]}' \
93+
--oAuth2Context='{"clientId": "microcks-test", "clientSecret": "ab54d329-e435-41ae-a900-ec6b3fe15c54", "tokenUri": "https://idp.acme.org/realms/my-app/protocol/openid-connect/token", "grantType": "CLIENT_CREDENTIALS"}'
9294

9395
MicrocksClient got status for test "64c25f7ddec62569f9a0ed95" - success: true, inProgress: false
9496
Full TestResult details are available here: http://localhost:8080/#/tests/64c25f7ddec62569f9a0ed95

cmd/test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ func (c *testComamnd) Execute() {
8282
var secretName string
8383
var filteredOperations string
8484
var operationsHeaders string
85+
var oAuth2Context string
8586
var insecureTLS bool
8687
var caCertPaths string
8788
var verbose bool
@@ -93,6 +94,7 @@ func (c *testComamnd) Execute() {
9394
testCmd.StringVar(&secretName, "secretName", "", "Secret to use for connecting test endpoint")
9495
testCmd.StringVar(&filteredOperations, "filteredOperations", "", "List of operations to launch a test for")
9596
testCmd.StringVar(&operationsHeaders, "operationsHeaders", "", "Override of operations headers as JSON string")
97+
testCmd.StringVar(&oAuth2Context, "oAuth2Context", "", "Spec of an OAuth2 client context as JSON string")
9698
testCmd.BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection")
9799
testCmd.StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs")
98100
testCmd.BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges")
@@ -165,7 +167,7 @@ func (c *testComamnd) Execute() {
165167
mc.SetOAuthToken(oauthToken)
166168

167169
var testResultID string
168-
testResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders)
170+
testResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders, oAuth2Context)
169171
if err != nil {
170172
fmt.Printf("Got error when invoking Microcks client creating Test: %s", err)
171173
os.Exit(1)

pkg/connectors/microcks_client.go

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,15 @@ import (
3232
"github.com/microcks/microcks-cli/pkg/config"
3333
)
3434

35+
var (
36+
grantTypeChoices = map[string]bool{"PASSWORD": true, "CLIENT_CREDENTIALS": true, "REFRESH_TOKEN": true}
37+
)
38+
3539
// MicrocksClient allows interacting with Microcks APIs
3640
type MicrocksClient interface {
3741
GetKeycloakURL() (string, error)
3842
SetOAuthToken(oauthToken string)
39-
CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string) (string, error)
43+
CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string, oAuth2Context string) (string, error)
4044
GetTestResult(testResultID string) (*TestResultSummary, error)
4145
UploadArtifact(specificationFilePath string, mainArtifact bool) (string, error)
4246
}
@@ -60,6 +64,18 @@ type HeaderDTO struct {
6064
Values string `json:"values"`
6165
}
6266

67+
// OAuth2ClientContext represents a test request OAuth2 client context
68+
type OAuth2ClientContext struct {
69+
ClientId string `json:"clientId"`
70+
ClientSecret string `json:"clientSecret"`
71+
TokenURI string `json:"tokenUri"`
72+
Username string `json:"username"`
73+
Password string `json:"password"`
74+
RefreshToken string `json:"refreshToken"`
75+
GrantType string `json:"grantType"`
76+
Scopes string `json:"scopes"`
77+
}
78+
6379
type microcksClient struct {
6480
APIURL *url.URL
6581
OAuthToken string
@@ -105,12 +121,18 @@ func (c *microcksClient) GetKeycloakURL() (string, error) {
105121

106122
req.Header.Set("Accept", "application/json")
107123

124+
// Dump request if verbose required.
125+
config.DumpRequestIfRequired("Microcks for getting Keycloak config", req, true)
126+
108127
resp, err := c.httpClient.Do(req)
109128
if err != nil {
110129
return "", err
111130
}
112131
defer resp.Body.Close()
113132

133+
// Dump request if verbose required.
134+
config.DumpResponseIfRequired("Microcks for getting Keycloak config", resp, true)
135+
114136
body, err := ioutil.ReadAll(resp.Body)
115137
if err != nil {
116138
panic(err.Error())
@@ -137,7 +159,7 @@ func (c *microcksClient) SetOAuthToken(oauthToken string) {
137159
c.OAuthToken = oauthToken
138160
}
139161

140-
func (c *microcksClient) CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string) (string, error) {
162+
func (c *microcksClient) CreateTestResult(serviceID string, testEndpoint string, runnerType string, secretName string, timeout int64, filteredOperations string, operationsHeaders string, oAuth2Context string) (string, error) {
141163
// Ensure we have a correct URL.
142164
rel := &url.URL{Path: "tests"}
143165
u := c.APIURL.ResolveReference(rel)
@@ -157,6 +179,9 @@ func (c *microcksClient) CreateTestResult(serviceID string, testEndpoint string,
157179
if len(operationsHeaders) > 0 && ensureValidOperationsHeaders(operationsHeaders) {
158180
input += (", \"operationsHeaders\": " + operationsHeaders)
159181
}
182+
if len(oAuth2Context) > 0 && ensureValieOAuth2Context(oAuth2Context) {
183+
input += (", \"oAuth2Context\": " + oAuth2Context)
184+
}
160185

161186
input += "}"
162187

@@ -311,3 +336,17 @@ func ensureValidOperationsHeaders(operationsHeaders string) bool {
311336
}
312337
return true
313338
}
339+
340+
func ensureValieOAuth2Context(oAuth2Context string) bool {
341+
var oContext = OAuth2ClientContext{}
342+
err := json.Unmarshal([]byte(oAuth2Context), &oContext)
343+
if err != nil {
344+
fmt.Println("Error parsing JSON in oAuth2Context: ", err)
345+
return false
346+
}
347+
if !grantTypeChoices[oContext.GrantType] {
348+
fmt.Println("grantType in oAuth2Context is not supported. OAuth2 is turned off.")
349+
return false
350+
}
351+
return true
352+
}

0 commit comments

Comments
 (0)