-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathlogin.go
More file actions
244 lines (204 loc) · 6.84 KB
/
login.go
File metadata and controls
244 lines (204 loc) · 6.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Package cluster contains commands for interacting with cluster logic of the service directly instead of through the
// REST API exposed via the serve command.
package login
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"github.com/bf2fc6cc711aee1a0c2a/cli/pkg/browser"
"github.com/bf2fc6cc711aee1a0c2a/cli/pkg/connection"
"github.com/bf2fc6cc711aee1a0c2a/cli/pkg/auth/pkce"
"github.com/bf2fc6cc711aee1a0c2a/cli/pkg/config"
"github.com/phayes/freeport"
"golang.org/x/oauth2"
"github.com/coreos/go-oidc"
"github.com/spf13/cobra"
)
var (
devURL = "http://localhost:8000"
productionURL = "https://api.openshift.com"
stagingURL = "https://api.stage.openshift.com"
integrationURL = "https://api-integration.6943.hive-integration.openshiftapps.com"
defaultClientID = "rhoas-cli-prod"
)
const PostLoginPage = `
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Red+Hat+Display&display=swap" rel="stylesheet">
<style>
.content {
font-family: 'Red Hat Display', sans-serif;
margin: auto;
width: 50%;
padding: 10px;
margin-top: 350px;
text-align: center;
}
</style>
<div class="content">
<h1>Logged in to RHOAS. Return to your terminal to begin.</h1>
</div>
`
// When the value of the `--url` option is one of the keys of this map it will be replaced by the
// corresponding value.
var urlAliases = map[string]string{
"production": productionURL,
"prod": productionURL,
"prd": productionURL,
"staging": stagingURL,
"stage": stagingURL,
"stg": stagingURL,
"integration": integrationURL,
"int": integrationURL,
"dev": devURL,
"development": devURL,
}
var args struct {
url string
authURL string
clientID string
insecureSkipTLSVerify bool
}
// NewLoginCmd gets the command that's log the user in
func NewLoginCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Short: "Login to Managed Application Services",
Long: "Login to Managed Application Services in order to manage your services",
RunE: runLogin,
}
cmd.Flags().StringVar(&args.url, "url", stagingURL, "URL of the API gateway. The value can be the complete URL or an alias. The valid aliases are 'production', 'staging', 'integration', 'development' and their shorthands.")
cmd.Flags().BoolVar(&args.insecureSkipTLSVerify, "insecure", false, "Enables insecure communication with the server. This disables verification of TLS certificates and host names.")
cmd.Flags().StringVar(&args.clientID, "client-id", defaultClientID, "OpenID client identifier.")
cmd.Flags().StringVar(&args.authURL, "auth-url", connection.DefaultAuthURL, "SSO Authentication server")
return cmd
}
// nolint
func runLogin(cmd *cobra.Command, _ []string) error {
cfg, _ := config.Load()
cfg.SetInsecure(args.insecureSkipTLSVerify)
cfg.SetClientID(args.clientID)
cfg.SetAuthURL(args.authURL)
// If the value of the `--url` is any of the aliases then replace it with the corresponding
// real URL:
unparsedGatewayURL, ok := urlAliases[args.url]
if !ok {
unparsedGatewayURL = args.url
}
gatewayURL, err := url.ParseRequestURI(unparsedGatewayURL)
if err != nil {
return err
}
if gatewayURL.Scheme != "http" && gatewayURL.Scheme != "https" {
return fmt.Errorf("Scheme missing from URL '%v'. Please add either 'https' or 'https'.", unparsedGatewayURL)
}
tr := createTransport(args.insecureSkipTLSVerify)
httpClient := &http.Client{Transport: tr}
parentCtx, cancel := context.WithCancel(context.Background())
ctx := oidc.ClientContext(parentCtx, httpClient)
provider, err := oidc.NewProvider(ctx, args.authURL)
if err != nil {
return err
}
redirectURLPort, err := freeport.GetFreePort()
if err != nil {
return err
}
redirectURL := url.URL{
Scheme: "http",
Host: fmt.Sprintf("localhost:%v", redirectURLPort),
Path: "sso-redhat-callback",
}
oauthCfg := oauth2.Config{
ClientID: args.clientID,
Endpoint: provider.Endpoint(),
RedirectURL: redirectURL.String(),
Scopes: []string{oidc.ScopeOpenID},
}
oidcCfg := &oidc.Config{
ClientID: oauthCfg.ClientID,
}
verifier := provider.Verifier(oidcCfg)
state, _ := pkce.GenerateVerifier(128)
// PKCE
pkceCodeVerifier, err := pkce.GenerateVerifier(128)
if err != nil {
return err
}
pkceCodeChallenge := pkce.CreateChallenge(pkceCodeVerifier)
authCodeURL := oauthCfg.AuthCodeURL(state, *pkce.GetAuthCodeURLOptions(pkceCodeChallenge)...)
sm := http.NewServeMux()
server := http.Server{
Handler: sm,
Addr: redirectURL.Host,
}
fmt.Fprintln(os.Stderr, "Logging in...")
sm.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, authCodeURL, http.StatusFound)
})
sm.HandleFunc("/sso-redhat-callback", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state {
http.Error(w, "state did not match", http.StatusBadRequest)
return
}
oauthExchangeOpts := []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", pkceCodeVerifier),
oauth2.SetAuthURLParam("grant_type", "authorization_code"),
}
oauth2Token, err := oauthCfg.Exchange(ctx, r.URL.Query().Get("code"), oauthExchangeOpts...)
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 := verifier.Verify(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
}
cfg.SetClientID(args.clientID)
cfg.SetURL(gatewayURL.String())
cfg.SetScopes(oauthCfg.Scopes)
cfg.SetInsecure(args.insecureSkipTLSVerify)
cfg.SetAccessToken(oauth2Token.AccessToken)
cfg.SetRefreshToken(oauth2Token.RefreshToken)
if err = config.Save(cfg); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintln(w, PostLoginPage)
fmt.Fprintln(os.Stderr, "Successfully logged in to RHOAS")
cancel()
})
openBrowserExec, _ := browser.GetOpenBrowserCommand(authCodeURL)
_ = openBrowserExec.Run()
go func() {
if err := server.ListenAndServe(); err != nil {
fmt.Fprintf(os.Stderr, "Error starting server: %v", err)
}
}()
<-parentCtx.Done()
return nil
}
func createTransport(insecure bool) *http.Transport {
// #nosec 402
return &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure},
}
}