/
goauth_helper.go
293 lines (275 loc) · 10.2 KB
/
goauth_helper.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
package googleoauth
import (
"encoding/json"
"fmt"
"net/http"
"strings"
v3 "github.com/rancher/rancher/pkg/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/googleapi"
)
func (g *googleOauthProvider) getUserInfoAndGroups(adminSvc *admin.Service, gOAuthToken *oauth2.Token, config *v3.GoogleOauthConfig, testAndEnableAction bool) (v3.Principal, []v3.Principal, error) {
var userPrincipal v3.Principal
var groupPrincipals []v3.Principal
// use the access token to make requests, get user info
user, err := g.goauthClient.getUser(gOAuthToken.AccessToken, config)
if err != nil {
return userPrincipal, groupPrincipals, err
}
if testAndEnableAction {
if user.HostedDomain != config.Hostname {
return userPrincipal, groupPrincipals, fmt.Errorf("invalid hostname provided")
}
}
userPrincipal = g.toPrincipal(userType, *user, nil)
userPrincipal.Me = true
logrus.Debugf("[Google OAuth] loginuser: Obtained userinfo using oauth access token")
groupPrincipals, err = g.getGroupsUserBelongsTo(adminSvc, user.SubjectUniqueID, user.HostedDomain, config)
if err != nil {
// The error for this group request could be 403, because svc acc was not provided, and we're relying on individual
// users' creds to get groups
if config.ServiceAccountCredential == "" {
if gErr, ok := err.(*googleapi.Error); !ok || gErr.Code != http.StatusForbidden {
// if the error is not forbidden, return the error
return userPrincipal, groupPrincipals, err
}
// if the error is forbidden, don't throw any error, just no group principals will be returned
} else {
// getting any error in spite of svc acc creds must be returned
return userPrincipal, groupPrincipals, err
}
}
if config.NestedGroupMembershipEnabled {
groupPrincipals, err = g.fetchParentGroups(config, groupPrincipals, adminSvc, user.HostedDomain)
if err != nil {
return userPrincipal, groupPrincipals, err
}
}
logrus.Debugf("[Google OAuth] loginuser: Retrieved user's groups using admin directory")
return userPrincipal, groupPrincipals, nil
}
func (g *googleOauthProvider) fetchParentGroups(config *v3.GoogleOauthConfig, groupPrincipals []v3.Principal, adminSvc *admin.Service, hostedDomain string) ([]v3.Principal, error) {
groupMap := make(map[string]bool)
var nestedGroupPrincipals []v3.Principal
for _, principal := range groupPrincipals {
principals, err := g.gatherParentGroups(principal, adminSvc, config, hostedDomain, groupMap)
if err != nil {
return groupPrincipals, err
}
if len(principals) > 0 {
nestedGroupPrincipals = append(nestedGroupPrincipals, principals...)
}
}
groupPrincipals = append(groupPrincipals, nestedGroupPrincipals...)
return groupPrincipals, nil
}
func (g *googleOauthProvider) getGroupsUserBelongsTo(adminSvc *admin.Service, userKey string, hostedDomain string, config *v3.GoogleOauthConfig) ([]v3.Principal, error) {
var groupPrincipals []v3.Principal
_, groups, err := g.paginateResults(adminSvc, hostedDomain, userKey, "", "", groupType, false)
if err != nil {
// The error for this group request could be 403, because svc acc was not provided, and we're relying on individual
// users' creds to get groups
if config.ServiceAccountCredential == "" {
// used the client creds, if error is forbidden, don't throw error
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
return groupPrincipals, nil
}
}
// getting any error in spite of svc acc creds must be returned
return nil, err
}
for _, gr := range groups {
group := Account{Name: gr.Name, Email: gr.Email, SubjectUniqueID: gr.Id}
groupPrincipal := g.toPrincipal(groupType, group, nil)
groupPrincipal.MemberOf = true
groupPrincipals = append(groupPrincipals, groupPrincipal)
}
return groupPrincipals, nil
}
func (g *googleOauthProvider) searchPrincipals(adminSvc *admin.Service, searchKey, principalType string, config *v3.GoogleOauthConfig) ([]Account, error) {
var accounts []Account
if principalType == "" || principalType == "user" {
userAccounts, err := g.searchUsers(adminSvc, searchKey, config, false)
if err != nil {
if config.ServiceAccountCredential == "" {
// used the client creds, must try once with viewType domain_public
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
userAccounts, err = g.searchUsers(adminSvc, searchKey, config, true)
if err != nil {
return nil, err
}
} else {
return nil, err
}
} else {
// getting any error in spite of svc acc creds must be returned
return nil, err
}
}
accounts = append(accounts, userAccounts...)
}
if principalType == "" || principalType == "group" {
groupAccounts, err := g.searchGroups(adminSvc, searchKey, config)
if err != nil {
if config.ServiceAccountCredential == "" {
// used the client creds, if error is forbidden, don't throw error
if gErr, ok := err.(*googleapi.Error); ok && gErr.Code == http.StatusForbidden {
return accounts, nil
}
}
// getting any error in spite of svc acc creds must be returned
return nil, err
}
accounts = append(accounts, groupAccounts...)
}
return accounts, nil
}
func (g *googleOauthProvider) searchUsers(adminSvc *admin.Service, searchKey string, config *v3.GoogleOauthConfig, viewPublic bool) ([]Account, error) {
var users []*admin.User
var accounts []Account
users, _, err := g.paginateResults(adminSvc, config.Hostname, "", searchKey, "", userType, viewPublic)
if err != nil {
return accounts, err
}
for _, u := range users {
a := Account{
SubjectUniqueID: u.Id,
Email: u.PrimaryEmail,
PictureURL: u.ThumbnailPhotoUrl,
Type: userType,
}
if u.Name != nil {
a.Name = u.Name.FullName
a.GivenName = u.Name.GivenName
a.FamilyName = u.Name.FamilyName
}
accounts = append(accounts, a)
}
return accounts, nil
}
func (g *googleOauthProvider) searchGroups(adminSvc *admin.Service, searchKey string, config *v3.GoogleOauthConfig) ([]Account, error) {
var accounts []Account
groupsMap := map[string]*admin.Group{}
for _, attr := range []string{"name", "email"} {
_, resGroups, err := g.paginateResults(adminSvc, config.Hostname, "", searchKey, attr, groupType, false)
if err != nil {
return accounts, err
}
//dedup groups
for _, gr := range resGroups {
if _, ok := groupsMap[gr.Id]; !ok {
groupsMap[gr.Id] = gr
}
}
}
for _, g := range groupsMap {
accounts = append(accounts, Account{SubjectUniqueID: g.Id, Email: g.Email, Name: g.Name, Type: groupType})
}
return accounts, nil
}
func (g *googleOauthProvider) paginateResults(adminSvc *admin.Service, hostedDomain, memberKey, searchKey, searchAttr, accountType string, viewPublic bool) ([]*admin.User, []*admin.Group, error) {
var groups []*admin.Group
var users []*admin.User
switch accountType {
case userType:
// in case of list users call, using the searchKey itself as query searches all attributes for the search key
userListCall := adminSvc.Users.List().Domain(hostedDomain).Query(searchKey)
if viewPublic {
userListCall.ViewType(domainPublicViewType)
}
for {
res, err := userListCall.Do()
if err != nil {
return users, nil, err
}
users = append(users, res.Users...)
if res.NextPageToken == "" {
return users, nil, nil
}
userListCall.PageToken(res.NextPageToken)
}
case groupType:
groupListCall := adminSvc.Groups.List().Domain(hostedDomain)
if memberKey != "" {
groupListCall.UserKey(memberKey)
} else if searchKey != "" {
// in case of list groups call, we need to specify search attributes
groupListCall.Query(searchAttr + ":" + searchKey + "*")
}
for {
res, err := groupListCall.Do()
if err != nil {
return nil, groups, err
}
groups = append(groups, res.Groups...)
if res.NextPageToken == "" {
return nil, groups, nil
}
groupListCall.PageToken(res.NextPageToken)
}
default:
return nil, nil, fmt.Errorf("paginateResults: Invalid principal type")
}
}
func (g *googleOauthProvider) gatherParentGroups(groupPrincipal v3.Principal, adminSvc *admin.Service, config *v3.GoogleOauthConfig, hostedDomain string, groupMap map[string]bool) ([]v3.Principal, error) {
var principals []v3.Principal
if groupMap[groupPrincipal.ObjectMeta.Name] {
return principals, nil
}
groupMap[groupPrincipal.ObjectMeta.Name] = true
parts := strings.SplitN(groupPrincipal.ObjectMeta.Name, ":", 2)
if len(parts) != 2 {
return principals, fmt.Errorf("error while gathering parent groups: invalid id %v", groupPrincipal.ObjectMeta.Name)
}
groupID := strings.TrimPrefix(parts[1], "//")
groups, err := g.getGroupsUserBelongsTo(adminSvc, groupID, hostedDomain, config)
if err != nil {
return principals, err
}
for _, group := range groups {
if groupMap[group.ObjectMeta.Name] {
continue
} else {
principals = append(principals, group)
nestedGroupPrincipals, err := g.gatherParentGroups(group, adminSvc, config, hostedDomain, groupMap)
if err != nil {
return principals, err
}
if len(nestedGroupPrincipals) > 0 {
principals = append(principals, nestedGroupPrincipals...)
}
}
}
return principals, nil
}
func (g *googleOauthProvider) getdirectoryServiceFromStoredToken(storedOauthToken string, config *v3.GoogleOauthConfig) (*admin.Service, error) {
var oauthToken oauth2.Token
if err := json.Unmarshal([]byte(storedOauthToken), &oauthToken); err != nil {
return nil, err
}
oauth2Config, err := google.ConfigFromJSON([]byte(config.OauthCredential), scopes...)
if err != nil {
return nil, err
}
adminSvc, err := g.getDirectoryService(g.ctx, config.AdminEmail, []byte(config.ServiceAccountCredential), oauth2Config.TokenSource(g.ctx, &oauthToken))
if err != nil {
return nil, err
}
return adminSvc, nil
}
func getUIDFromPrincipalID(principalID string) (string, string, error) {
var externalID string
parts := strings.SplitN(principalID, ":", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid id %v", principalID)
}
externalID = strings.TrimPrefix(parts[1], "//")
parts = strings.SplitN(parts[0], "_", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid id %v", principalID)
}
return externalID, parts[1], nil
}