Skip to content

Commit

Permalink
fix: add support for dynamic config url (#1565)
Browse files Browse the repository at this point in the history
  • Loading branch information
wtrocki authored May 17, 2022
1 parent b5b2c4c commit 9b50176
Show file tree
Hide file tree
Showing 12 changed files with 148 additions and 31 deletions.
12 changes: 12 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -274,5 +274,17 @@
"--dir", "./docs/commands"
]
},
{
"name": "request",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/rhoas",
"env": {},
"args": [
"request",
"--path", "/api/kafkas_mgmt/v1/sso_providers",
]
},
]
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ require (
github.com/redhat-developer/app-services-sdk-go/accountmgmt v0.1.0
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.5.0
github.com/redhat-developer/app-services-sdk-go/kafkainstance v0.6.0
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.2
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.4
github.com/redhat-developer/app-services-sdk-go/registryinstance v0.3.1
github.com/redhat-developer/app-services-sdk-go/registrymgmt v0.6.1
github.com/redhat-developer/service-binding-operator v0.9.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -640,8 +640,8 @@ github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.5.0 h1:cf+K96kW
github.com/redhat-developer/app-services-sdk-go/connectormgmt v0.5.0/go.mod h1:JAedrXf/qLHd7lpOS+bOFh8nrOpp2j0sg4/VG/1um6c=
github.com/redhat-developer/app-services-sdk-go/kafkainstance v0.6.0 h1:ExEHQaihnPNxN2nKXB0q5nrmSv4p8b3Idzt7TChxv+Q=
github.com/redhat-developer/app-services-sdk-go/kafkainstance v0.6.0/go.mod h1:hMpejngP3BFnifCDH1gKRG9cU9Q4lr0WiQaW7A1LYo4=
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.2 h1:NhvRB9amMDp/iGOlqcf5KdIUebIre7Vgv79xLPDZ7BA=
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.2/go.mod h1:NvNM4Gnw3dPMY6H+fsc1GHWev0ydSGsgjiCP10Bj2/M=
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.4 h1:piT2sSsH+gLDYLObUqRtm5Yd8LYDZ/Fl+nCHv5dIvw0=
github.com/redhat-developer/app-services-sdk-go/kafkamgmt v0.11.4/go.mod h1:NvNM4Gnw3dPMY6H+fsc1GHWev0ydSGsgjiCP10Bj2/M=
github.com/redhat-developer/app-services-sdk-go/registryinstance v0.3.1 h1:xRq5XJzRDs/Z7e/9SDt6zbNRIyesC4LTqN9ajHKwjHo=
github.com/redhat-developer/app-services-sdk-go/registryinstance v0.3.1/go.mod h1:Z/gr/snlpsqYg4vftmcx97vCR3qMQJhALGelDHx4pMA=
github.com/redhat-developer/app-services-sdk-go/registrymgmt v0.6.1 h1:3sUmQ3nAawsYWg7ZCO2Q8HF2J7MW6YA38h/YFL3ao6o=
Expand Down
20 changes: 12 additions & 8 deletions pkg/cmd/generate/build-configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"time"

"github.com/redhat-developer/app-services-cli/pkg/cmd/serviceaccount/svcaccountcmdutil"
"github.com/redhat-developer/app-services-cli/pkg/core/ioutil/icon"
"github.com/redhat-developer/app-services-cli/pkg/core/localize"
"github.com/redhat-developer/app-services-cli/pkg/core/servicecontext"
Expand All @@ -26,12 +27,10 @@ type configValues struct {
}

func createServiceAccount(opts *options, shortDescription string) (*kafkamgmtclient.ServiceAccount, error) {

conn, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return nil, err
}

serviceAccountPayload := kafkamgmtclient.ServiceAccountRequest{Name: shortDescription}

serviceacct, httpRes, err := conn.API().
Expand Down Expand Up @@ -63,11 +62,6 @@ func BuildConfiguration(svcConfig *servicecontext.ServiceConfig, opts *options)
ServiceContext: opts.ServiceContext,
}

cfg, err := opts.Config.Load()
if err != nil {
return err
}

configurations := &configValues{}

var serviceAvailable bool
Expand Down Expand Up @@ -106,9 +100,19 @@ func BuildConfiguration(svcConfig *servicecontext.ServiceConfig, opts *options)
opts.localizer.MustLocalize("serviceAccount.create.log.info.createdSuccessfully", localize.NewEntry("ID", serviceAccount.GetId())),
)

conn, err := opts.Connection(connection.DefaultConfigSkipMasAuth)
if err != nil {
return err
}

providerUrls, err := svcaccountcmdutil.GetProvidersDetails(conn, opts.Context)
if err != nil {
return err
}

configurations.ClientID = serviceAccount.GetClientId()
configurations.ClientSecret = serviceAccount.GetClientSecret()
configurations.TokenURL = cfg.MasAuthURL + "/protocol/openid-connect/token"
configurations.TokenURL = providerUrls.GetTokenUrl()
configurations.Name = configInstanceName

if err = WriteConfig(opts.configType, opts.fileName, configurations); err != nil {
Expand Down
12 changes: 7 additions & 5 deletions pkg/cmd/kafka/create/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,19 @@ func GetValidKafkaSizes(f *factory.Factory,
if desiredInstanceType == DeveloperType {
for _, instanceType := range instanceTypes.GetInstanceTypes() {
if desiredInstanceType == instanceType.GetId() {
for _, instanceSize := range instanceType.GetSizes() {
validSizes = append(validSizes, instanceSize.GetId())
instanceSizes := instanceType.GetSizes()
for i := range instanceSizes {
validSizes = append(validSizes, instanceSizes[i].GetId())
}
}
}
} else {
for _, instanceType := range instanceTypes.GetInstanceTypes() {
if desiredInstanceType == instanceType.GetId() {
for _, instanceSize := range instanceType.GetSizes() {
if instanceSize.GetQuotaConsumed() <= int32(amsType.Quota) {
validSizes = append(validSizes, instanceSize.GetId())
instanceSizes := instanceType.GetSizes()
for i := range instanceSizes {
if instanceSizes[i].GetQuotaConsumed() <= int32(amsType.Quota) {
validSizes = append(validSizes, instanceSizes[i].GetId())
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/cmd/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func runLogin(opts *options) (err error) {
ctx, cancel := context.WithTimeout(context.Background(), build.DefaultLoginTimeout)
defer cancel()

if err = loginExec.Execute(ctx, ssoCfg, masSsoCfg); err != nil {
if err = loginExec.Execute(ctx, ssoCfg, masSsoCfg, gatewayURL.String()); err != nil {
spinner.Stop()
opts.Logger.Info()
if errors.Is(err, context.DeadlineExceeded) {
Expand Down
11 changes: 6 additions & 5 deletions pkg/cmd/serviceaccount/create/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,6 @@ func runCreate(opts *options) error {
if err != nil {
return err
}
cfg, err := opts.Config.Load()
if err != nil {
return err
}

if opts.interactive {
// run the create command interactively
Expand All @@ -134,6 +130,11 @@ func runCreate(opts *options) error {
// create the service account
serviceAccountPayload := kafkamgmtclient.ServiceAccountRequest{Name: opts.shortDescription}

providerUrls, err := svcaccountcmdutil.GetProvidersDetails(conn, opts.Context)
if err != nil {
return err
}

serviceacct, httpRes, err := conn.API().
ServiceAccountMgmt().
CreateServiceAccount(opts.Context).
Expand All @@ -154,7 +155,7 @@ func runCreate(opts *options) error {
creds := &credentials.Credentials{
ClientID: serviceacct.GetClientId(),
ClientSecret: serviceacct.GetClientSecret(),
TokenURL: cfg.MasAuthURL + "/protocol/openid-connect/token",
TokenURL: providerUrls.GetTokenUrl(),
}

// save the credentials to a file
Expand Down
8 changes: 3 additions & 5 deletions pkg/cmd/serviceaccount/resetcredentials/reset_credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ func runResetCredentials(opts *options) (err error) {
if err != nil {
return err
}

if opts.interactive {
err = runInteractivePrompt(opts)
if err != nil {
Expand Down Expand Up @@ -156,15 +157,12 @@ func runResetCredentials(opts *options) (err error) {

opts.Logger.Info(icon.SuccessPrefix(), opts.localizer.MustLocalize("serviceAccount.resetCredentials.log.info.resetSuccess", localize.NewEntry("ID", updatedServiceAccount.GetId())))

cfg, err := opts.Config.Load()
if err != nil {
return err
}
providerUrls, err := svcaccountcmdutil.GetProvidersDetails(conn, opts.Context)

creds := &credentials.Credentials{
ClientID: updatedServiceAccount.GetClientId(),
ClientSecret: updatedServiceAccount.GetClientSecret(),
TokenURL: cfg.MasAuthURL + "/protocol/openid-connect/token",
TokenURL: providerUrls.GetTokenUrl(),
}

// save the credentials to a file
Expand Down
24 changes: 23 additions & 1 deletion pkg/cmd/serviceaccount/svcaccountcmdutil/svcaccount_util.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
package svcaccountcmdutil

import "github.com/redhat-developer/app-services-cli/pkg/cmd/serviceaccount/svcaccountcmdutil/credentials"
import (
"context"

"github.com/redhat-developer/app-services-cli/pkg/cmd/serviceaccount/svcaccountcmdutil/credentials"
"github.com/redhat-developer/app-services-cli/pkg/shared/connection"
kafkamgmtclient "github.com/redhat-developer/app-services-sdk-go/kafkamgmt/apiv1/client"
)

var (
CredentialsOutputFormats = []string{credentials.EnvFormat, credentials.JSONFormat, credentials.PropertiesFormat}
)

// Method fetches authentication details for providers
func GetProvidersDetails(conn connection.Connection, context context.Context) (*kafkamgmtclient.SsoProvider, error) {
providers, httpRes, err := conn.API().
ServiceAccountMgmt().GetSsoProviders(context).Execute()

if httpRes != nil {
defer httpRes.Body.Close()
}

if err != nil {
return nil, err
}

return &providers, err
}
8 changes: 7 additions & 1 deletion pkg/core/auth/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/redhat-developer/app-services-cli/pkg/core/ioutil/iostreams"
"github.com/redhat-developer/app-services-cli/pkg/core/localize"
"github.com/redhat-developer/app-services-cli/pkg/core/logging"
"github.com/redhat-developer/app-services-cli/pkg/shared/hacks"

"github.com/coreos/go-oidc/v3/oidc"
"github.com/phayes/freeport"
Expand All @@ -39,11 +40,16 @@ type SSOConfig struct {
// Execute runs an Authorization Code flow login
// enabling the user to log in to SSO and MAS-SSO in succession
// https://tools.ietf.org/html/rfc6749#section-4.1
func (a *AuthorizationCodeGrant) Execute(ctx context.Context, ssoCfg *SSOConfig, masSSOCfg *SSOConfig) error {
func (a *AuthorizationCodeGrant) Execute(ctx context.Context,
ssoCfg *SSOConfig, masSSOCfg *SSOConfig, apiUrl string) error {
if err := a.loginSSO(ctx, ssoCfg); err != nil {
return err
}

if !hacks.ShouldUseMasSSO(a.Logger, apiUrl) {
return nil
}

masSSOHost := masSSOCfg.AuthURL.Host

a.Logger.Debug(a.Localizer.MustLocalize("login.log.info.loggingInMAS", localize.NewEntry("Host", masSSOHost)))
Expand Down
14 changes: 12 additions & 2 deletions pkg/shared/connection/api/defaultapi/default_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
connectormgmtclient "github.com/redhat-developer/app-services-sdk-go/connectormgmt/apiv1/client"
kafkamgmt "github.com/redhat-developer/app-services-sdk-go/kafkamgmt/apiv1"

"github.com/redhat-developer/app-services-cli/pkg/shared/hacks"
"github.com/redhat-developer/app-services-cli/pkg/shared/kafkautil"

"github.com/redhat-developer/app-services-cli/internal/build"
Expand Down Expand Up @@ -144,10 +145,15 @@ func (a *defaultAPI) KafkaAdmin(instanceID string) (*kafkainstanceclient.APIClie

a.Logger.Debugf("Making request to %v", apiURL.String())

token := a.MasAccessToken
if !hacks.ShouldUseMasSSO(a.Logger, a.ApiURL.String()) {
token = a.AccessToken
}

client := kafkainstance.NewAPIClient(&kafkainstance.Config{
BaseURL: apiURL.String(),
Debug: a.Logger.DebugEnabled(),
HTTPClient: a.CreateOAuthTransport(a.MasAccessToken),
HTTPClient: a.CreateOAuthTransport(token),
UserAgent: a.UserAgent,
})

Expand Down Expand Up @@ -204,11 +210,15 @@ func (a *defaultAPI) ServiceRegistryInstance(instanceID string) (*registryinstan
}

a.Logger.Debugf("Making request to %v", baseURL)
token := a.MasAccessToken
if !hacks.ShouldUseMasSSO(a.Logger, a.ApiURL.String()) {
token = a.AccessToken
}

client := registryinstance.NewAPIClient(&registryinstance.Config{
BaseURL: baseURL,
Debug: a.Logger.DebugEnabled(),
HTTPClient: a.CreateOAuthTransport(a.MasAccessToken),
HTTPClient: a.CreateOAuthTransport(token),
UserAgent: build.DefaultUserAgentPrefix + build.Version,
})

Expand Down
62 changes: 62 additions & 0 deletions pkg/shared/hacks/temp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package hacks

// Temporary hack package
// Nothing to see here

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/redhat-developer/app-services-cli/pkg/core/logging"
kafkamgmtclient "github.com/redhat-developer/app-services-sdk-go/kafkamgmt/apiv1/client"
)

// Temporary hack that we use to determine if
// Our CLI needs to use mas-sso token
func ShouldUseMasSSO(logger logging.Logger, apiUrl string) bool {
req, err := http.NewRequest("GET", apiUrl+"/api/kafkas_mgmt/v1/sso_providers", nil)
if err != nil {
logger.Debug("Error when fetching auth config", err)
return true
}

req = req.WithContext(context.Background())

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

resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.Debug("Error when fetching auth config", err)
return true
}

defer resp.Body.Close()

b, err := io.ReadAll(resp.Body)
if err != nil {
logger.Debug("Error when fetching auth config", err)
return true
}

response := string(b)

// defining a struct instance
var provider *kafkamgmtclient.SsoProvider

responseBytes := []byte(fmt.Sprintf("%v", response))
err = json.Unmarshal(responseBytes, &provider)
if err != nil {
logger.Debug("Error when fetching auth config", err)
return true
}

if provider.GetBaseUrl() == "" {
logger.Debug("Error when fetching auth config", err)
return true
}

return provider.GetName() == "mas_sso"
}

0 comments on commit 9b50176

Please sign in to comment.