-
Notifications
You must be signed in to change notification settings - Fork 212
/
usergroup.go
266 lines (247 loc) · 8.3 KB
/
usergroup.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
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 security
import (
"fmt"
"os/user"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"github.com/apache/yunikorn-core/pkg/common"
"github.com/apache/yunikorn-core/pkg/locking"
"github.com/apache/yunikorn-core/pkg/log"
"github.com/apache/yunikorn-scheduler-interface/lib/go/si"
)
const (
negcache = 30 // time to cache failures for lookups in seconds
poscache = 300 // time to cache a positive lookup in seconds
cleanerInterval = 60 // default cleaner interval
)
// global variables
var now time.Time // One clock to access
var instance *UserGroupCache // The instance of the cache
var once = &sync.Once{} // Make sure we can only create the cache once
var stopped atomic.Bool // whether UserGroupCache is stopped (needed for multiple partitions)
// Cache for the user entries.
type UserGroupCache struct {
lock locking.RWMutex
interval time.Duration
ugs map[string]*UserGroup
// methods that allow mocking of the class or extending to use non OS solutions
lookup func(userName string) (*user.User, error)
lookupGroupID func(gid string) (*user.Group, error)
groupIds func(osUser *user.User) ([]string, error)
stop chan struct{}
}
// The structure of the entry in the cache.
type UserGroup struct {
User string
Groups []string
failed bool
resolved int64
}
// Get the resolver for the user and group info.
// Current setup allows three resolvers:
// * NO resolver: default, no user or group resolution just return the info (k8s use case)
// * OS resolver: uses the OS libraries to resolve user and group memberships
// * Test resolver: fake resolution for testing
// TODO need to make this fully configurable and look at reflection etc
func GetUserGroupCache(resolver string) *UserGroupCache {
once.Do(func() {
switch resolver {
case "test":
log.Log(log.Security).Info("creating test user group resolver")
instance = GetUserGroupCacheTest()
case "os":
log.Log(log.Security).Info("creating OS user group resolver")
instance = GetUserGroupCacheOS()
default:
log.Log(log.Security).Info("creating UserGroupCache without resolver")
instance = GetUserGroupNoResolve()
}
instance.ugs = make(map[string]*UserGroup)
log.Log(log.Security).Info("starting UserGroupCache cleaner",
zap.Stringer("cleanerInterval", instance.interval))
go instance.run()
stopped.Store(false)
})
return instance
}
// Run the cleanup in a separate routine
func (c *UserGroupCache) run() {
log.Log(log.Security).Info("Starting user/group cache cleaner")
for {
select {
case <-c.stop:
return
case <-time.After(c.interval):
runStart := time.Now()
c.cleanUpCache()
log.Log(log.Security).Debug("time consumed cleaning the UserGroupCache",
zap.Stringer("duration", time.Since(runStart)))
}
}
}
// Do the real work for the cache cleanup
func (c *UserGroupCache) cleanUpCache() {
oldest := now.Unix() - poscache
oldestFailed := now.Unix() - negcache
// clean up the cache so we do not grow out of bounds
instance.lock.Lock()
defer instance.lock.Unlock()
// walk over the entries in the map and delete the expired ones, cleanup based on the resolved time.
// Negative cached entries will expire quicker
for key, val := range c.ugs {
if val.resolved < oldest || (val.failed && val.resolved < oldestFailed) {
delete(c.ugs, key)
}
}
}
// reset the cached content, test use only
func (c *UserGroupCache) resetCache() {
log.Log(log.Security).Debug("UserGroupCache reset")
instance.lock.Lock()
defer instance.lock.Unlock()
c.ugs = make(map[string]*UserGroup)
}
func (c *UserGroupCache) ConvertUGI(ugi *si.UserGroupInformation, force bool) (UserGroup, error) {
// check if we have a user to convert
if ugi == nil || ugi.User == "" {
if force {
// app creation is forced, so we need to synthesize a user / group
ugi.User = common.AnonymousUser
ugi.Groups = []string{common.AnonymousGroup}
} else {
return UserGroup{}, fmt.Errorf("empty user cannot resolve")
}
}
// try to resolve the user if group info is empty otherwise we just convert
if len(ugi.Groups) == 0 {
ug, err := c.GetUserGroup(ugi.User)
if force && (err != nil || ug.failed) {
ugi.Groups = []string{common.AnonymousGroup}
} else {
return ug, err
}
}
// If groups are already present we should just convert
newUG := UserGroup{User: ugi.User}
newUG.Groups = append(newUG.Groups, ugi.Groups...)
newUG.resolved = now.Unix()
c.lock.Lock()
defer c.lock.Unlock()
c.ugs[ugi.User] = &newUG
return newUG, nil
}
// Get the user group information. An error will still return a UserGroup.
// The Failed flag in the object will be set to true for any failures.
// The information is cached, negatively and positively.
func (c *UserGroupCache) GetUserGroup(userName string) (UserGroup, error) {
// check if we have a user to resolve
if userName == "" {
return UserGroup{}, fmt.Errorf("empty user cannot resolve")
}
// look in the cache before resolving
c.lock.RLock()
ug, ok := c.ugs[userName]
c.lock.RUnlock()
// return if this was not a negative cache that has not timed out
if ok && !ug.failed {
return *ug, nil
}
// nothing returned so create a new one
if ug == nil {
ug = &UserGroup{
User: userName,
}
}
// if we failed before we could get an object back, return the existing one with an error
if ug.failed {
return *ug, fmt.Errorf("user resolution failed, cached data returned: %v", time.Unix(ug.resolved, 0))
}
// resolve if we do not have it in the cache
// find the user first, then resolve the groups
osUser, err := c.lookup(userName)
if err != nil {
log.Log(log.Security).Error("Error resolving user: does not exist",
zap.String("userName", userName),
zap.Error(err))
ug.failed = true
}
// skip group resolution if we did not find the user
if osUser != nil {
// groups are updated in the object directly
err = ug.resolveGroups(osUser, c)
// log a failure and continue
if err != nil {
log.Log(log.Security).Error("Error resolving groups for user",
zap.String("userName", userName),
zap.Error(err))
ug.failed = true
}
}
// all resolved (or not) but use this time stamp
ug.resolved = now.Unix()
// add it to the cache, even if we fail negative cache is also good to know
c.lock.Lock()
defer c.lock.Unlock()
c.ugs[userName] = ug
return *ug, err
}
func (c *UserGroupCache) Stop() {
// make sure that in case of multiple partitions, we call Stop() only once (the instance is shared)
// see ClusterContext.Stop()
if !stopped.Load() {
log.Log(log.Security).Info("Stopping UserGroupCache background cleanup")
close(c.stop)
once = &sync.Once{} // re-init so that GetUserGroupCache() can create a new instance again
instance = nil
stopped.Store(true)
return
}
log.Log(log.Security).Info("UserGroupCache already stopped")
}
// Resolve the groups for the user if the user exists
func (ug *UserGroup) resolveGroups(osUser *user.User, c *UserGroupCache) error {
// resolve the primary group and add it first
groupName, err := c.lookupGroupID(osUser.Gid)
if err != nil {
ug.Groups = append(ug.Groups, osUser.Gid)
} else {
ug.Groups = append(ug.Groups, groupName.Name)
}
var gids []string
// resolve the group IDs for the user
gids, err = c.groupIds(osUser)
if err != nil {
return err
}
// we have a list hide the failure to resolve some of the groups and just add them as IDs
for _, gid := range gids {
// skip the primary group if it is in the list
if gid == osUser.Gid {
continue
}
groupName, err = c.lookupGroupID(gid)
if err != nil {
ug.Groups = append(ug.Groups, gid)
} else {
ug.Groups = append(ug.Groups, groupName.Name)
}
}
return nil
}