This repository has been archived by the owner on Sep 27, 2020. It is now read-only.
/
main.go
274 lines (229 loc) · 8.61 KB
/
main.go
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package main
import (
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
)
var (
uaaURL = flag.String("uaa.url", "", "UAA URL.")
uaaClientID = flag.String("uaa.client_id", "cf", "UAA Client ID (must have an 'openid' scope).")
uaaClientSecret = flag.String("uaa.client_secret", "", "UAA Client Secret.")
uaaUsername = flag.String("uaa.username", "", "UAA Username to generate credentials for.")
uaaPassword = flag.String("uaa.password", "", "UAA Password to generate credentials for.")
uaaSkipSSLValidation = flag.Bool("uaa.skip_ssl_verify", false, "Disable UAA SSL Verify.")
)
type OIDCInfo struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported"`
TokenEndpointAuthSigningAlgValuesSupported []string `json:"token_endpoint_auth_signing_alg_values_supported"`
UserinfoEndpoint string `json:"userinfo_endpoint"`
JWKSURI string `json:"jwks_uri"`
ScopesSupported []string `json:"scopes_supported"`
ResponseTypesSupported []string `json:"response_types_supported"`
SubjectTypesSupported []string `json:"subject_types_supported"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported"`
IDTokenEncryptionAlgValuesSupported []string `json:"id_token_encryption_alg_values_supported"`
ClaimTypesSupported []string `json:"claim_types_supported"`
ClaimSupported []string `json:"claims_supported"`
ClaimsParameterSupported bool `json:"claims_parameter_supported"`
ServiceDocumentation string `json:"service_documentation"`
UILocalesSupported []string `json:"ui_locales_supported"`
}
type AuthToken struct {
IDToken string `json:"id_token"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
JTI string `json:"jti"`
}
type UserInfo struct {
UserID string `json:"user_id"`
Sub string `json:"sub"`
UserName string `json:"user_name"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
PreviousLogonTime int `json:"previous_logon_time"`
Name string `json:"name"`
}
type Kubeconfig struct {
AuthInfos []NamedAuthInfo `yaml:"users"`
}
type NamedAuthInfo struct {
Name string `yaml:"name"`
AuthInfo *AuthInfo `yaml:"user"`
}
type AuthInfo struct {
AuthProvider *AuthProvider `yaml:"auth-provider"`
}
type AuthProvider struct {
Name string `yaml:"name"`
AuthProviderConfig *AuthProviderConfig `yaml:"config"`
}
type AuthProviderConfig struct {
IdpIssuerURL string `yaml:"idp-issuer-url"`
ClientID string `yaml:"client-id"`
ClientSecret string `yaml:"client-secret"`
IDToken string `yaml:"id-token"`
RefreshToken string `yaml:"refresh-token"`
}
func httpClient(skipSSLValidation bool) *http.Client {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: skipSSLValidation,
},
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
KeepAlive: 30 * time.Second,
}).DialContext,
}
return &http.Client{Transport: tr}
}
func getOIDCInfo(uaaURL string, skipSSLValidation bool) (*OIDCInfo, error) {
oidcInfo := &OIDCInfo{}
uri, err := url.Parse(uaaURL)
if err != nil {
return oidcInfo, fmt.Errorf("Error parsing UAA URL: %s", err)
}
request, err := http.NewRequest("GET", fmt.Sprintf("%s/.well-known/openid-configuration", uri), nil)
if err != nil {
return oidcInfo, fmt.Errorf("Error generating request: %s", err)
}
request.Header.Set("Content-Type", "application/json")
response, err := httpClient(skipSSLValidation).Do(request)
if err != nil {
return oidcInfo, fmt.Errorf("Request error: %s", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return oidcInfo, fmt.Errorf("Received a %s status code", response.Status)
}
if err = json.NewDecoder(response.Body).Decode(oidcInfo); err != nil {
return oidcInfo, fmt.Errorf("Error decoding response: %s", err)
}
return oidcInfo, nil
}
func getAuthToken(tokenEndpoint string, skipSSLValidation bool, clientID string, clientSecret string, username string, password string) (*AuthToken, error) {
authToken := &AuthToken{}
requestBody := url.Values{}
requestBody.Set("username", username)
requestBody.Set("password", password)
requestBody.Set("grant_type", "password")
requestBody.Set("response_type", "id_token")
request, err := http.NewRequest("POST", tokenEndpoint, strings.NewReader(requestBody.Encode()))
if err != nil {
return authToken, fmt.Errorf("Error generating request: %s", err)
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetBasicAuth(clientID, clientSecret)
response, err := httpClient(skipSSLValidation).Do(request)
if err != nil {
return authToken, fmt.Errorf("Request error: %s", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return authToken, fmt.Errorf("Received a %s status code", response.Status)
}
if err := json.NewDecoder(response.Body).Decode(authToken); err != nil {
return authToken, fmt.Errorf("Error decoding response: %s", err)
}
return authToken, nil
}
func getUserInfo(userinfoEndpoint string, skipSSLValidation bool, tokenType string, accessToken string) (*UserInfo, error) {
userInfo := &UserInfo{}
request, err := http.NewRequest("GET", userinfoEndpoint, nil)
if err != nil {
return userInfo, fmt.Errorf("Error generating request: %s", err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("%s %s", tokenType, accessToken))
response, err := httpClient(skipSSLValidation).Do(request)
if err != nil {
return userInfo, fmt.Errorf("Request error: %s", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return userInfo, fmt.Errorf("Received a %s status code", response.Status)
}
if err := json.NewDecoder(response.Body).Decode(userInfo); err != nil {
return userInfo, fmt.Errorf("Error decoding response: %s", err)
}
return userInfo, nil
}
func generateUserKubeconfig(email string, issuer string, clientID string, clientSecret string, idToken string, refreshToken string) ([]byte, error) {
kubeconfig := &Kubeconfig{
AuthInfos: []NamedAuthInfo{
NamedAuthInfo{
Name: email,
AuthInfo: &AuthInfo{
AuthProvider: &AuthProvider{
Name: "oidc",
AuthProviderConfig: &AuthProviderConfig{
IdpIssuerURL: issuer,
ClientID: clientID,
ClientSecret: clientSecret,
IDToken: idToken,
RefreshToken: refreshToken,
},
},
},
},
},
}
output, err := yaml.Marshal(kubeconfig)
if err != nil {
return nil, fmt.Errorf("Error marshaling yaml: %s", err)
}
return output, nil
}
func main() {
flag.Parse()
if len(*uaaURL) == 0 {
fmt.Print("uaa.url parameter is required")
os.Exit(1)
}
if len(*uaaUsername) == 0 {
fmt.Print("uaa.username parameter is required")
os.Exit(1)
}
if len(*uaaPassword) == 0 {
fmt.Print("uaa.password parameter is required")
os.Exit(1)
}
oidcInfo, err := getOIDCInfo(*uaaURL, *uaaSkipSSLValidation)
if err != nil {
fmt.Printf("Error getting OIDC info: %s\n", err)
os.Exit(1)
}
authToken, err := getAuthToken(oidcInfo.TokenEndpoint, *uaaSkipSSLValidation, *uaaClientID, *uaaClientSecret, *uaaUsername, *uaaPassword)
if err != nil {
fmt.Printf("Error getting auth code: %s\n", err)
os.Exit(1)
}
userInfo, err := getUserInfo(oidcInfo.UserinfoEndpoint, *uaaSkipSSLValidation, authToken.TokenType, authToken.AccessToken)
if err != nil {
fmt.Printf("Error getting user info: %s\n", err)
os.Exit(1)
}
userKubeconfig, err := generateUserKubeconfig(userInfo.Email, oidcInfo.Issuer, *uaaClientID, *uaaClientSecret, authToken.IDToken, authToken.RefreshToken)
if err != nil {
fmt.Printf("Error generating user kubeconfig: %s\n", err)
os.Exit(1)
}
fmt.Println("# Add the following to your ~/.kube/config")
fmt.Println(string(userKubeconfig))
os.Exit(0)
}