-
Notifications
You must be signed in to change notification settings - Fork 5
/
groups.go
205 lines (173 loc) · 4.94 KB
/
groups.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
package groups
import (
"context"
"errors"
"fmt"
"io/ioutil"
"regexp"
"strings"
"go.uber.org/zap"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
)
// GroupTree is the service that deals with google groups
type GroupTree struct {
svc *admin.Service
logger *zap.SugaredLogger
domain string
groups map[string]*Group
users map[string]*User
groupBlacklist []string
}
// Group is a 'google group', but in a more useful format than the original libarary provides
type Group struct {
Email string
Groups []*Group
Users []*User
}
// User is a more useful version of a google user
type User struct {
Email string
// Groups []*Group // Groups a user is in directly
// AllGroups []*Group // Groups + all indirect groups
}
// AllUsers constructs a slice containing all users of the group (including users of all nested groups recursively)
func (g *Group) AllUsers() []*User {
var result []*User
openSet := []*Group{g}
addGroup := func(newGroup *Group) {
for _, gr := range openSet {
if gr.Email == newGroup.Email {
return // already present, don't add
}
}
openSet = append(openSet, newGroup)
}
addUser := func(newUser *User) {
for _, u := range result {
if u.Email == newUser.Email {
return // already present, don't add
}
}
result = append(result, newUser)
}
for i := 0; i < len(openSet); i++ {
current := openSet[i]
if current == nil {
continue
}
// add all users in that group
for _, u := range current.Users {
if u != nil {
addUser(u)
}
}
// and also add all sub-groups to the exploration list
for _, subGroup := range current.Groups {
if subGroup != nil {
addGroup(subGroup)
}
}
}
return result
}
// CreateGroupTree -
func CreateGroupTree(logger *zap.SugaredLogger, domain string, userEmail string, serviceAccountFilePath string, groupBlacklist []string, scopes ...string) (*GroupTree, error) {
ctx := context.Background()
log := logger
log.Infow("loading creds", "path", serviceAccountFilePath)
jsonCredentials, err := ioutil.ReadFile(serviceAccountFilePath)
if err != nil {
return nil, err
}
config, err := google.JWTConfigFromJSON(jsonCredentials, scopes...)
if err != nil {
return nil, fmt.Errorf("JWTConfigFromJSON: %v", err)
}
config.Subject = userEmail
ts := config.TokenSource(ctx)
svc, err := admin.NewService(ctx, option.WithTokenSource(ts))
if err != nil {
return nil, fmt.Errorf("NewService: %v", err)
}
return &GroupTree{svc, logger, domain, map[string]*Group{}, make(map[string]*User), groupBlacklist}, nil
}
// Clear removes all groups and users from the cache
func (g *GroupTree) Clear() {
g.groups = make(map[string]*Group)
g.users = make(map[string]*User)
}
// ListGroupMembersRaw finds all members in a group
func (g *GroupTree) ListGroupMembersRaw(groupKey string) (result []*admin.Member, err error) {
// g.logger.Infof("listing members for group: %v", groupKey)
result = []*admin.Member{}
err = g.svc.Members.List(groupKey).IncludeDerivedMembership(false).Pages(context.Background(), func(page *admin.Members) error {
for _, member := range page.Members {
result = append(result, member)
}
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
// GetGroup -
func (g *GroupTree) GetGroup(email string) (*Group, error) {
grp, exists := g.groups[email]
if exists {
return grp, nil // return existing
}
// Check blacklist
isBlacklisted, reason := g.isGroupInBlacklist(email)
if isBlacklisted {
g.logger.Infow("Skipping group because it is blacklisted", "groupEmail", email, "pattern", reason)
return nil, errors.New("group is blacklisted by: '" + reason + "'")
}
members, err := g.ListGroupMembersRaw(email)
if err != nil {
g.logger.Warnw("error listing group members", "groupEmail", email, "err", err)
return nil, err // error
}
grp = &Group{Email: email} // create new
g.groups[email] = grp
for _, m := range members {
if m.Type == "GROUP" {
subGroup, err := g.GetGroup(m.Email) // cache that sub group as well
if err != nil {
continue
}
grp.Groups = append(grp.Groups, subGroup) // add it as a child
} else if m.Type == "USER" {
// cache user
u, exists := g.users[m.Email]
if !exists {
u = &User{m.Email}
g.users[m.Email] = u
}
grp.Users = append(grp.Users, u)
} else {
g.logger.Fatalw("unknown member type in google group", "group", email, "memberType", m.Type, "memberId", m.Id, "memberEmail", m.Email)
}
}
return grp, nil
}
func (g *GroupTree) isGroupInBlacklist(email string) (isBlacklisted bool, reason string) {
for _, item := range g.groupBlacklist {
if strings.HasPrefix(item, "/") && strings.HasSuffix(item, "/") {
// regex match
pattern := item[1 : len(item)-1]
isMatch, err := regexp.MatchString(pattern, email)
if err == nil && isMatch {
return true, item
}
} else {
// regular match
if item == email {
return true, item
}
}
}
return false, ""
}