-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
562 lines (496 loc) · 14.6 KB
/
user.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
package services
import (
"encoding/json"
"fmt"
"time"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
)
// User represents teleport embedded user or external user
type User interface {
// Resource provides common resource properties
Resource
// GetOIDCIdentities returns a list of connected OIDCIdentities
GetOIDCIdentities() []ExternalIdentity
// GetSAMLIdentities returns a list of connected OIDCIdentities
GetSAMLIdentities() []ExternalIdentity
// GetRoles returns a list of roles assigned to user
GetRoles() []string
// String returns user
String() string
// Equals checks if user equals to another
Equals(other User) bool
// GetStatus return user login status
GetStatus() LoginStatus
// SetLocked sets login status to locked
SetLocked(until time.Time, reason string)
// SetRoles sets user roles
SetRoles(roles []string)
// AddRole adds role to the users' role list
AddRole(name string)
// GetCreatedBy returns information about user
GetCreatedBy() CreatedBy
// SetCreatedBy sets created by information
SetCreatedBy(CreatedBy)
// Check checks basic user parameters for errors
Check() error
// GetRawObject returns raw object data, used for migrations
GetRawObject() interface{}
// WebSessionInfo returns web session information about user
WebSessionInfo(allowedLogins []string) interface{}
}
// NewUser creates new empty user
func NewUser(name string) (User, error) {
u := &UserV2{
Kind: KindUser,
Version: V2,
Metadata: Metadata{
Name: name,
Namespace: defaults.Namespace,
},
}
if err := u.Check(); err != nil {
return nil, trace.Wrap(err)
}
return u, nil
}
// ConnectorRef holds information about OIDC connector
type ConnectorRef struct {
// Type is connector type
Type string `json:"type"`
// ID is connector ID
ID string `json:"id"`
// Identity is external identity of the user
Identity string `json:"identity"`
}
// UserRef holds refernce to user
type UserRef struct {
// Name is name of the user
Name string `json:"name"`
}
// CreatedBy holds information about the person or agent who created the user
type CreatedBy struct {
// Identity if present means that user was automatically created by identity
Connector *ConnectorRef `json:"connector,omitempty"`
// Time specifies when user was created
Time time.Time `json:"time"`
// User holds information about user
User UserRef `json:"user"`
}
const CreatedBySchema = `{
"type": "object",
"additionalProperties": false,
"properties": {
"connector": {
"additionalProperties": false,
"type": "object",
"properties": {
"type": {"type": "string"},
"id": {"type": "string"},
"identity": {"type": "string"}
}
},
"time": {"type": "string"},
"user": {
"type": "object",
"additionalProperties": false,
"properties": {"name": {"type": "string"}}
}
}
}`
// IsEmpty returns true if there's no info about who created this user
func (c CreatedBy) IsEmpty() bool {
return c.User.Name == ""
}
// String returns human readable information about the user
func (c CreatedBy) String() string {
if c.User.Name == "" {
return "system"
}
if c.Connector != nil {
return fmt.Sprintf("%v connector %v for user %v at %v",
c.Connector.Type, c.Connector.ID, c.Connector.Identity, utils.HumanTimeFormat(c.Time))
}
return fmt.Sprintf("%v at %v", c.User.Name, c.Time)
}
// LoginStatus is a login status of the user
type LoginStatus struct {
// IsLocked tells us if user is locked
IsLocked bool `json:"is_locked"`
// LockedMessage contains the message in case if user is locked
LockedMessage string `json:"locked_message,omitempty"`
// LockedTime contains time when user was locked
LockedTime time.Time `json:"locked_time,omitempty"`
// LockExpires contains time when this lock will expire
LockExpires time.Time `json:"lock_expires,omitempty"`
}
const LoginStatusSchema = `{
"type": "object",
"additionalProperties": false,
"properties": {
"is_locked": {"type": "boolean"},
"locked_message": {"type": "string"},
"locked_time": {"type": "string"},
"lock_expires": {"type": "string"}
}
}`
// LoginAttempt represents successfull or unsuccessful attempt for user to login
type LoginAttempt struct {
// Time is time of the attempt
Time time.Time `json:"time"`
// Sucess indicates whether attempt was successfull
Success bool `json:"bool"`
}
// Check checks parameters
func (la *LoginAttempt) Check() error {
if la.Time.IsZero() {
return trace.BadParameter("missing parameter time")
}
return nil
}
// UserV2 is version1 resource spec of the user
type UserV2 struct {
// Kind is a resource kind
Kind string `json:"kind"`
// Version is version
Version string `json:"version"`
// Metadata is User metadata
Metadata Metadata `json:"metadata"`
// Spec contains user specification
Spec UserSpecV2 `json:"spec"`
// rawObject contains raw object representation
rawObject interface{}
}
// GetMetadata returns object metadata
func (u *UserV2) GetMetadata() Metadata {
return u.Metadata
}
// SetExpiry sets expiry time for the object
func (u *UserV2) SetExpiry(expires time.Time) {
u.Metadata.SetExpiry(expires)
}
// SetTTL sets Expires header using realtime clock
func (u *UserV2) SetTTL(clock clockwork.Clock, ttl time.Duration) {
u.Metadata.SetTTL(clock, ttl)
}
// GetName returns the name of the User
func (u *UserV2) GetName() string {
return u.Metadata.Name
}
// SetName sets the name of the User
func (u *UserV2) SetName(e string) {
u.Metadata.Name = e
}
// WebSessionInfo returns web session information about user
func (u *UserV2) WebSessionInfo(allowedLogins []string) interface{} {
out := u.V1()
out.AllowedLogins = allowedLogins
return *out
}
// UserSpecV2 is a specification for V2 user
type UserSpecV2 struct {
// OIDCIdentities lists associated OpenID Connect identities
// that let user log in using externally verified identity
OIDCIdentities []ExternalIdentity `json:"oidc_identities,omitempty"`
// SAMLIdentities lists associated SAML identities
// that let user log in using externally verified identity
SAMLIdentities []ExternalIdentity `json:"saml_identities,omitempty"`
// Roles is a list of roles assigned to user
Roles []string `json:"roles,omitempty"`
// Status is a login status of the user
Status LoginStatus `json:"status"`
// Expires if set sets TTL on the user
Expires time.Time `json:"expires"`
// CreatedBy holds information about agent or person created this usre
CreatedBy CreatedBy `json:"created_by"`
}
// V1 converts UserV2 to UserV1 format
func (u *UserV2) V1() *UserV1 {
return &UserV1{
Name: u.Metadata.Name,
OIDCIdentities: u.Spec.OIDCIdentities,
Status: u.Spec.Status,
Expires: u.Spec.Expires,
CreatedBy: u.Spec.CreatedBy,
}
}
// V2 converts UserV2 to UserV2 format
func (u *UserV2) V2() *UserV2 {
return u
}
// UserSpecV2SchemaTemplate is JSON schema for V2 user
const UserSpecV2SchemaTemplate = `{
"type": "object",
"additionalProperties": false,
"properties": {
"expires": {"type": "string"},
"roles": {
"type": "array",
"items": {
"type": "string"
}
},
"oidc_identities": {
"type": "array",
"items": %v
},
"saml_identities": {
"type": "array",
"items": %v
},
"status": %v,
"created_by": %v%v
}
}`
// GetObject returns raw object data, used for migrations
func (u *UserV2) GetRawObject() interface{} {
return u.rawObject
}
// SetCreatedBy sets created by information
func (u *UserV2) SetCreatedBy(b CreatedBy) {
u.Spec.CreatedBy = b
}
// GetCreatedBy returns information about who created user
func (u *UserV2) GetCreatedBy() CreatedBy {
return u.Spec.CreatedBy
}
// Equals checks if user equals to another
func (u *UserV2) Equals(other User) bool {
if u.Metadata.Name != other.GetName() {
return false
}
otherIdentities := other.GetOIDCIdentities()
if len(u.Spec.OIDCIdentities) != len(otherIdentities) {
return false
}
for i := range u.Spec.OIDCIdentities {
if !u.Spec.OIDCIdentities[i].Equals(&otherIdentities[i]) {
return false
}
}
otherSAMLIdentities := other.GetSAMLIdentities()
if len(u.Spec.SAMLIdentities) != len(otherSAMLIdentities) {
return false
}
for i := range u.Spec.SAMLIdentities {
if !u.Spec.SAMLIdentities[i].Equals(&otherSAMLIdentities[i]) {
return false
}
}
return true
}
// Expiry returns expiry time for temporary users
func (u *UserV2) Expiry() time.Time {
if !u.Metadata.Expires.IsZero() {
return u.Metadata.Expires
}
return u.Spec.Expires
}
// SetRoles sets a list of roles for user
func (u *UserV2) SetRoles(roles []string) {
u.Spec.Roles = utils.Deduplicate(roles)
}
// GetStatus returns login status of the user
func (u *UserV2) GetStatus() LoginStatus {
return u.Spec.Status
}
// GetOIDCIdentities returns a list of connected OIDCIdentities
func (u *UserV2) GetOIDCIdentities() []ExternalIdentity {
return u.Spec.OIDCIdentities
}
// GetSAMLIdentities returns a list of connected SAMLIdentities
func (u *UserV2) GetSAMLIdentities() []ExternalIdentity {
return u.Spec.SAMLIdentities
}
// GetRoles returns a list of roles assigned to user
func (u *UserV2) GetRoles() []string {
return u.Spec.Roles
}
// AddRole adds a role to user's role list
func (u *UserV2) AddRole(name string) {
for _, r := range u.Spec.Roles {
if r == name {
return
}
}
u.Spec.Roles = append(u.Spec.Roles, name)
}
func (u *UserV2) String() string {
return fmt.Sprintf("User(name=%v, roles=%v, identities=%v)", u.Metadata.Name, u.Spec.Roles, u.Spec.OIDCIdentities)
}
func (u *UserV2) SetLocked(until time.Time, reason string) {
u.Spec.Status.IsLocked = true
u.Spec.Status.LockExpires = until
u.Spec.Status.LockedMessage = reason
}
// Check checks validity of all parameters
func (u *UserV2) Check() error {
if u.Kind == "" {
return trace.BadParameter("user kind is not set")
}
if u.Version == "" {
return trace.BadParameter("user version is not set")
}
if u.Metadata.Name == "" {
return trace.BadParameter("user name cannot be empty")
}
for _, id := range u.Spec.OIDCIdentities {
if err := id.Check(); err != nil {
return trace.Wrap(err)
}
}
return nil
}
// UserV1 is V1 version of the user
type UserV1 struct {
// Name is a user name
Name string `json:"name"`
// AllowedLogins represents a list of OS users this teleport
// user is allowed to login as
AllowedLogins []string `json:"allowed_logins"`
// OIDCIdentities lists associated OpenID Connect identities
// that let user log in using externally verified identity
OIDCIdentities []ExternalIdentity `json:"oidc_identities"`
// Status is a login status of the user
Status LoginStatus `json:"status"`
// Expires if set sets TTL on the user
Expires time.Time `json:"expires"`
// CreatedBy holds information about agent or person created this usre
CreatedBy CreatedBy `json:"created_by"`
// Roles is a list of roles
Roles []string `json:"roles"`
}
// Check checks validity of all parameters
func (u *UserV1) Check() error {
if u.Name == "" {
return trace.BadParameter("user name cannot be empty")
}
for _, id := range u.OIDCIdentities {
if err := id.Check(); err != nil {
return trace.Wrap(err)
}
}
return nil
}
//V1 returns itself
func (u *UserV1) V1() *UserV1 {
return u
}
//V2 converts UserV1 to UserV2 format
func (u *UserV1) V2() *UserV2 {
return &UserV2{
Kind: KindUser,
Version: V2,
Metadata: Metadata{
Name: u.Name,
Namespace: defaults.Namespace,
},
Spec: UserSpecV2{
OIDCIdentities: u.OIDCIdentities,
Status: u.Status,
Expires: u.Expires,
CreatedBy: u.CreatedBy,
Roles: u.Roles,
},
rawObject: *u,
}
}
var userMarshaler UserMarshaler = &TeleportUserMarshaler{}
// SetUserMarshaler sets global user marshaler
func SetUserMarshaler(u UserMarshaler) {
marshalerMutex.Lock()
defer marshalerMutex.Unlock()
userMarshaler = u
}
// GetUserMarshaler returns currently set user marshaler
func GetUserMarshaler() UserMarshaler {
marshalerMutex.RLock()
defer marshalerMutex.RUnlock()
return userMarshaler
}
// UserMarshaler implements marshal/unmarshal of User implementations
// mostly adds support for extended versions
type UserMarshaler interface {
// UnmarshalUser from binary representation
UnmarshalUser(bytes []byte) (User, error)
// MarshalUser to binary representation
MarshalUser(u User, opts ...MarshalOption) ([]byte, error)
// GenerateUser generates new user based on standard teleport user
// it gives external implementations to add more app-specific
// data to the user
GenerateUser(User) (User, error)
}
// GetRoleSchema returns role schema with optionally injected
// schema for extensions
func GetUserSchema(extensionSchema string) string {
var userSchema string
if extensionSchema == "" {
userSchema = fmt.Sprintf(UserSpecV2SchemaTemplate, ExternalIdentitySchema, ExternalIdentitySchema, LoginStatusSchema, CreatedBySchema, ``)
} else {
userSchema = fmt.Sprintf(UserSpecV2SchemaTemplate, ExternalIdentitySchema, ExternalIdentitySchema, LoginStatusSchema, CreatedBySchema, ", "+extensionSchema)
}
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, userSchema)
}
type TeleportUserMarshaler struct{}
// UnmarshalUser unmarshals user from JSON
func (*TeleportUserMarshaler) UnmarshalUser(bytes []byte) (User, error) {
var h ResourceHeader
err := json.Unmarshal(bytes, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case "":
var u UserV1
err := json.Unmarshal(bytes, &u)
if err != nil {
return nil, trace.Wrap(err)
}
return u.V2(), nil
case V2:
var u UserV2
if err := utils.UnmarshalWithSchema(GetUserSchema(""), &u, bytes); err != nil {
return nil, trace.BadParameter(err.Error())
}
utils.UTC(&u.Metadata.Expires)
u.rawObject = u
return &u, nil
}
return nil, trace.BadParameter("user resource version %v is not supported", h.Version)
}
// GenerateUser generates new user
func (*TeleportUserMarshaler) GenerateUser(in User) (User, error) {
return in, nil
}
// MarshalUser marshalls user into JSON
func (*TeleportUserMarshaler) MarshalUser(u User, opts ...MarshalOption) ([]byte, error) {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type userv1 interface {
V1() *UserV1
}
type userv2 interface {
V2() *UserV2
}
version := cfg.GetVersion()
switch version {
case V1:
v, ok := u.(userv1)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V1)
}
return json.Marshal(v.V1())
case V2:
v, ok := u.(userv2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
return json.Marshal(v.V2())
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
}