forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github_provider.go
376 lines (323 loc) · 10.7 KB
/
github_provider.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
package github
import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rancher/norman/httperror"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rancher/pkg/api/store/auth"
"github.com/rancher/rancher/pkg/auth/providers/common"
"github.com/rancher/rancher/pkg/auth/tokens"
corev1 "github.com/rancher/types/apis/core/v1"
v3 "github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/rancher/types/apis/management.cattle.io/v3public"
client "github.com/rancher/types/client/management/v3"
publicclient "github.com/rancher/types/client/management/v3public"
"github.com/rancher/types/config"
"github.com/rancher/types/user"
"github.com/sirupsen/logrus"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
const (
Name = "github"
)
type ghProvider struct {
ctx context.Context
authConfigs v3.AuthConfigInterface
secrets corev1.SecretInterface
githubClient *GClient
userMGR user.Manager
tokenMGR *tokens.Manager
}
func Configure(ctx context.Context, mgmtCtx *config.ScaledContext, userMGR user.Manager, tokenMGR *tokens.Manager) common.AuthProvider {
githubClient := &GClient{
httpClient: &http.Client{},
}
return &ghProvider{
ctx: ctx,
authConfigs: mgmtCtx.Management.AuthConfigs(""),
secrets: mgmtCtx.Core.Secrets(""),
githubClient: githubClient,
userMGR: userMGR,
tokenMGR: tokenMGR,
}
}
func (g *ghProvider) GetName() string {
return Name
}
func (g *ghProvider) CustomizeSchema(schema *types.Schema) {
schema.ActionHandler = g.actionHandler
schema.Formatter = g.formatter
}
func (g *ghProvider) TransformToAuthProvider(authConfig map[string]interface{}) map[string]interface{} {
p := common.TransformToAuthProvider(authConfig)
p[publicclient.GithubProviderFieldRedirectURL] = formGithubRedirectURLFromMap(authConfig)
return p
}
func (g *ghProvider) getGithubConfigCR() (*v3.GithubConfig, error) {
authConfigObj, err := g.authConfigs.ObjectClient().UnstructuredClient().Get(Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to retrieve GithubConfig, error: %v", err)
}
u, ok := authConfigObj.(runtime.Unstructured)
if !ok {
return nil, fmt.Errorf("failed to retrieve GithubConfig, cannot read k8s Unstructured data")
}
storedGithubConfigMap := u.UnstructuredContent()
storedGithubConfig := &v3.GithubConfig{}
mapstructure.Decode(storedGithubConfigMap, storedGithubConfig)
metadataMap, ok := storedGithubConfigMap["metadata"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("failed to retrieve GithubConfig metadata, cannot read k8s Unstructured data")
}
typemeta := &metav1.ObjectMeta{}
mapstructure.Decode(metadataMap, typemeta)
storedGithubConfig.ObjectMeta = *typemeta
if storedGithubConfig.ClientSecret != "" {
value, err := common.ReadFromSecret(g.secrets, storedGithubConfig.ClientSecret, strings.ToLower(auth.TypeToField[client.GithubConfigType]))
if err != nil {
return nil, err
}
storedGithubConfig.ClientSecret = value
}
return storedGithubConfig, nil
}
func (g *ghProvider) saveGithubConfig(config *v3.GithubConfig) error {
storedGithubConfig, err := g.getGithubConfigCR()
if err != nil {
return err
}
config.APIVersion = "management.cattle.io/v3"
config.Kind = v3.AuthConfigGroupVersionKind.Kind
config.Type = client.GithubConfigType
config.ObjectMeta = storedGithubConfig.ObjectMeta
secretInfo := convert.ToString(config.ClientSecret)
field := strings.ToLower(auth.TypeToField[config.Type])
if err := common.CreateOrUpdateSecrets(g.secrets, secretInfo, field, strings.ToLower(config.Type)); err != nil {
return err
}
config.ClientSecret = common.GetName(config.Type, field)
_, err = g.authConfigs.ObjectClient().Update(config.ObjectMeta.Name, config)
if err != nil {
return err
}
return nil
}
func (g *ghProvider) AuthenticateUser(input interface{}) (v3.Principal, []v3.Principal, string, error) {
login, ok := input.(*v3public.GithubLogin)
if !ok {
return v3.Principal{}, nil, "", errors.New("unexpected input type")
}
return g.LoginUser(login, nil, false)
}
func (g *ghProvider) LoginUser(githubCredential *v3public.GithubLogin, config *v3.GithubConfig, test bool) (v3.Principal, []v3.Principal, string, error) {
var groupPrincipals []v3.Principal
var userPrincipal v3.Principal
var err error
if config == nil {
config, err = g.getGithubConfigCR()
if err != nil {
return v3.Principal{}, nil, "", err
}
}
securityCode := githubCredential.Code
accessToken, err := g.githubClient.getAccessToken(securityCode, config)
if err != nil {
logrus.Infof("Error generating accessToken from github %v", err)
return v3.Principal{}, nil, "", err
}
user, err := g.githubClient.getUser(accessToken, config)
if err != nil {
return v3.Principal{}, nil, "", err
}
userPrincipal = g.toPrincipal(userType, user, nil)
userPrincipal.Me = true
orgAccts, err := g.githubClient.getOrgs(accessToken, config)
if err != nil {
return v3.Principal{}, nil, "", err
}
for _, orgAcct := range orgAccts {
groupPrincipal := g.toPrincipal(orgType, orgAcct, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
teamAccts, err := g.githubClient.getTeams(accessToken, config)
if err != nil {
return v3.Principal{}, nil, "", err
}
for _, teamAcct := range teamAccts {
groupPrincipal := g.toPrincipal(teamType, teamAcct, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
testAllowedPrincipals := config.AllowedPrincipalIDs
if test && config.AccessMode == "restricted" {
testAllowedPrincipals = append(testAllowedPrincipals, userPrincipal.Name)
}
allowed, err := g.userMGR.CheckAccess(config.AccessMode, testAllowedPrincipals, userPrincipal.Name, groupPrincipals)
if err != nil {
return v3.Principal{}, nil, "", err
}
if !allowed {
return v3.Principal{}, nil, "", httperror.NewAPIError(httperror.Unauthorized, "unauthorized")
}
return userPrincipal, groupPrincipals, accessToken, nil
}
func (g *ghProvider) RefetchGroupPrincipals(principalID string, secret string) ([]v3.Principal, error) {
var groupPrincipals []v3.Principal
var err error
var config *v3.GithubConfig
if config == nil {
config, err = g.getGithubConfigCR()
if err != nil {
return nil, err
}
}
orgAccts, err := g.githubClient.getOrgs(secret, config)
if err != nil {
return nil, err
}
for _, orgAcct := range orgAccts {
groupPrincipal := g.toPrincipal(orgType, orgAcct, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
teamAccts, err := g.githubClient.getTeams(secret, config)
if err != nil {
return nil, err
}
for _, teamAcct := range teamAccts {
groupPrincipal := g.toPrincipal(teamType, teamAcct, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
return groupPrincipals, nil
}
func (g *ghProvider) SearchPrincipals(searchKey, principalType string, token v3.Token) ([]v3.Principal, error) {
var principals []v3.Principal
var err error
config, err := g.getGithubConfigCR()
if err != nil {
return principals, err
}
accessToken, err := g.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{&token})
if err != nil {
if !apierrors.IsNotFound(err) {
return nil, err
}
accessToken = token.ProviderInfo["access_token"]
}
accts, err := g.githubClient.searchUsers(searchKey, principalType, accessToken, config)
if err != nil {
logrus.Errorf("problem searching github: %v", err)
}
for _, acct := range accts {
pType := strings.ToLower(acct.Type)
if pType == "organization" {
pType = orgType
}
p := g.toPrincipal(pType, acct, &token)
principals = append(principals, p)
}
return principals, nil
}
const (
userType = "user"
teamType = "team"
orgType = "org"
)
func (g *ghProvider) GetPrincipal(principalID string, token v3.Token) (v3.Principal, error) {
config, err := g.getGithubConfigCR()
if err != nil {
return v3.Principal{}, err
}
accessToken, err := g.tokenMGR.GetSecret(token.UserID, token.AuthProvider, []*v3.Token{&token})
if err != nil {
if !apierrors.IsNotFound(err) {
return v3.Principal{}, err
}
accessToken = token.ProviderInfo["access_token"]
}
// parsing id to get the external id and type. id looks like github_[user|org|team]://12345
var externalID string
parts := strings.SplitN(principalID, ":", 2)
if len(parts) != 2 {
return v3.Principal{}, errors.Errorf("invalid id %v", principalID)
}
externalID = strings.TrimPrefix(parts[1], "//")
parts = strings.SplitN(parts[0], "_", 2)
if len(parts) != 2 {
return v3.Principal{}, errors.Errorf("invalid id %v", principalID)
}
principalType := parts[1]
var acct Account
switch principalType {
case userType:
fallthrough
case orgType:
acct, err = g.githubClient.getUserOrgByID(externalID, accessToken, config)
if err != nil {
return v3.Principal{}, err
}
case teamType:
acct, err = g.githubClient.getTeamByID(externalID, accessToken, config)
if err != nil {
return v3.Principal{}, err
}
default:
return v3.Principal{}, fmt.Errorf("Cannot get the github account due to invalid externalIDType %v", principalType)
}
princ := g.toPrincipal(principalType, acct, &token)
return princ, nil
}
func (g *ghProvider) toPrincipal(principalType string, acct Account, token *v3.Token) v3.Principal {
displayName := acct.Name
if displayName == "" {
displayName = acct.Login
}
princ := v3.Principal{
ObjectMeta: metav1.ObjectMeta{Name: Name + "_" + principalType + "://" + strconv.Itoa(acct.ID)},
DisplayName: displayName,
LoginName: acct.Login,
Provider: Name,
Me: false,
ProfilePicture: acct.AvatarURL,
}
if principalType == userType {
princ.PrincipalType = "user"
if token != nil {
princ.Me = g.isThisUserMe(token.UserPrincipal, princ)
}
} else {
princ.PrincipalType = "group"
if token != nil {
princ.MemberOf = g.tokenMGR.IsMemberOf(*token, princ)
}
}
return princ
}
func (g *ghProvider) isThisUserMe(me v3.Principal, other v3.Principal) bool {
if me.ObjectMeta.Name == other.ObjectMeta.Name && me.LoginName == other.LoginName && me.PrincipalType == other.PrincipalType {
return true
}
return false
}
func (g *ghProvider) CanAccessWithGroupProviders(userPrincipalID string, groupPrincipals []v3.Principal) (bool, error) {
config, err := g.getGithubConfigCR()
if err != nil {
logrus.Errorf("Error fetching github config: %v", err)
return false, err
}
allowed, err := g.userMGR.CheckAccess(config.AccessMode, config.AllowedPrincipalIDs, userPrincipalID, groupPrincipals)
if err != nil {
return false, err
}
return allowed, nil
}