/
subject.go
407 lines (317 loc) · 8.75 KB
/
subject.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package kuro
import (
"encoding/gob"
"errors"
"fmt"
"github.com/jalkanen/kuro/authc"
"github.com/jalkanen/kuro/authz"
"github.com/jalkanen/kuro/session"
"net/http"
"sync"
"bytes"
)
func init() {
gob.Register(PrincipalStack{})
}
/*
A Subject represents the current user in Kuro. Subjects exist even when the user is not logged
in, and in such a case, represent an anonymous user.
However, a Subject is tied to a particular user and never shared with another user.
In an HTTP context, they live through a single
HTTP request. If you wish to maintain some state across subsequent requests, use the Subject's Session.
*/
type Subject interface {
Principal() interface{}
Session() session.Session
HasRole(role string) bool
IsAuthenticated() bool
IsPermitted(permission string) bool
IsPermittedP(permission authz.Permission) bool
Login(authc.AuthenticationToken) error
Logout()
RunAs([]interface{}) error
ReleaseRunAs() ([]interface{}, error)
IsRunAs() bool
PreviousPrincipals() []interface{}
IsRemembered() bool
}
/*
Delegator is an implementation of Subject that just delegates all the Subject's methods to an underlying
SecurityManager instance.
*/
type Delegator struct {
principals []interface{}
mgr SecurityManager
authenticated bool
session session.Session
createSessions bool
request *http.Request
response http.ResponseWriter
}
const (
sessionPrincipalsKey = "__principals"
sessionAuthenticatedKey = "__authenticated"
sessionRunAsKey = "__principalstack"
)
func newSubject(securityManager SecurityManager, ctx SubjectContext) *Delegator {
d := Delegator{
mgr: securityManager,
authenticated: ctx.Authenticated,
principals: ctx.Principals,
createSessions: ctx.CreateSessions,
request: ctx.Request,
response: ctx.ResponseWriter,
}
return &d
}
var lock sync.Mutex
var subjects map[interface{}]Subject = make(map[interface{}]Subject, 64)
// Gets the current subject which is related to the given object. Typically, you would
// use something like *http.Request as the "where" interface. Every call must be paired
// with a corresponding call to Finish()
// The Subject itself can be shared among goroutines.
// This only works with the global SecurityManager
func Get(r *http.Request, w http.ResponseWriter) Subject {
lock.Lock()
defer lock.Unlock()
subject := subjects[r]
if subject == nil {
sc := SubjectContext{
CreateSessions: true,
Request: r,
ResponseWriter: w,
}
subject, _ = Manager.CreateSubject(&sc)
if d, ok := subject.(*Delegator); ok {
d.load()
}
// Store this one for the request to avoid further calls to the session
subjects[r] = subject
}
return subject
}
func With(where *http.Request, s Subject) {
lock.Lock()
defer lock.Unlock()
subjects[where] = s
}
// Must be called at the end of the request to clear the current subject
func Finish(where *http.Request) {
lock.Lock()
defer lock.Unlock()
delete(subjects, where)
}
// TODO: Should return something else in error?
func (s *Delegator) Principal() interface{} {
p := s.Principals()
if p == nil {
return nil
}
return p[0]
}
func (s *Delegator) Principals() []interface{} {
if !s.hasPrincipals() {
return nil
}
// Check for current RunAs state.
ps, err := s.getPrincipalStack()
if err == nil {
p, _ := ps.Peek()
if p != nil {
return p
}
}
return s.principals
}
func (s *Delegator) Session() session.Session {
if s.session == nil && s.createSessions {
s.session = s.mgr.SessionManager().Start(&session.SessionContext{
Request: s.request,
Response: s.response,
})
}
return s.session
}
func (s *Delegator) HasRole(role string) bool {
return s.hasPrincipals() && s.mgr.HasRole(s.Principals(), role)
}
func (s *Delegator) IsAuthenticated() bool {
return s.authenticated
}
func (s *Delegator) IsRemembered() bool {
return len(s.principals) > 0 && !s.authenticated
}
// Swallows the error in case for simplicity
func (s *Delegator) IsPermitted(permission string) bool {
return s.hasPrincipals() && s.mgr.IsPermitted(s.Principals(), permission)
}
func (s *Delegator) IsPermittedP(permission authz.Permission) bool {
return s.hasPrincipals() && s.mgr.IsPermittedP(s.Principals(), permission)
}
func (s *Delegator) hasPrincipals() bool {
return s.principals != nil && len(s.principals) > 0
}
func (s *Delegator) Login(token authc.AuthenticationToken) error {
s.clearPrincipalStack()
return s.mgr.Login(s, token)
}
func (s *Delegator) Logout() {
s.clearPrincipalStack()
s.mgr.Logout(s)
}
// Stringer. Outputs a nicer version of the subject's principals and whether it is authenticated or not.
func (s *Delegator) String() string {
return fmt.Sprintf("Subject%s(%t)", s.Principals(), s.authenticated)
}
// Load and store the Subject into the store itself. In practice, all
// we need to store are the principals and whether the user is authenticated
// or not.
func (s *Delegator) store() {
session := s.Session()
if session != nil {
session.Set(sessionPrincipalsKey, s.principals)
session.Set(sessionAuthenticatedKey, s.authenticated)
session.Save()
}
}
func (s *Delegator) load() *Delegator {
session := s.Session()
if session != nil {
if p := session.Get(sessionPrincipalsKey); p != nil {
s.principals = p.([]interface{})
}
if a := session.Get(sessionAuthenticatedKey); a != nil {
s.authenticated = a.(bool)
}
}
return s
}
func (s *Delegator) IsRunAs() bool {
ps, err := s.getPrincipalStack()
return !(err != nil || ps == nil || ps.IsEmpty())
}
func (s *Delegator) RunAs(newprincipals []interface{}) error {
if !s.hasPrincipals() {
return errors.New("The Subject does not have any principals yet, so it cannot impersonate another principal.")
}
if len(newprincipals) == 0 {
return errors.New("Must have at least one principal to impersonate.")
}
ps, err := s.getPrincipalStack()
if err != nil {
return err
}
ps.Push(newprincipals)
s.storePrincipalStack(ps)
s.Session().Save()
return nil
}
func (s *Delegator) ReleaseRunAs() ([]interface{}, error) {
if !s.hasPrincipals() {
return nil, errors.New("The Subject does not have any principals yet, so it cannot impersonate another principal.")
}
ps, err := s.getPrincipalStack()
if err != nil {
return nil, err
}
principals, err := ps.Pop()
if ps.IsEmpty() {
s.clearPrincipalStack()
} else {
s.storePrincipalStack(ps)
}
s.Session().Save()
return principals, nil
}
func (s *Delegator) PreviousPrincipals() []interface{} {
ps, err := s.getPrincipalStack()
if err == nil {
p, _ := ps.Peek()
return p
}
return nil
}
func (s *Delegator) clearPrincipalStack() {
if session := s.Session(); session != nil {
session.Del(sessionRunAsKey)
}
}
func (s *Delegator) getPrincipalStack() (*PrincipalStack, error) {
session := s.Session()
if session != nil {
var p *PrincipalStack
ps := session.Get(sessionRunAsKey)
// The thing is that we don't know in which format the session is storing
// our stuff; this is a known problem with Gorilla.
if ps == nil {
p = &PrincipalStack{}
} else if _, ok := ps.(*PrincipalStack); ok {
p = ps.(*PrincipalStack)
} else if _, ok := ps.(PrincipalStack); ok {
pp := ps.(PrincipalStack)
p = &pp
}
return p, nil
}
return nil, errors.New("No session available")
}
func (s *Delegator) storePrincipalStack(ps *PrincipalStack) error {
if ps.IsEmpty() {
return errors.New("Principal stack must contain at least one principal.")
}
if session := s.Session(); session != nil {
session.Set(sessionRunAsKey, ps)
return nil
}
return errors.New("No session available")
}
/****************************************************************/
// Represents principals for RunAs functionality.
type PrincipalStack struct {
Stack [][]interface{}
lock sync.Mutex
}
func (s *PrincipalStack) Push(principals []interface{}) {
s.lock.Lock()
defer s.lock.Unlock()
s.Stack = append(s.Stack, principals)
}
func (s *PrincipalStack) IsEmpty() bool {
s.lock.Lock()
defer s.lock.Unlock()
return len(s.Stack) == 0
}
func (s *PrincipalStack) Pop() ([]interface{}, error) {
s.lock.Lock()
defer s.lock.Unlock()
l := len(s.Stack)
if l == 0 {
return nil, errors.New("Empty stack")
}
res := s.Stack[l-1]
s.Stack = s.Stack[:l-1]
return res, nil
}
func (s *PrincipalStack) Peek() ([]interface{}, error) {
s.lock.Lock()
defer s.lock.Unlock()
l := len(s.Stack)
if l == 0 {
return nil, errors.New("Empty stack")
}
res := s.Stack[l-1]
return res, nil
}
// Provide GOB encoding and decoding.
func (s *PrincipalStack) GobEncode() ([]byte, error) {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
enc.Encode(s.Stack)
return b.Bytes(), nil
}
func (s *PrincipalStack) GobDecode(data []byte) error {
b := bytes.NewBuffer(data)
dec := gob.NewDecoder(b)
err := dec.Decode(&s.Stack)
return err
}