Skip to content

Commit

Permalink
Address issues pointed out by reviewers.
Browse files Browse the repository at this point in the history
Use the golang.org/x/oauth2/clientcredentials library instead of manually crafting a Http request to CSP for OAuth2.0 authentication flow.

Testing done:
make build
make test
golangci-lint run

terraform-provider-vmc % make testacc TESTARGS="-run='TestAccResourceVmcSddcZerocloud'"
TF_ACC=1 go test $(go list ./... |grep -v 'vendor') -v -run='TestAccResourceVmcSddcZerocloud' -timeout 240m
?   	github.com/vmware/terraform-provider-vmc	[no test files]
=== RUN   TestAccResourceVmcSddcZerocloud
=== PAUSE TestAccResourceVmcSddcZerocloud
=== CONT  TestAccResourceVmcSddcZerocloud
SDDC terraform_sddc_test_eucsf7qmk2 created successfully with id eb298641-625d-491b-8954-ea5311158965
--- PASS: TestAccResourceVmcSddcZerocloud (122.66s)
PASS
ok  	github.com/vmware/terraform-provider-vmc/vmc	122.930s
?   	github.com/vmware/terraform-provider-vmc/vmc/connector	[no test files]
?   	github.com/vmware/terraform-provider-vmc/vmc/constants	[no test files]
testing: warning: no tests to run
PASS
ok  	github.com/vmware/terraform-provider-vmc/vmc/sddcgroup	0.200s [no tests to run]
testing: warning: no tests to run
PASS
ok  	github.com/vmware/terraform-provider-vmc/vmc/task	0.184s [no tests to run]

Signed-off-by: Dimitar Proynov <proynovd@vmware.com>
  • Loading branch information
Dimitar Proynov committed Feb 22, 2023
1 parent 5ce2e5e commit 8dc5030
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 32 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
github.com/vmware/vsphere-automation-sdk-go/services/vmc v0.10.0
github.com/vmware/vsphere-automation-sdk-go/services/vmc/autoscaler v0.4.0
github.com/vmware/vsphere-automation-sdk-go/services/vmc/draas v0.4.0
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
)

require (
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ golang.org/x/net v0.0.0-20210510120150-4163338589ed h1:p9UgmWI9wKpfYmgaV/IZKGdXc
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand Down
48 changes: 18 additions & 30 deletions vmc/connector/clientconnector.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
package connector

import (
"encoding/base64"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/vmware/terraform-provider-vmc/vmc/constants"
"golang.org/x/oauth2/clientcredentials"
"io"
"net/http"
"reflect"
Expand All @@ -35,14 +36,7 @@ type Wrapper struct {
}

func CopyWrapper(original Wrapper) *Wrapper {
return &Wrapper{
RefreshToken: original.RefreshToken,
ClientID: original.ClientID,
ClientSecret: original.ClientSecret,
OrgID: original.OrgID,
VmcURL: original.VmcURL,
CspURL: original.CspURL,
}
return &original
}

func (c *Wrapper) Authenticate() error {
Expand Down Expand Up @@ -123,10 +117,10 @@ func newClientConnectorByClientID(clientID, clientSecret, serviceURL, cspURL str

if len(cspURL) <= 0 {
cspURL = constants.DefaultCspURL +
constants.CspOauthURLSuffix
constants.CspTokenURLSuffix
} else {
cspURL = cspURL +
constants.CspOauthURLSuffix
constants.CspTokenURLSuffix
}

securityCtx, err := securityContextByClientID(clientID, clientSecret, cspURL)
Expand All @@ -140,28 +134,17 @@ func newClientConnectorByClientID(clientID, clientSecret, serviceURL, cspURL str
return connector, nil
}

func securityContextByClientID(clientID string, clientSecret string, cspURL string) (core.SecurityContext, error) {
clientCredentials := clientID + ":" + clientSecret
encodedClientCredentials := base64.StdEncoding.EncodeToString([]byte(clientCredentials))

payload := strings.NewReader("grant_type=client_credentials")

req, _ := http.NewRequest("POST", cspURL, payload)

req.Header.Add("content-type", "application/x-www-form-urlencoded")
req.Header.Add("authorization", "Basic "+encodedClientCredentials)

res, err := http.DefaultClient.Do(req)

if err != nil {
return nil, err
func securityContextByClientID(clientID string, clientSecret string, cspTokenEndpointURL string) (core.SecurityContext, error) {
oauth2Config := clientcredentials.Config{
ClientID: clientID,
ClientSecret: clientSecret,
TokenURL: cspTokenEndpointURL,
}

securityCtx, err := parseAuthnResponse(res)
token, err := oauth2Config.Token(context.TODO())
if err != nil {
return nil, err
}
return securityCtx, nil
return security.NewOauthSecurityContext(token.AccessToken), nil
}

func parseAuthnResponse(response *http.Response) (*security.OauthSecurityContext, error) {
Expand All @@ -170,7 +153,12 @@ func parseAuthnResponse(response *http.Response) (*security.OauthSecurityContext
return nil, fmt.Errorf("response from Cloud Service Provider contains status code %d : %s", response.StatusCode, string(b))
}

defer response.Body.Close()
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
fmt.Println(err)
}
}(response.Body)

var jsondata map[string]interface{}
err := json.NewDecoder(response.Body).Decode(&jsondata)
Expand Down
4 changes: 2 additions & 2 deletions vmc/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ const (
// CspRefreshURLSuffix defines the CSP Refresh Token API endpoint.
CspRefreshURLSuffix string = "/csp/gateway/am/api/auth/api-tokens/authorize"

// CspOauthURLSuffix defines the CSP Oauth API endpoint.
CspOauthURLSuffix string = "/csp/gateway/am/api/auth/token"
// CspTokenURLSuffix defines the CSP Oauth API endpoint.
CspTokenURLSuffix string = "/csp/gateway/am/api/auth/token"

// sksNSXTManager to be stripped from nsxt reverse proxy url for public IP resource
SksNSXTManager string = "/sks-nsxt-manager"
Expand Down

0 comments on commit 8dc5030

Please sign in to comment.