/
cmd.go
378 lines (336 loc) · 9 KB
/
cmd.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*
Copyright (c) 2020 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package idp
import (
"fmt"
"strconv"
"strings"
c "github.com/openshift-online/ocm-cli/pkg/cluster"
"github.com/openshift-online/ocm-cli/pkg/ocm"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/AlecAivazis/survey/v2"
"github.com/spf13/cobra"
)
var args struct {
clusterKey string
idpType string
idpName string
clientID string
clientSecret string
mappingMethod string
// GitHub
githubHostname string
githubOrganizations string
githubTeams string
// Google
googleHostedDomain string
// LDAP
ldapURL string
ldapBindDN string
ldapBindPassword string
ldapIDs string
ldapUsernames string
ldapDisplayNames string
ldapEmails string
// OpenID
openidIssuerURL string
openidEmail string
openidName string
openidUsername string
openidExtraScopes string
// HTPasswd
htpasswdUsername string
htpasswdPassword string
}
var validIdps = []string{"github", "google", "ldap", "openid", "htpasswd"}
var Cmd = &cobra.Command{
Use: "idp --cluster={NAME|ID|EXTERNAL_ID}",
Short: "Add IDP for cluster",
Long: "Add an Identity providers to determine how users log into the cluster.",
Example: ` # Add a GitHub identity provider to a cluster named "mycluster"
ocm create idp --type=github --cluster=mycluster
# Add an identity provider following interactive prompts
ocm create idp --cluster=mycluster`,
Args: cobra.NoArgs,
RunE: run,
}
func init() {
flags := Cmd.Flags()
flags.SortFlags = false
flags.StringVarP(
&args.clusterKey,
"cluster",
"c",
"",
"Name or ID or external_id of the cluster to add the IdP to (required).",
)
//nolint:gosec
Cmd.MarkFlagRequired("cluster")
flags.StringVarP(
&args.idpType,
"type",
"t",
"",
fmt.Sprintf("Type of identity provider. Options are %s\n", validIdps),
)
flags.StringVarP(
&args.idpName,
"name",
"n",
"",
"Name of the identity provider.",
)
flags.StringVar(
&args.mappingMethod,
"mapping-method",
"claim",
"Specifies how new identities are mapped to users when they log in",
)
flags.StringVar(
&args.clientID,
"client-id",
"",
"Client ID from the registered application.",
)
flags.StringVar(
&args.clientSecret,
"client-secret",
"",
"Client Secret from the registered application.\n",
)
// GitHub
flags.StringVar(
&args.githubHostname,
"hostname",
"",
"GitHub: Optional domain to use with a hosted instance of GitHub Enterprise.",
)
flags.StringVar(
&args.githubOrganizations,
"organizations",
"",
"GitHub: Only users that are members of at least one of the listed organizations will be allowed to log in.",
)
flags.StringVar(
&args.githubTeams,
"teams",
"",
"GitHub: Only users that are members of at least one of the listed teams will be allowed to log in. "+
"The format is <org>/<team>.\n",
)
// Google
flags.StringVar(
&args.googleHostedDomain,
"hosted-domain",
"",
"Google: Restrict users to a Google Apps domain. Example: http://redhat.com (scheme required)\n",
)
// LDAP
flags.StringVar(
&args.ldapURL,
"url",
"",
"LDAP: An RFC 2255 URL which specifies the LDAP search parameters to use.",
)
flags.StringVar(
&args.ldapBindDN,
"bind-dn",
"",
"LDAP: DN to bind with during the search phase.",
)
flags.StringVar(
&args.ldapBindPassword,
"bind-password",
"",
"LDAP: Password to bind with during the search phase.",
)
flags.StringVar(
&args.ldapIDs,
"id-attributes",
"dn",
"LDAP: The list of attributes whose values should be used as the user ID.",
)
flags.StringVar(
&args.ldapUsernames,
"username-attributes",
"uid",
"LDAP: The list of attributes whose values should be used as the preferred username.",
)
flags.StringVar(
&args.ldapDisplayNames,
"name-attributes",
"cn",
"LDAP: The list of attributes whose values should be used as the display name.",
)
flags.StringVar(
&args.ldapEmails,
"email-attributes",
"",
"LDAP: The list of attributes whose values should be used as the email address.\n",
)
// OpenID
flags.StringVar(
&args.openidIssuerURL,
"issuer-url",
"",
"OpenID: The URL that the OpenID Provider asserts as the Issuer Identifier. "+
"It must use the https scheme with no URL query parameters or fragment.",
)
flags.StringVar(
&args.openidEmail,
"email-claims",
"",
"OpenID: List of claims to use as the email address.",
)
flags.StringVar(
&args.openidName,
"name-claims",
"",
"OpenID: List of claims to use as the display name.",
)
flags.StringVar(
&args.openidUsername,
"username-claims",
"",
"OpenID: List of claims to use as the preferred username when provisioning a user.\n",
)
flags.StringVar(
&args.openidExtraScopes,
"extra-scopes",
"",
"OpenID: List of extra scopes to request when provisioning a user.\n",
)
// HTPasswd
flags.StringVar(
&args.htpasswdUsername,
"username",
"",
"HTPasswd: Username.\n",
)
flags.StringVar(
&args.htpasswdPassword,
"password",
"",
"HTPasswd: Password.\n",
)
}
func run(cmd *cobra.Command, argv []string) error {
// Check that the cluster key (name, identifier or external identifier) given by the user
// is reasonably safe so that there is no risk of SQL injection:
clusterKey := args.clusterKey
if !c.IsValidClusterKey(clusterKey) {
return fmt.Errorf(
"Cluster name, identifier or external identifier '%s' isn't valid: it "+
"must contain only letters, digits, dashes and underscores",
clusterKey,
)
}
// Create the client for the OCM API:
connection, err := ocm.NewConnection().Build()
if err != nil {
return fmt.Errorf("Failed to create OCM connection: %v", err)
}
defer connection.Close()
// Get the client for the cluster management api
clusterCollection := connection.ClustersMgmt().V1().Clusters()
cluster, err := c.GetCluster(connection, clusterKey)
if err != nil {
return fmt.Errorf("Failed to get cluster '%s': %v", clusterKey, err)
}
if cluster.State() != cmv1.ClusterStateReady {
return fmt.Errorf("Cluster '%s' is not yet ready", clusterKey)
}
idps, err := c.GetIdentityProviders(clusterCollection, cluster.ID())
if err != nil {
return fmt.Errorf("Failed to get identity providers for cluster '%s': %v", clusterKey, err)
}
// Grab all the IDP information interactively if necessary
idpType := args.idpType
if idpType == "" {
prompt := &survey.Select{
Message: "Type of identity provider:",
Options: validIdps,
}
err = survey.AskOne(prompt, &idpType)
if err != nil {
return fmt.Errorf("Failed to get a valid IDP type")
}
}
idpName := args.idpName
if idpName == "" {
prompt := &survey.Input{
Message: "Name of the identity provider:",
}
err = survey.AskOne(prompt, &idpName)
if err != nil {
return fmt.Errorf("Failed to get a valid IDP name")
}
}
var idpBuilder cmv1.IdentityProviderBuilder
if idpName == "" {
idpName = getNextName(idpType, idps)
}
message := ""
switch idpType {
case "github":
idpBuilder, err = buildGithubIdp(cluster, idpName)
case "google":
idpBuilder, err = buildGoogleIdp(cluster, idpName)
case "ldap":
idpBuilder, err = buildLdapIdp(cluster, idpName)
case "openid":
idpBuilder, err = buildOpenidIdp(cluster, idpName)
case "htpasswd":
idpBuilder, message, err = buildHtpasswdIdp(cluster, idpName)
default:
err = fmt.Errorf("Invalid IDP type '%s'", idpType)
}
if err != nil {
return fmt.Errorf("Failed to create IDP for cluster '%s': %v", clusterKey, err)
}
fmt.Printf("Configuring IDP for cluster '%s'\n", clusterKey)
idp, err := idpBuilder.Build()
if err != nil {
return fmt.Errorf("Failed to create IDP for cluster '%s': %v", clusterKey, err)
}
_, err = clusterCollection.Cluster(cluster.ID()).
IdentityProviders().
Add().
Body(idp).
Send()
if err != nil {
return fmt.Errorf("Failed to add IDP to cluster '%s': %v", clusterKey, err)
}
fmt.Printf(
"Identity Provider '%s' has been created.\nYou need to ensure that there is a list "+
"of cluster administrators defined.\nSee 'ocm create user --help' for more "+
"information.\nTo login into the console, open %s and click on %s.\n%s",
idpName, cluster.Console().URL(), idpName, message,
)
return nil
}
func getNextName(idpType string, idps []*cmv1.IdentityProvider) string {
nextSuffix := 0
for _, idp := range idps {
if strings.Contains(idp.Name(), idpType) {
lastSuffix, err := strconv.Atoi(strings.Split(idp.Name(), "-")[1])
if err != nil {
continue
}
if lastSuffix >= nextSuffix {
nextSuffix = lastSuffix
}
}
}
return fmt.Sprintf("%s-%d", idpType, nextSuffix+1)
}