diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0fae86dec..7c5ba6572 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ go run ./cmd/rhoas kafka create "test" --provider=aws --region=us-east-1 To use QA environment we need to login using following arguments ```shell -rhoas login --api-gateway=stage --mas-auth-url=stage +rhoas login --api-gateway=stage ``` ### Development features diff --git a/Makefile b/Makefile index ca5f062f5..74e844754 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,6 @@ REPOSITORY_NAME ?= "app-services-cli" CONSTANTS_URL ?= "https://console.redhat.com/apps/application-services/service-constants.json" SSO_REDIRECT_PATH ?= "sso-redhat-callback" -MAS_SSO_REDIRECT_PATH ?= "mas-sso-callback" BUILD_SOURCE ?= "local" # see pkg/cmdutil/constants.go @@ -22,7 +21,6 @@ GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.Dyn GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.DefaultPageSize=$(DEFAULT_PAGE_SIZE) $(GO_LDFLAGS) GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.DefaultPageNumber=$(DEFAULT_PAGE_NUMBER) $(GO_LDFLAGS) GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.SSORedirectPath=$(SSO_REDIRECT_PATH) $(GO_LDFLAGS) -GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.MASSSORedirectPath=$(MAS_SSO_REDIRECT_PATH) $(GO_LDFLAGS) GO_LDFLAGS := -X github.com/redhat-developer/app-services-cli/internal/build.BuildSource=$(BUILD_SOURCE) $(GO_LDFLAGS) BUILDFLAGS := diff --git a/docs/commands/rhoas_login.md b/docs/commands/rhoas_login.md index 1e906f7cc..1100e7546 100644 --- a/docs/commands/rhoas_login.md +++ b/docs/commands/rhoas_login.md @@ -38,7 +38,7 @@ $ rhoas login --token f5cgc... --auth-url string The URL of the SSO Authentication server (default "https://sso.redhat.com/auth/realms/redhat-external") --client-id string OpenID client identifier (default "rhoas-cli-prod") --insecure Allow insecure communication with the server by disabling TLS certificate and host name verification - --mas-auth-url string The URL of the identity.api.openshift.com Authentication server (default "https://identity.api.openshift.com/auth/realms/rhoas") + --mas-auth-url string This flag is no longer valid and will be removed in a future release. --print-sso-url Print the console login URL, which you can use to log in to RHOAS from a different web browser (this is useful if you need to log in with different credentials than the credentials you used in your default web browser) --scope stringArray Override the default OpenID scope (to specify multiple scopes, use a separate --scope for each scope) (default [openid]) -t, --token string Log in using an offline token, which can be obtained at https://console.redhat.com/openshift/token diff --git a/internal/build/build.go b/internal/build/build.go index 96c1923cf..feb5d2f59 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -45,9 +45,6 @@ var ( // SSORedirectPath is the default SSO redirect path SSORedirectPath = "sso-redhat-callback" - // MASSSORedirectPath is the default MAS-SSO redirect path - MASSSORedirectPath = "mas-sso-callback" - // BuildSource is a unique key which indicates the infrastructure on which the binary was built BuildSource = "local" ) @@ -63,8 +60,6 @@ var ( DefaultLoginTimeout = 60 * time.Second OfflineTokenURL = ConsoleURL + "/openshift/token" ProductionAuthURL = "https://sso.redhat.com/auth/realms/redhat-external" - ProductionMasAuthURL = "https://identity.api.openshift.com/auth/realms/rhoas" - StagingMasAuthURL = "https://identity.api.stage.openshift.com/auth/realms/rhoas" ) func init() { diff --git a/internal/mockutil/mockutil.go b/internal/mockutil/mockutil.go index ef7329a75..eb528218d 100644 --- a/internal/mockutil/mockutil.go +++ b/internal/mockutil/mockutil.go @@ -60,8 +60,6 @@ func NewConnectionMock(conn *kcconnection.Connection, apiClient *kafkamgmtclient cfg.AccessToken = "" cfg.RefreshToken = "" - cfg.MasAccessToken = "" - cfg.MasRefreshToken = "" return conn.Config.Save(cfg) }, diff --git a/pkg/cmd/login/login.go b/pkg/cmd/login/login.go index 2fff1f179..d79d1e53f 100644 --- a/pkg/cmd/login/login.go +++ b/pkg/cmd/login/login.go @@ -17,7 +17,6 @@ import ( "github.com/redhat-developer/app-services-cli/pkg/core/ioutil/spinner" "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/connection" "github.com/redhat-developer/app-services-cli/pkg/shared/connection/kcconnection" "github.com/redhat-developer/app-services-cli/pkg/shared/factory" @@ -45,15 +44,6 @@ var authURLAliases = map[string]string{ "stage": build.ProductionAuthURL, } -// When the value of the `--mas-auth-url` option is one of the keys of this map it will be replaced by the -// corresponding value. -var masAuthURLAliases = map[string]string{ - "production": build.ProductionMasAuthURL, - "prod": build.ProductionMasAuthURL, - "staging": build.StagingMasAuthURL, - "stage": build.StagingMasAuthURL, -} - type options struct { Config config.IConfig Logger logging.Logger @@ -64,7 +54,7 @@ type options struct { url string authURL string - masAuthURL string + deprecatedUrl string clientID string scopes []string insecureSkipTLSVerify bool @@ -106,7 +96,7 @@ func NewLoginCmd(f *factory.Factory) *cobra.Command { cmd.Flags().BoolVar(&opts.insecureSkipTLSVerify, "insecure", false, opts.localizer.MustLocalize("login.flag.insecure")) cmd.Flags().StringVar(&opts.clientID, "client-id", build.DefaultClientID, opts.localizer.MustLocalize("login.flag.clientId")) cmd.Flags().StringVar(&opts.authURL, "auth-url", build.ProductionAuthURL, opts.localizer.MustLocalize("login.flag.authUrl")) - cmd.Flags().StringVar(&opts.masAuthURL, "mas-auth-url", build.ProductionMasAuthURL, opts.localizer.MustLocalize("login.flag.masAuthUrl")) + cmd.Flags().StringVar(&opts.deprecatedUrl, "mas-auth-url", "", opts.localizer.MustLocalize("login.flag.masAuthUrl")) cmd.Flags().BoolVar(&opts.printURL, "print-sso-url", false, opts.localizer.MustLocalize("login.flag.printSsoUrl")) cmd.Flags().StringArrayVar(&opts.scopes, "scope", kcconnection.DefaultScopes, opts.localizer.MustLocalize("login.flag.scope")) cmd.Flags().StringVarP(&opts.offlineToken, "token", "t", "", opts.localizer.MustLocalize("login.flag.token", localize.NewEntry("OfflineTokenURL", build.OfflineTokenURL))) @@ -127,12 +117,6 @@ func runLogin(opts *options) (err error) { } opts.authURL = authURL.String() - masAuthURL, err := getURLFromAlias(opts.masAuthURL, masAuthURLAliases, opts.localizer) - if err != nil { - return err - } - opts.masAuthURL = masAuthURL.String() - // log in to SSO spinner := spinner.New(opts.IO.ErrOut, opts.localizer) spinner.SetLocalizedSuffix("login.log.info.loggingIn") @@ -158,16 +142,11 @@ func runLogin(opts *options) (err error) { RedirectPath: build.SSORedirectPath, } - masSsoCfg := &login.SSOConfig{ - AuthURL: masAuthURL, - RedirectPath: build.MASSSORedirectPath, - } - // Creating a global context with timeout ctx, cancel := context.WithTimeout(context.Background(), build.DefaultLoginTimeout) defer cancel() - if err = loginExec.Execute(ctx, ssoCfg, masSsoCfg, gatewayURL.String()); err != nil { + if err = loginExec.Execute(ctx, ssoCfg, gatewayURL.String()); err != nil { spinner.Stop() opts.Logger.Info() if errors.Is(err, context.DeadlineExceeded) { @@ -196,7 +175,6 @@ func runLogin(opts *options) (err error) { cfg.Insecure = opts.insecureSkipTLSVerify cfg.ClientID = opts.clientID cfg.AuthURL = opts.authURL - cfg.MasAuthURL = opts.masAuthURL cfg.Scopes = opts.scopes if err = opts.Config.Save(cfg); err != nil { @@ -229,18 +207,13 @@ func loginWithOfflineToken(opts *options) (err error) { cfg.Insecure = opts.insecureSkipTLSVerify cfg.ClientID = opts.clientID cfg.AuthURL = opts.authURL - cfg.MasAuthURL = opts.masAuthURL cfg.Scopes = opts.scopes cfg.RefreshToken = opts.offlineToken - // remove MAS-SSO tokens, as this does not support token login - cfg.MasAccessToken = "" - cfg.MasRefreshToken = "" if err = opts.Config.Save(cfg); err != nil { return err } - _, err = opts.Connection(connection.DefaultConfigSkipMasAuth) return err } diff --git a/pkg/core/auth/login/login.go b/pkg/core/auth/login/login.go index 6b6f78b85..592afaa25 100644 --- a/pkg/core/auth/login/login.go +++ b/pkg/core/auth/login/login.go @@ -13,11 +13,9 @@ 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" - "github.com/redhat-developer/app-services-cli/static" "golang.org/x/oauth2" ) @@ -38,37 +36,12 @@ 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, apiUrl string) error { + ssoCfg *SSOConfig, apiUrl string) error { if err := a.loginSSO(ctx, ssoCfg); err != nil { return err } - - if !hacks.ShouldUseMasSSO(a.Logger, apiUrl) { - cfg, err := a.Config.Load() - if err != nil { - return err - } - cfg.MasAccessToken = "" - cfg.MasRefreshToken = "" - err = a.Config.Save(cfg) - if err != nil { - return err - } - return nil - } - - masSSOHost := masSSOCfg.AuthURL.Host - - a.Logger.Debug(a.Localizer.MustLocalize("login.log.info.loggingInMAS", localize.NewEntry("Host", masSSOHost))) - // log in to MAS-SSO - if err := a.loginMAS(ctx, masSSOCfg); err != nil { - return err - } - a.Logger.Debug(a.Localizer.MustLocalize("login.log.info.loggedInMAS", localize.NewEntry("Host", masSSOHost))) - return nil } @@ -123,8 +96,6 @@ func (a *AuthorizationCodeGrant) loginSSO(ctx context.Context, cfg *SSOConfig) e http.Redirect(w, r, authCodeURL, http.StatusFound) }) - sm.Handle("/static/", createStaticHTTPHandler()) - authURL, err := url.Parse(cfg.AuthURL.String()) if err != nil { return err @@ -158,85 +129,6 @@ func (a *AuthorizationCodeGrant) loginSSO(ctx context.Context, cfg *SSOConfig) e return nil } -// log in to MAS-SSO -func (a *AuthorizationCodeGrant) loginMAS(ctx context.Context, cfg *SSOConfig) error { - a.Logger.Debug("Logging into", cfg.AuthURL, "\n") - - clientCtx, cancel := createClientContext(ctx, a.HTTPClient) - defer cancel() - provider, err := oidc.NewProvider(ctx, cfg.AuthURL.String()) - if err != nil { - return err - } - - redirectURL, redirectURLPort, err := createRedirectURL(cfg.RedirectPath) - if err != nil { - return err - } - - oauthConfig := &oauth2.Config{ - ClientID: a.ClientID, - Endpoint: provider.Endpoint(), - RedirectURL: redirectURL.String(), - Scopes: a.Scopes, - } - - oidcConfig := &oidc.Config{ - ClientID: a.ClientID, - } - - // Configure PKCE challenge and verifier - // https://tools.ietf.org/html/rfc7636 - verifier := provider.Verifier(oidcConfig) - state, _ := pkce.GenerateVerifier(128) - pkceCodeVerifier, err := pkce.GenerateVerifier(128) - if err != nil { - return err - } - pkceCodeChallenge := pkce.CreateChallenge(pkceCodeVerifier) - - authCodeURL := oauthConfig.AuthCodeURL(state, *pkce.GetAuthCodeURLOptions(pkceCodeChallenge)...) - a.Logger.Debug("Opening Authorization URL:", authCodeURL) - a.Logger.Debug() - - sm := http.NewServeMux() - server := http.Server{ - Handler: sm, - Addr: redirectURL.Host, - } - - sm.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, authCodeURL, http.StatusFound) - }) - - sm.Handle("/static/", createStaticHTTPHandler()) - - // HTTP handler for the redirect page - sm.Handle("/"+redirectURL.Path, &masRedirectPageHandler{ - CancelContext: cancel, - Ctx: clientCtx, - Port: redirectURLPort, - Config: a.Config, - Logger: a.Logger, - AuthURL: cfg.AuthURL, - IO: a.IO, - ServerAddr: server.Addr, - Oauth2Config: oauthConfig, - State: state, - TokenVerifier: verifier, - Localizer: a.Localizer, - AuthOptions: []oauth2.AuthCodeOption{ - oauth2.SetAuthURLParam("code_verifier", pkceCodeVerifier), - oauth2.SetAuthURLParam("grant_type", "authorization_code"), - }, - }) - - a.openBrowser(authCodeURL, redirectURL) - a.startServer(clientCtx, &server) - - return nil -} - func (a *AuthorizationCodeGrant) openBrowser(authCodeURL string, redirectURL *url.URL) { if a.PrintURL { a.Logger.Info(a.Localizer.MustLocalize("login.log.info.openSSOUrl"), "\n") @@ -291,8 +183,3 @@ func (a *AuthorizationCodeGrant) printAuthURLFallback(authCodeURL string, redire a.Logger.Debug("Error opening browser:", err, "\nPrinting Auth URL to console instead") a.openBrowser(authCodeURL, redirectURL) } - -func createStaticHTTPHandler() http.Handler { - staticFs := http.FileServer(http.FS(static.ImagesFS())) - return http.StripPrefix("/static", staticFs) -} diff --git a/pkg/core/auth/login/mas_sso_redirect_handler.go b/pkg/core/auth/login/mas_sso_redirect_handler.go deleted file mode 100644 index 2eaeb28ff..000000000 --- a/pkg/core/auth/login/mas_sso_redirect_handler.go +++ /dev/null @@ -1,101 +0,0 @@ -package login - -import ( - "context" - "github.com/redhat-developer/app-services-cli/pkg/core/config" - "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" - - // embed static HTML file - _ "embed" - "encoding/json" - "fmt" - "net/http" - "net/url" - "os" - - "github.com/coreos/go-oidc/v3/oidc" - "golang.org/x/oauth2" -) - -//go:embed static/mas-sso-redirect-page.html -var masSSOredirectHTMLPage string - -// handler for the MAS-SSO redirect page -type masRedirectPageHandler struct { - IO *iostreams.IOStreams - Config config.IConfig - Logger logging.Logger - ServerAddr string - Port int - AuthURL *url.URL - AuthOptions []oauth2.AuthCodeOption - State string - Oauth2Config *oauth2.Config - Ctx context.Context - TokenVerifier *oidc.IDTokenVerifier - CancelContext context.CancelFunc - Localizer localize.Localizer -} - -// nolint:funlen -func (h *masRedirectPageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - logger := h.Logger - - callbackURL := fmt.Sprintf("%v%v", h.ServerAddr, r.URL.String()) - logger.Debug("Redirected to callback URL:", callbackURL) - logger.Debug() - - if r.URL.Query().Get("state") != h.State { - http.Error(w, "state did not match", http.StatusBadRequest) - return - } - - // nolint:govet - oauth2Token, err := h.Oauth2Config.Exchange(h.Ctx, r.URL.Query().Get("code"), h.AuthOptions...) - if err != nil { - http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError) - return - } - rawIDToken, ok := oauth2Token.Extra("id_token").(string) - if !ok { - http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError) - return - } - idToken, err := h.TokenVerifier.Verify(h.Ctx, rawIDToken) - if err != nil { - http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError) - return - } - - resp := struct { - OAuth2Token *oauth2.Token - IDTokenClaims *json.RawMessage // ID Token payload is just JSON. - }{oauth2Token, new(json.RawMessage)} - - if err = idToken.Claims(&resp.IDTokenClaims); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, masSSOredirectHTMLPage) - - cfg, err := h.Config.Load() - if err != nil { - logger.Error(err) - os.Exit(1) - } - // save the received tokens to the user's config - cfg.MasAccessToken = oauth2Token.AccessToken - cfg.MasRefreshToken = oauth2Token.RefreshToken - - if err = h.Config.Save(cfg); err != nil { - logger.Error(err) - os.Exit(1) - } - - h.CancelContext() -} diff --git a/pkg/core/auth/login/static/mas-sso-redirect-page.html b/pkg/core/auth/login/static/mas-sso-redirect-page.html deleted file mode 100644 index 516e49bea..000000000 --- a/pkg/core/auth/login/static/mas-sso-redirect-page.html +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/pkg/core/auth/login/static/sso-redirect-page.html b/pkg/core/auth/login/static/sso-redirect-page.html index 1387bf74c..b63316c8e 100644 --- a/pkg/core/auth/login/static/sso-redirect-page.html +++ b/pkg/core/auth/login/static/sso-redirect-page.html @@ -3,13 +3,38 @@ %v -
- Logo + + + + + + + + + + +

%v

%v
diff --git a/pkg/core/config/type.go b/pkg/core/config/type.go index ce143b628..39b15bb71 100644 --- a/pkg/core/config/type.go +++ b/pkg/core/config/type.go @@ -12,19 +12,16 @@ type IConfig interface { // Config is a type which describes the properties which can be in the config type Config struct { - AccessToken string `json:"access_token,omitempty" doc:"Bearer access token."` - RefreshToken string `json:"refresh_token,omitempty" doc:"Offline or refresh token."` - MasAuthURL string `json:"mas_auth_url,omitempty"` - MasAccessToken string `json:"mas_access_token,omitempty"` - MasRefreshToken string `json:"mas_refresh_token,omitempty"` - Services ServiceConfigMap `json:"services,omitempty"` - APIUrl string `json:"api_url,omitempty" doc:"URL of the API gateway. The value can be the complete URL or an alias. The valid aliases are 'production', 'staging' and 'integration'."` - AuthURL string `json:"auth_url,omitempty" doc:"URL of the authentication server"` - ClientID string `json:"client_id,omitempty" doc:"OpenID client identifier."` - Insecure bool `json:"insecure,omitempty" doc:"Enables insecure communication with the server. This disables verification of TLS certificates and host names."` - Scopes []string `json:"scopes,omitempty" doc:"OpenID scope. If this option is used it will replace completely the default scopes. Can be repeated multiple times to specify multiple scopes."` - Telemetry string `json:"telemetry,omitempty" doc:"Flag used to enable telemetry for user."` - LastUpdated int64 `json:"last_updated,omitempty" doc:"Timestamp of the last update cli"` + AccessToken string `json:"access_token,omitempty" doc:"Bearer access token."` + RefreshToken string `json:"refresh_token,omitempty" doc:"Offline or refresh token."` + Services ServiceConfigMap `json:"services,omitempty"` + APIUrl string `json:"api_url,omitempty" doc:"URL of the API gateway. The value can be the complete URL or an alias. The valid aliases are 'production', 'staging' and 'integration'."` + AuthURL string `json:"auth_url,omitempty" doc:"URL of the authentication server"` + ClientID string `json:"client_id,omitempty" doc:"OpenID client identifier."` + Insecure bool `json:"insecure,omitempty" doc:"Enables insecure communication with the server. This disables verification of TLS certificates and host names."` + Scopes []string `json:"scopes,omitempty" doc:"OpenID scope. If this option is used it will replace completely the default scopes. Can be repeated multiple times to specify multiple scopes."` + Telemetry string `json:"telemetry,omitempty" doc:"Flag used to enable telemetry for user."` + LastUpdated int64 `json:"last_updated,omitempty" doc:"Timestamp of the last update cli"` } // ServiceConfigMap is a map of configs for the application services diff --git a/pkg/core/localize/locales/en/cmd/login.en.toml b/pkg/core/localize/locales/en/cmd/login.en.toml index 30152bf38..1c1ec3f9d 100644 --- a/pkg/core/localize/locales/en/cmd/login.en.toml +++ b/pkg/core/localize/locales/en/cmd/login.en.toml @@ -44,8 +44,7 @@ description = 'Description for the --auth-url flag' one = "The URL of the SSO Authentication server" [login.flag.masAuthUrl] -description = 'Description for the --auth-url flag' -one = "The URL of the identity.api.openshift.com Authentication server" +one = "This flag is no longer valid and will be removed in a future release." [login.flag.token] one = "Log in using an offline token, which can be obtained at {{.OfflineTokenURL}}" @@ -104,12 +103,6 @@ one = 'Logging in...' [login.log.info.loggedIn] one = 'Logged in successfully' -[login.log.info.loggingInMAS] -one = 'Logging in to {{.Host}}...' - -[login.log.info.loggedInMAS] -one = 'Logged in successfully to {{.Host}}' - [login.error.noRealmInURL] one = 'the authentication URL is missing a realm' diff --git a/pkg/core/localize/locales/en/connection.en.toml b/pkg/core/localize/locales/en/connection.en.toml index 4268f41e1..f76e45bda 100644 --- a/pkg/core/localize/locales/en/connection.en.toml +++ b/pkg/core/localize/locales/en/connection.en.toml @@ -1,8 +1,5 @@ [connection.error.notLoggedInError] one = 'not logged in. Run "rhoas login" to authenticate' -[connection.error.notLoggedInMASError] -one = 'not logged in to identity.api.openshift.com. Run "rhoas login" to authenticate. Note: token-based login is not supported by the Kafka "topic" and "consumer-group" subcommands.' - [connection.error.sessionExpiredError] one = 'session expired. Run "rhoas login" to authenticate' \ No newline at end of file diff --git a/pkg/shared/connection/api/api.go b/pkg/shared/connection/api/api.go index 66a45efd9..7d2568f5b 100644 --- a/pkg/shared/connection/api/api.go +++ b/pkg/shared/connection/api/api.go @@ -30,11 +30,10 @@ type API interface { } type Config struct { - AccessToken string - MasAccessToken string - ApiURL *url.URL - ConsoleURL *url.URL - UserAgent string - HTTPClient *http.Client - Logger logging.Logger + AccessToken string + ApiURL *url.URL + ConsoleURL *url.URL + UserAgent string + HTTPClient *http.Client + Logger logging.Logger } diff --git a/pkg/shared/connection/api/defaultapi/default_client.go b/pkg/shared/connection/api/defaultapi/default_client.go index 42a0aadf2..ff38ba3cb 100644 --- a/pkg/shared/connection/api/defaultapi/default_client.go +++ b/pkg/shared/connection/api/defaultapi/default_client.go @@ -11,7 +11,6 @@ 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" @@ -127,10 +126,7 @@ func (a *defaultAPI) KafkaAdmin(instanceID string) (*kafkainstanceclient.APIClie apiURL := kafkaInstance.GetAdminApiServerUrl() a.Logger.Debugf("Making request to %v", apiURL) - token := a.MasAccessToken - if !hacks.ShouldUseMasSSO(a.Logger, a.ApiURL.String()) { - token = a.AccessToken - } + token := a.AccessToken client := kafkainstance.NewAPIClient(&kafkainstance.Config{ BaseURL: apiURL, @@ -192,10 +188,8 @@ 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 - } + + token := a.AccessToken client := registryinstance.NewAPIClient(®istryinstance.Config{ BaseURL: baseURL, diff --git a/pkg/shared/connection/connection.go b/pkg/shared/connection/connection.go index d96f5a496..23fab41ab 100644 --- a/pkg/shared/connection/connection.go +++ b/pkg/shared/connection/connection.go @@ -6,21 +6,19 @@ import ( "github.com/redhat-developer/app-services-cli/pkg/shared/connection/api" ) +// FIXLATER This entire class can be removed however it should be done +// after connectors commands are finished thus we do not have many conflicts. type Config struct { - RequireAuth bool - RequireMASAuth bool + RequireAuth bool } -// DefaultConfigSkipMasAuth is used when running commands which do not require authenticatation with MAS-SSO +// DefaultConfigSkipMasAuth is used when running all commads var DefaultConfigSkipMasAuth = &Config{ - RequireAuth: true, - RequireMASAuth: false, + RequireAuth: true, } -// DefaultConfigRequireMasAuth is used when running commands which must authenticate with MAS-SSO var DefaultConfigRequireMasAuth = &Config{ - RequireAuth: true, - RequireMASAuth: true, + RequireAuth: true, } // Connection is an interface which defines methods for interacting diff --git a/pkg/shared/connection/kcconnection/builder.go b/pkg/shared/connection/kcconnection/builder.go index c034036c7..8254695be 100644 --- a/pkg/shared/connection/kcconnection/builder.go +++ b/pkg/shared/connection/kcconnection/builder.go @@ -28,13 +28,10 @@ type ConnectionBuilder struct { disableKeepAlives bool accessToken string refreshToken string - masAccessToken string - masRefreshToken string clientID string scopes []string apiURL string authURL string - masAuthURL string consoleURL string config config.IConfig logger logging.Logger @@ -53,6 +50,11 @@ func NewConnectionBuilder() *ConnectionBuilder { return &ConnectionBuilder{} } +func (b *ConnectionBuilder) WithURL(url string) *ConnectionBuilder { + b.apiURL = url + return b +} + func (b *ConnectionBuilder) WithAccessToken(accessToken string) *ConnectionBuilder { b.accessToken = accessToken return b @@ -63,16 +65,6 @@ func (b *ConnectionBuilder) WithRefreshToken(refreshToken string) *ConnectionBui return b } -func (b *ConnectionBuilder) WithMASAccessToken(accessToken string) *ConnectionBuilder { - b.masAccessToken = accessToken - return b -} - -func (b *ConnectionBuilder) WithMASRefreshToken(refreshToken string) *ConnectionBuilder { - b.masRefreshToken = refreshToken - return b -} - func (b *ConnectionBuilder) WithTrustedCAs(value *x509.CertPool) *ConnectionBuilder { b.trustedCAs = value return b @@ -93,11 +85,6 @@ func (b *ConnectionBuilder) WithLogger(logger logging.Logger) *ConnectionBuilder return b } -func (b *ConnectionBuilder) WithURL(url string) *ConnectionBuilder { - b.apiURL = url - return b -} - func (b *ConnectionBuilder) WithConsoleURL(url string) *ConnectionBuilder { b.consoleURL = url return b @@ -108,11 +95,6 @@ func (b *ConnectionBuilder) WithAuthURL(authURL string) *ConnectionBuilder { return b } -func (b *ConnectionBuilder) WithMASAuthURL(authURL string) *ConnectionBuilder { - b.masAuthURL = authURL - return b -} - func (b *ConnectionBuilder) WithClientID(clientID string) *ConnectionBuilder { b.clientID = clientID return b @@ -185,12 +167,6 @@ func (b *ConnectionBuilder) BuildContext(ctx context.Context) (connection *Conne Logger: b.logger, } - masTk := token.Token{ - AccessToken: b.masAccessToken, - RefreshToken: b.masRefreshToken, - Logger: b.logger, - } - tokenIsValid, err := tkn.IsValid() if err != nil { return nil, err @@ -226,12 +202,6 @@ func (b *ConnectionBuilder) BuildContext(ctx context.Context) (connection *Conne return } - masAuthURL, err := url.Parse(b.masAuthURL) - if err != nil { - err = AuthErrorf("unable to parse Auth URL '%s': %w", b.masAuthURL, err) - return - } - consoleURL, err := url.Parse(b.consoleURL) if err != nil { err = fmt.Errorf("unable to parse Console URL '%s': %w", b.consoleURL, err) @@ -260,19 +230,6 @@ func (b *ConnectionBuilder) BuildContext(ctx context.Context) (connection *Conne restyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: b.insecure}) keycloak.SetRestyClient(&restyClient) - baseMasAuthURL := fmt.Sprintf("%v://%v", masAuthURL.Scheme, masAuthURL.Host) - masKc := gocloak.NewClient(baseMasAuthURL) - masRestyClient := *keycloak.RestyClient() - - _, masKcRealm, ok := SplitKeycloakRealmURL(masAuthURL) - if !ok { - return nil, fmt.Errorf("unable to get realm name from Auth URL: '%s'", b.masAuthURL) - } - - // #nosec 402 - restyClient.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: b.insecure}) - masKc.SetRestyClient(&masRestyClient) - connection = &Connection{ insecure: b.insecure, trustedCAs: b.trustedCAs, @@ -282,11 +239,8 @@ func (b *ConnectionBuilder) BuildContext(ctx context.Context) (connection *Conne apiURL: apiURL, defaultHTTPClient: client, keycloakClient: keycloak, - masKeycloakClient: masKc, Token: &tkn, - MASToken: &masTk, defaultRealm: kcRealm, - masRealm: masKcRealm, logger: b.logger, Config: b.config, connectionConfig: b.connectionConfig, diff --git a/pkg/shared/connection/kcconnection/keycloak_connection.go b/pkg/shared/connection/kcconnection/keycloak_connection.go index 2624dea51..ba9ed7fb4 100644 --- a/pkg/shared/connection/kcconnection/keycloak_connection.go +++ b/pkg/shared/connection/kcconnection/keycloak_connection.go @@ -31,14 +31,11 @@ type Connection struct { defaultHTTPClient *http.Client clientID string Token *token.Token - MASToken *token.Token scopes []string keycloakClient gocloak.GoCloak - masKeycloakClient gocloak.GoCloak apiURL *url.URL consoleURL *url.URL defaultRealm string - masRealm string logger logging.Logger Config config.IConfig connectionConfig *connection.Config @@ -75,25 +72,6 @@ func (c *Connection) RefreshTokens(ctx context.Context) (err error) { } } - if c.connectionConfig.RequireMASAuth && c.MASToken.RefreshToken != "" { - c.logger.Debug("Refreshing MAS SSO tokens") - // nolint:govet - refreshedMasTk, err := c.masKeycloakClient.RefreshToken(ctx, c.MASToken.RefreshToken, c.clientID, "", c.masRealm) - if err != nil { - return &MasAuthError{err} - } - if refreshedMasTk.AccessToken != c.MASToken.AccessToken { - c.MASToken.AccessToken = refreshedMasTk.AccessToken - cfg.MasAccessToken = refreshedMasTk.AccessToken - cfgChanged = true - } - if refreshedMasTk.RefreshToken != c.MASToken.RefreshToken { - c.MASToken.RefreshToken = refreshedMasTk.RefreshToken - cfg.MasRefreshToken = refreshedMasTk.RefreshToken - cfgChanged = true - } - } - if !cfgChanged { return nil } @@ -115,17 +93,8 @@ func (c *Connection) Logout(ctx context.Context) (err error) { return &AuthError{err} } - if c.MASToken.RefreshToken != "" { - err = c.masKeycloakClient.Logout(ctx, c.clientID, "", c.masRealm, c.MASToken.RefreshToken) - if err != nil { - return &AuthError{err} - } - } - c.Token.AccessToken = "" c.Token.RefreshToken = "" - c.MASToken.AccessToken = "" - c.MASToken.RefreshToken = "" cfg, err := c.Config.Load() if err != nil { @@ -134,8 +103,6 @@ func (c *Connection) Logout(ctx context.Context) (err error) { cfg.AccessToken = "" cfg.RefreshToken = "" - cfg.MasAccessToken = "" - cfg.MasRefreshToken = "" return c.Config.Save(cfg) } @@ -143,13 +110,12 @@ func (c *Connection) Logout(ctx context.Context) (err error) { // API Creates a new API type which is a single type for multiple APIs func (c *Connection) API() api.API { apiClient := defaultapi.New(&api.Config{ - HTTPClient: c.defaultHTTPClient, - UserAgent: build.DefaultUserAgentPrefix + build.Version, - MasAccessToken: c.MASToken.AccessToken, - AccessToken: c.Token.AccessToken, - ApiURL: c.apiURL, - ConsoleURL: c.consoleURL, - Logger: c.logger, + HTTPClient: c.defaultHTTPClient, + UserAgent: build.DefaultUserAgentPrefix + build.Version, + AccessToken: c.Token.AccessToken, + ApiURL: c.apiURL, + ConsoleURL: c.consoleURL, + Logger: c.logger, }) return apiClient diff --git a/pkg/shared/factory/defaultfactory/default.go b/pkg/shared/factory/defaultfactory/default.go index 54b22b14b..fdde33bcc 100644 --- a/pkg/shared/factory/defaultfactory/default.go +++ b/pkg/shared/factory/defaultfactory/default.go @@ -50,12 +50,6 @@ func New(localizer localize.Localizer) *factory.Factory { if cfg.RefreshToken != "" { builder.WithRefreshToken(cfg.RefreshToken) } - if cfg.MasAccessToken != "" { - builder.WithMASAccessToken(cfg.MasAccessToken) - } - if cfg.MasRefreshToken != "" { - builder.WithMASRefreshToken(cfg.MasRefreshToken) - } if cfg.ClientID != "" { builder.WithClientID(cfg.ClientID) } @@ -70,11 +64,6 @@ func New(localizer localize.Localizer) *factory.Factory { } builder.WithAuthURL(cfg.AuthURL) - if cfg.MasAuthURL == "" { - cfg.MasAuthURL = build.ProductionMasAuthURL - } - builder.WithMASAuthURL(cfg.MasAuthURL) - builder.WithConsoleURL(build.ConsoleURL) builder.WithInsecure(cfg.Insecure) diff --git a/pkg/shared/hacks/temp.go b/pkg/shared/hacks/temp.go deleted file mode 100644 index d49992343..000000000 --- a/pkg/shared/hacks/temp.go +++ /dev/null @@ -1,69 +0,0 @@ -package hacks - -// Temporary hack package -// Nothing to see here - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - - "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 { - finalUrl := apiUrl + "/api/kafkas_mgmt/v1/sso_providers" - externalUrl := os.Getenv("RHOAS_CUSTOM_SSO_PROVIDER_URL") - if externalUrl != "" { - finalUrl = externalUrl - } - - req, err := http.NewRequest("GET", finalUrl, 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" -} diff --git a/static/img/favicon.ico b/static/img/favicon.ico deleted file mode 100644 index c1f6359ea..000000000 Binary files a/static/img/favicon.ico and /dev/null differ diff --git a/static/img/logo.svg b/static/img/logo.svg deleted file mode 100644 index d2b56aade..000000000 --- a/static/img/logo.svg +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - diff --git a/static/static.go b/static/static.go deleted file mode 100644 index 98ebfad10..000000000 --- a/static/static.go +++ /dev/null @@ -1,14 +0,0 @@ -package static - -import ( - "embed" - "io/fs" -) - -//go:embed img/* -var images embed.FS - -// ImagesFS returns the embedded images assets -func ImagesFS() fs.FS { - return images -}