forked from ctdk/goiardi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
659 lines (611 loc) · 15.7 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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/*
* Copyright (c) 2013-2017, Jeremy Bingham (<jeremy@goiardi.gl>)
*
* Licensed 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 user is the result of users and clients ended up having to be split
// apart after all, once adding the SQL backing started falling into place.
// Users are very similar to clients, except that they are unique across the
// whole server and can log in via the web interface, while clients are only
// unique across an organization and cannot log in over the web. Basically,
// users are generally for something you would do, while a client would be
// associated with a specific node.
//
// Note: At this time, organizations are not implemented, so the difference
// between clients and users is a little less stark.
package user
import (
"bytes"
"database/sql"
"encoding/gob"
"fmt"
"github.com/ctdk/chefcrypto"
"github.com/ctdk/goiardi/config"
"github.com/ctdk/goiardi/datastore"
"github.com/ctdk/goiardi/secret"
"github.com/ctdk/goiardi/util"
"github.com/tideland/golib/logger"
"net/http"
)
// User is, uh, a user. It's very similar to a Client, but subtly different, as
// explained elsewhere.
type User struct {
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
Admin bool `json:"admin"`
pubKey string
passwd string
salt []byte
}
type privUser struct {
Username *string `json:"username"`
Name *string `json:"name"`
Email *string `json:"email"`
Admin *bool `json:"admin"`
PublicKey *string `json:"public_key"`
Passwd *string `json:"password"`
Salt *[]byte `json:"salt"`
}
// New creates a new API user.
func New(name string) (*User, util.Gerror) {
var found bool
var err util.Gerror
if config.UsingDB() {
var uerr error
found, uerr = checkForUserSQL(datastore.Dbh, name)
if uerr != nil {
err = util.Errorf(uerr.Error())
err.SetStatus(http.StatusInternalServerError)
return nil, err
}
} else {
ds := datastore.New()
_, found = ds.Get("user", name)
}
if found {
err := util.Errorf("User '%s' already exists", name)
err.SetStatus(http.StatusConflict)
return nil, err
}
if err := validateUserName(name); err != nil {
return nil, err
}
salt, saltErr := chefcrypto.GenerateSalt()
if saltErr != nil {
err := util.Errorf(saltErr.Error())
return nil, err
}
user := &User{
Username: name,
Name: name,
Admin: false,
Email: "",
pubKey: "",
salt: salt,
}
return user, nil
}
// Get a user.
func Get(name string) (*User, util.Gerror) {
var user *User
if config.UsingDB() {
var err error
user, err = getUserSQL(name)
if err != nil {
var gerr util.Gerror
if err != sql.ErrNoRows {
gerr = util.Errorf(err.Error())
gerr.SetStatus(http.StatusInternalServerError)
} else {
gerr = util.Errorf("Client %s not found", name)
gerr.SetStatus(http.StatusNotFound)
}
return nil, gerr
}
} else {
ds := datastore.New()
u, found := ds.Get("user", name)
if !found {
err := util.Errorf("User %s not found", name)
return nil, err
}
if u != nil {
user = u.(*User)
}
}
return user, nil
}
// DoesExist checks if the user in question exists or not
func DoesExist(userName string) (bool, util.Gerror) {
var found bool
if config.UsingDB() {
var cerr error
found, cerr = checkForUserSQL(datastore.Dbh, userName)
if cerr != nil {
err := util.Errorf(cerr.Error())
err.SetStatus(http.StatusInternalServerError)
return false, err
}
} else {
ds := datastore.New()
_, found = ds.Get("user", userName)
}
return found, nil
}
// Save the user's current state.
func (u *User) Save() util.Gerror {
if config.UsingDB() {
var err util.Gerror
if config.Config.UseMySQL {
err = u.saveMySQL()
} else {
err = u.savePostgreSQL()
}
if err != nil {
return err
}
} else {
if err := chkInMemClient(u.Username); err != nil {
gerr := util.Errorf(err.Error())
gerr.SetStatus(http.StatusConflict)
return gerr
}
ds := datastore.New()
ds.Set("user", u.Username, u)
}
return nil
}
// Delete a user, but will refuse to do so and give an error if it is the last
// administrator user.
func (u *User) Delete() util.Gerror {
if u.isLastAdmin() {
err := util.Errorf("Cannot delete the last admin")
return err
}
if config.UsingDB() {
err := u.deleteSQL()
if err != nil {
gerr := util.CastErr(err)
return gerr
}
} else {
ds := datastore.New()
ds.Delete("user", u.Username)
}
if config.UsingExternalSecrets() {
err := secret.DeletePublicKey(u)
if err != nil {
return util.CastErr(err)
}
err = secret.DeletePasswdHash(u)
if err != nil {
return util.CastErr(err)
}
}
return nil
}
// Rename a user. Save() must be called after this method is used. Will not
// rename the last administrator user.
func (u *User) Rename(newName string) util.Gerror {
if err := validateUserName(newName); err != nil {
return err
}
if u.isLastAdmin() {
err := util.Errorf("Cannot rename the last admin")
err.SetStatus(http.StatusForbidden)
return err
}
var pk string
var pw string
if config.UsingExternalSecrets() {
pk = u.PublicKey()
pw = u.Passwd()
err := secret.DeletePublicKey(u)
if err != nil {
return util.CastErr(err)
}
err = secret.DeletePasswdHash(u)
if err != nil {
return util.CastErr(err)
}
}
if config.UsingDB() {
if config.Config.UseMySQL {
if err := u.renameMySQL(newName); err != nil {
return err
}
} else if config.Config.UsePostgreSQL {
if err := u.renamePostgreSQL(newName); err != nil {
return err
}
}
} else {
ds := datastore.New()
if err := chkInMemClient(newName); err != nil {
gerr := util.Errorf(err.Error())
gerr.SetStatus(http.StatusConflict)
return gerr
}
if _, found := ds.Get("user", newName); found {
err := util.Errorf("User %s already exists, cannot rename %s", newName, u.Username)
err.SetStatus(http.StatusConflict)
return err
}
ds.Delete("client", u.Username)
}
u.Username = newName
if config.UsingExternalSecrets() {
err := secret.SetPublicKey(u, pk)
if err != nil {
return util.CastErr(err)
}
err = secret.SetPasswdHash(u, pw)
if err != nil {
return util.CastErr(err)
}
}
return nil
}
// NewFromJSON builds a new user from a JSON object.
func NewFromJSON(jsonUser map[string]interface{}) (*User, util.Gerror) {
userName, nerr := util.ValidateAsString(jsonUser["name"])
if nerr != nil {
return nil, nerr
}
user, err := New(userName)
if err != nil {
return nil, err
}
// check if the password is supplied if this is a user, and fail if
// it isn't.
if _, ok := jsonUser["password"]; !ok {
err := util.Errorf("Field 'password' missing")
return nil, err
}
err = user.UpdateFromJSON(jsonUser)
if err != nil {
return nil, err
}
return user, nil
}
// UpdateFromJSON updates a user from a JSON object, carrying out a bunch of
// validations inside.
func (u *User) UpdateFromJSON(jsonUser map[string]interface{}) util.Gerror {
userName, nerr := util.ValidateAsString(jsonUser["name"])
if nerr != nil {
return nerr
}
if u.Username != userName {
err := util.Errorf("User name %s and %s from JSON do not match", u.Username, userName)
return err
}
/* Validations. */
/* Invalid top level elements */
validElements := []string{"username", "name", "org_name", "public_key", "private_key", "admin", "password", "email", "salt"}
ValidElem:
for k := range jsonUser {
for _, i := range validElements {
if k == i {
continue ValidElem
}
}
err := util.Errorf("Invalid key %s in request body", k)
return err
}
var verr util.Gerror
// Check the password first. If it's bad, bail before touching anything
// else.
if passwd, ok := jsonUser["password"]; ok {
passwd, verr = util.ValidateAsString(passwd)
if verr != nil {
return verr
}
if passwd != "" {
verr = u.SetPasswd(passwd.(string))
if verr != nil {
return verr
}
}
}
if adminVal, ok := jsonUser["admin"]; ok {
var ab bool
if ab, verr = util.ValidateAsBool(adminVal); verr != nil {
// NOTE: may need to tweak this error message depending
// if this is a user or a client
verr = util.Errorf("Field 'admin' invalid")
return verr
} else if u.Admin && !ab {
if u.isLastAdmin() {
verr = util.Errorf("Cannot remove admin status from the last admin")
verr.SetStatus(http.StatusForbidden)
return verr
}
}
u.Admin = ab
}
return nil
}
// SetPasswdHash is a utility function to directly set a password hash. Only
// especially useful when importing user data with the -m/--import flags, since
// it's still hashed with the user's salt.
func (u *User) SetPasswdHash(pwhash string) {
if pwhash != "" {
if config.UsingExternalSecrets() {
secret.SetPasswdHash(u, pwhash)
} else {
u.passwd = pwhash
}
}
}
// GetList returns a list of users.
func GetList() []string {
var userList []string
if config.UsingDB() {
userList = getListSQL()
} else {
ds := datastore.New()
userList = ds.GetList("user")
}
return userList
}
// ToJSON converts the user to a JSON object, massaging it as needed to keep
// the chef client happy (be it knife, chef-pedant, etc.) NOTE: There may be a
// more idiomatic way to do this.
func (u *User) ToJSON() map[string]interface{} {
toJSON := make(map[string]interface{})
toJSON["name"] = u.Name
toJSON["admin"] = u.Admin
toJSON["public_key"] = u.PublicKey()
return toJSON
}
func (u *User) isLastAdmin() bool {
if u.Admin {
numAdmins := 0
if config.UsingDB() {
numAdmins = numAdminsSQL()
} else {
userList := GetList()
for _, u := range userList {
u1, _ := Get(u)
if u1 != nil && u1.Admin {
numAdmins++
}
}
}
if numAdmins == 1 {
return true
}
}
return false
}
// GenerateKeys generates a new set of RSA keys for the user. The new private
// key is saved with the user object, the public key is given to the user and
// not saved on the server at all.
func (u *User) GenerateKeys() (string, error) {
privPem, pubPem, err := chefcrypto.GenerateRSAKeys()
if err != nil {
return "", err
}
u.SetPublicKey(pubPem)
return privPem, nil
}
// ValidatePublicKey checks that the provided public key is valid. Wrapper
// around chefcrypto.ValidatePublicKey(), but with a different error type.
func ValidatePublicKey(publicKey interface{}) (bool, util.Gerror) {
ok, pkerr := chefcrypto.ValidatePublicKey(publicKey)
var err util.Gerror
if !ok {
err = util.CastErr(pkerr)
}
return ok, err
}
// IsAdmin returns true if the user is an admin. If use-auth is false, this
// always returns true.
func (u *User) IsAdmin() bool {
if !config.Config.UseAuth {
return true
}
return u.Admin
}
// IsValidator always returns false, since users are never validators. This is
// true even if auth mode is not on.
func (u *User) IsValidator() bool {
return false
}
// IsSelf returns true if the actor in question s the same client or user as the
// caller. Always returns true if use-auth is false.
func (u *User) IsSelf(other interface{}) bool {
if !config.Config.UseAuth {
return true
}
if ou, ok := other.(*User); ok {
if u.Username == ou.Username {
return true
}
}
return false
}
// IsUser returns true for users.
func (u *User) IsUser() bool {
return true
}
// IsClient returns false for users.
func (u *User) IsClient() bool {
return false
}
// PublicKey returns the user's public key. Part of the Actor interface.
func (u *User) PublicKey() string {
if config.UsingExternalSecrets() {
pk, err := secret.GetPublicKey(u)
if err != nil {
// pubKey's not goign to work very well if we can't get
// it....
logger.Errorf(err.Error())
return ""
}
return pk
}
return u.pubKey
}
// SetPublicKey does what it says on the tin. Part of the Actor interface.
func (u *User) SetPublicKey(pk interface{}) error {
switch pk := pk.(type) {
case string:
ok, err := ValidatePublicKey(pk)
if !ok {
return err
}
if config.UsingExternalSecrets() {
secret.SetPublicKey(u, pk)
} else {
u.pubKey = pk
}
default:
err := fmt.Errorf("invalid type %T for public key", pk)
return err
}
return nil
}
// CheckPermEdit checks to see if the user is trying to edit admin and
// validator attributes, and if it has permissions to do so.
func (u *User) CheckPermEdit(userData map[string]interface{}, perm string) util.Gerror {
gerr := util.Errorf("You are not allowed to take this action.")
gerr.SetStatus(http.StatusForbidden)
if av, ok := userData[perm]; ok {
if a, _ := util.ValidateAsBool(av); a {
return gerr
}
}
return nil
}
// SetPasswd validates and sets the user's password. Will not set a password for
// a client.
func (u *User) SetPasswd(password string) util.Gerror {
if len(password) < 6 {
err := util.Errorf("Password must have at least 6 characters")
return err
}
/* If those validations pass, set the password */
pw, perr := chefcrypto.HashPasswd(password, u.salt)
if perr != nil {
err := util.Errorf(perr.Error())
return err
}
if config.UsingExternalSecrets() {
err := secret.SetPasswdHash(u, pw)
if err != nil {
return util.CastErr(err)
}
} else {
u.passwd = pw
}
return nil
}
// CheckPasswd checks the provided password to see if it matches the stored
// password hash.
func (u *User) CheckPasswd(password string) util.Gerror {
h, perr := chefcrypto.HashPasswd(password, u.salt)
if perr != nil {
err := util.Errorf(perr.Error())
return err
}
if u.Passwd() != h {
err := util.Errorf("password did not match")
return err
}
return nil
}
// Passwd returns the password hash, either from the user object or an external
// secret store
func (u *User) Passwd() string {
if config.UsingExternalSecrets() {
pw, err := secret.GetPasswdHash(u)
if err != nil {
logger.Errorf(err.Error())
}
return pw
}
return u.passwd
}
func validateUserName(name string) util.Gerror {
if !util.ValidateUserName(name) {
err := util.Errorf("Field 'name' invalid")
return err
}
return nil
}
// GetName returns the user's name.
func (u *User) GetName() string {
return u.Username
}
// URLType returns the base element of a user's URL.
func (u *User) URLType() string {
return "users"
}
func (u *User) export() *privUser {
return &privUser{Name: &u.Name, Username: &u.Username, PublicKey: &u.pubKey, Admin: &u.Admin, Email: &u.Email, Passwd: &u.passwd, Salt: &u.salt}
}
func (u *User) GobEncode() ([]byte, error) {
prv := u.export()
buf := new(bytes.Buffer)
decoder := gob.NewEncoder(buf)
if err := decoder.Encode(prv); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (u *User) GobDecode(b []byte) error {
prv := u.export()
buf := bytes.NewReader(b)
encoder := gob.NewDecoder(buf)
err := encoder.Decode(prv)
if err != nil {
return err
}
return nil
}
// AllUsers returns all the users on this server.
func AllUsers() []*User {
var users []*User
if config.UsingDB() {
users = allUsersSQL()
} else {
userList := GetList()
for _, u := range userList {
us, err := Get(u)
if err != nil {
continue
}
users = append(users, us)
}
}
return users
}
// ExportAllUsers return all users, in a fashion suitable for exporting.
func ExportAllUsers() []interface{} {
users := AllUsers()
export := make([]interface{}, len(users))
for i, u := range users {
export[i] = u.export()
}
return export
}
func chkInMemClient(name string) error {
var err error
ds := datastore.New()
if _, found := ds.Get("client", name); found {
err = fmt.Errorf("a client named %s was found that would conflict with this user", name)
}
return err
}