Skip to content

Commit

Permalink
Refactor org retrieval, add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
vuil committed Sep 25, 2024
1 parent b12a340 commit 9294e28
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 14 deletions.
37 changes: 23 additions & 14 deletions pkg/command/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,9 +660,12 @@ type DeploymentMetadataOrganization struct {
Name string `json:"name"`
}

func getOrgFromSelfManaged(c *configtypes.Context) (string, string, error) {
hubEndpoint := c.AdditionalMetadata[config.TanzuHubEndpointKey].(string)
hubEndpoint = strings.TrimRight(hubEndpoint, " /")
func getOrgFromSelfManagedEndpoint(c *configtypes.Context) (string, string, error) {
val, ok := c.AdditionalMetadata[config.TanzuHubEndpointKey]
if !ok {
return "", "", errors.New("Hub endpoint not set")
}
hubEndpoint := strings.TrimRight(val.(string), " /")
metadataURL := hubEndpoint + "/assets/env-config/env-config.json"
req, _ := http.NewRequest("GET", metadataURL, http.NoBody) //nolint:noctx

Expand Down Expand Up @@ -699,21 +702,13 @@ func getOrgFromSelfManaged(c *configtypes.Context) (string, string, error) {
return dm.Organization.ID, dm.Organization.Name, nil
}

func globalTanzuLoginUAA(c *configtypes.Context, generateContextNameFunc func(orgName, endpoint string, isStaging bool) string) error {
uaaEndpoint := c.AdditionalMetadata[config.TanzuAuthEndpointKey].(string)
log.V(7).Infof("Login to UAA endpoint: %s", uaaEndpoint)

claims, err := doInteractiveLoginAndUpdateContext(c, uaaEndpoint)
if err != nil {
return err
}

func getSelfManagedOrg(c *configtypes.Context) (string, string) {
// UAA-based authentication itself not provide org id or name.
// Instead they are retrievable via a predefined location
var orgID string
orgName := "self-managed"

retrievedOrgID, retrievedOrgName, err := getOrgFromSelfManaged(c)
retrievedOrgID, retrievedOrgName, err := getOrgFromSelfManagedEndpoint(c)
if err == nil && retrievedOrgID != "" {
orgID = retrievedOrgID
if retrievedOrgName != "" {
Expand All @@ -729,12 +724,26 @@ func globalTanzuLoginUAA(c *configtypes.Context, generateContextNameFunc func(or
}
orgID = uaaOrgIDValue
}
claims.OrgID = orgID
uaaOrgNameValue, ok := os.LookupEnv(constants.UAALoginOrgName)
if ok {
orgName = uaaOrgNameValue
}

return orgID, orgName
}

func globalTanzuLoginUAA(c *configtypes.Context, generateContextNameFunc func(orgName, endpoint string, isStaging bool) string) error {
uaaEndpoint := c.AdditionalMetadata[config.TanzuAuthEndpointKey].(string)
log.V(7).Infof("Login to UAA endpoint: %s", uaaEndpoint)

claims, err := doInteractiveLoginAndUpdateContext(c, uaaEndpoint)
if err != nil {
return err
}

orgID, orgName := getSelfManagedOrg(c)
claims.OrgID = orgID

if err := updateContextOnTanzuLogin(c, generateContextNameFunc, claims, orgName); err != nil {
return err
}
Expand Down
82 changes: 82 additions & 0 deletions pkg/command/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -1280,6 +1282,86 @@ var _ = Describe("testing context use", func() {
})
})

var _ = Describe("Test get org information", func() {
var (
err error
serverGoodData *httptest.Server
serverBadData *httptest.Server
tanzuContext *configtypes.Context
)
const (
fakeContextName = "fake-context"
fakeAccessToken = "fake-access-token"
fakeEndpoint = "fake.tanzu.cloud.vmware.com"
fakeIssuer = "https://fake.issuer.come/auth"
)
BeforeEach(func() {
tanzuContext = &configtypes.Context{
Name: fakeContextName,
ContextType: configtypes.ContextTypeTanzu,
AdditionalMetadata: map[string]interface{}{},
GlobalOpts: &configtypes.GlobalServer{
Endpoint: fakeEndpoint,
Auth: configtypes.GlobalServerAuth{
AccessToken: fakeAccessToken,
Issuer: fakeIssuer,
Type: common.APITokenType,
},
},
}

serverGoodData = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"apiEndpoint":"/hub/graphql","apiHost":"","organization":{"displayName":"TPSM","id":"c4558dfb-18ae-480a-af06-8222600b198f","name":"Test Org"}}`))
}))
serverBadData = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"badkey":"badvalue"}`))
}))
})

It("should return org information from metadata file if found but env vars if set", func() {
tanzuContext.AdditionalMetadata[config.TanzuHubEndpointKey] = serverGoodData.URL
err = config.SetContext(tanzuContext, false)
Expect(err).To(BeNil())

orgID, orgName := getSelfManagedOrg(tanzuContext)
Expect(orgID).To(Equal("c4558dfb-18ae-480a-af06-8222600b198f"))
Expect(orgName).To(Equal("Test Org"))

os.Setenv(constants.UAALoginOrgID, "11111111-1111-1111-1111-111111111111")
os.Setenv(constants.UAALoginOrgName, "OverwrittenOrgName")
orgID, orgName = getSelfManagedOrg(tanzuContext)
Expect(orgID).To(Equal("11111111-1111-1111-1111-111111111111"))
Expect(orgName).To(Equal("OverwrittenOrgName"))
defer os.Unsetenv(constants.UAALoginOrgID)
defer os.Unsetenv(constants.UAALoginOrgName)
})

It("should return default org information or on invalid metadata or env vars if set", func() {
tanzuContext.AdditionalMetadata[config.TanzuHubEndpointKey] = serverBadData.URL
err = config.SetContext(tanzuContext, false)
Expect(err).To(BeNil())

orgID, orgName := getSelfManagedOrg(tanzuContext)
Expect(orgID).To(Equal(""))
Expect(orgName).To(Equal("self-managed"))

os.Setenv(constants.UAALoginOrgID, "11111111-2222-2222-2222-222222222222")
os.Setenv(constants.UAALoginOrgName, "OverwrittenOrgName")
orgID, orgName = getSelfManagedOrg(tanzuContext)
Expect(orgID).To(Equal("11111111-2222-2222-2222-222222222222"))
Expect(orgName).To(Equal("OverwrittenOrgName"))
defer os.Unsetenv(constants.UAALoginOrgID)
defer os.Unsetenv(constants.UAALoginOrgName)
})

AfterEach(func() {
serverGoodData.Close()
serverBadData.Close()
})
})

func TestCompletionContext(t *testing.T) {
ctxK8s1 := &configtypes.Context{
Name: "tkg1",
Expand Down

0 comments on commit 9294e28

Please sign in to comment.