/usr/share/gocode/src/github.com/ctdk/goiardi/client/client.go is in golang-github-ctdk-goiardi-dev 0.11.2-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 660 661 662 663 664 665 666 667 668 | /* The client object */
/*
* Copyright (c) 2013-2016, 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 client defines the Chef clients. Formerly clients and users were the
same kind of object and stored together, but they have now been split apart.
They do both implement the Actor interface, though. Clients are the more usual
case for the nodes interacting with the server, but users are used for the
webui and often for general user (as opposed to node) interactions with the
server.
*/
package client
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/indexer"
"github.com/ctdk/goiardi/secret"
"github.com/ctdk/goiardi/util"
"github.com/tideland/golib/logger"
"net/http"
)
// A Client and a user are very similar, with some small differences - users
// can never be validators, while clients don't have passwords. Generally nodes
// and the like will be clients, while people interacting with the goiardi
// server will be users.
type Client struct {
Name string `json:"name"`
NodeName string `json:"node_name"`
JSONClass string `json:"json_class"`
ChefType string `json:"chef_type"`
Validator bool `json:"validator"`
Orgname string `json:"orgname"`
pubKey string
Admin bool `json:"admin"`
Certificate string `json:"certificate"`
}
// for gob encoding. Needed the json tags for flattening, but that's handled
// by a different struct now. However, they're staying because they may still be
// useful.
type privClient struct {
Name *string `json:"name"`
NodeName *string `json:"node_name"`
JSONClass *string `json:"json_class"`
ChefType *string `json:"chef_type"`
Validator *bool `json:"validator"`
Orgname *string `json:"orgname"`
PublicKey *string `json:"public_key"`
Admin *bool `json:"admin"`
Certificate *string `json:"certificate"`
}
// For flattening. Needs the json tags for flattening.
type flatClient struct {
Name string `json:"name"`
NodeName string `json:"node_name"`
JSONClass string `json:"json_class"`
ChefType string `json:"chef_type"`
Validator bool `json:"validator"`
Orgname string `json:"orgname"`
PublicKey string `json:"public_key"`
Admin bool `json:"admin"`
Certificate string `json:"certificate"`
}
// New creates a new client.
func New(clientname string) (*Client, util.Gerror) {
var found bool
var err util.Gerror
if config.UsingDB() {
var cerr error
found, cerr = checkForClientSQL(datastore.Dbh, clientname)
if cerr != nil {
err = util.Errorf(cerr.Error())
err.SetStatus(http.StatusInternalServerError)
return nil, err
}
} else {
ds := datastore.New()
_, found = ds.Get("client", clientname)
}
if found {
err = util.Errorf("Client already exists")
err.SetStatus(http.StatusConflict)
return nil, err
}
if err := validateClientName(clientname); err != nil {
return nil, err
}
client := &Client{
Name: clientname,
NodeName: clientname,
ChefType: "client",
JSONClass: "Chef::ApiClient",
Validator: false,
Orgname: "",
pubKey: "",
Admin: false,
Certificate: "",
}
return client, nil
}
// Get gets a client from the data store.
func Get(clientname string) (*Client, util.Gerror) {
var client *Client
var err error
if config.UsingDB() {
client, err = getClientSQL(clientname)
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", clientname)
gerr.SetStatus(http.StatusNotFound)
}
return nil, gerr
}
} else {
ds := datastore.New()
c, found := ds.Get("client", clientname)
if !found {
gerr := util.Errorf("Client %s not found", clientname)
gerr.SetStatus(http.StatusNotFound)
return nil, gerr
}
if c != nil {
client = c.(*Client)
}
}
return client, nil
}
// GetMulti gets multiple clients from a given slice of client names.
func GetMulti(clientNames []string) ([]*Client, util.Gerror) {
var clients []*Client
if config.UsingDB() {
var err error
clients, err = getMultiSQL(clientNames)
if err != nil && err != sql.ErrNoRows {
return nil, util.CastErr(err)
}
} else {
clients = make([]*Client, 0, len(clientNames))
for _, c := range clientNames {
co, _ := Get(c)
if co != nil {
clients = append(clients, co)
}
}
}
return clients, nil
}
// Save the client. If a user with the same name as the client exists, returns
// an error. Additionally, if running with MySQL it will return any DB error.
func (c *Client) Save() util.Gerror {
if config.UsingDB() {
var err error
if config.Config.UseMySQL {
err = c.saveMySQL()
} else if config.Config.UsePostgreSQL {
err = c.savePostgreSQL()
}
if err != nil {
return util.CastErr(err)
}
} else {
if err := chkInMemUser(c.Name); err != nil {
return err
}
ds := datastore.New()
ds.Set("client", c.Name, c)
}
indexer.IndexObj(c)
return nil
}
// Delete a client, but will refuse to do so if it is the last client
// that is an adminstrator.
func (c *Client) Delete() error {
// Make sure this isn't the last admin or something
// This will be a *lot* easier with an actual database.
if c.isLastAdmin() {
err := fmt.Errorf("Cannot delete the last admin")
return err
}
if config.UsingDB() {
err := c.deleteSQL()
if err != nil {
return err
}
} else {
ds := datastore.New()
ds.Delete("client", c.Name)
}
indexer.DeleteItemFromCollection("client", c.Name)
if config.UsingExternalSecrets() {
err := secret.DeletePublicKey(c)
if err != nil {
return err
}
}
return nil
}
// ToJSON converts the client object into a JSON object, massaging it as needed
// to make chef-pedant happy.
func (c *Client) ToJSON() map[string]interface{} {
toJSON := make(map[string]interface{})
toJSON["name"] = c.Name
toJSON["admin"] = c.Admin
toJSON["public_key"] = c.PublicKey()
toJSON["validator"] = c.Validator
toJSON["json_class"] = c.JSONClass
toJSON["chef_type"] = c.ChefType
return toJSON
}
func (c *Client) isLastAdmin() bool {
if c.Admin {
numAdmins := 0
if config.UsingDB() {
numAdmins = numAdminsSQL()
} else {
clist := GetList()
for _, cc := range clist {
c1, _ := Get(cc)
if c1 != nil && c1.Admin {
numAdmins++
}
}
}
if numAdmins == 1 {
return true
}
}
return false
}
// Rename the client. Save() must be called after this method is used.
// Will not rename the last admin.
func (c *Client) Rename(newName string) util.Gerror {
if err := validateClientName(newName); err != nil {
return err
}
if c.isLastAdmin() {
err := util.Errorf("Cannot rename the last admin")
err.SetStatus(http.StatusForbidden)
return err
}
var pk string
if config.UsingExternalSecrets() {
pk = c.PublicKey()
err := secret.DeletePublicKey(c)
if err != nil {
return util.CastErr(err)
}
}
if config.UsingDB() {
var err util.Gerror
if config.Config.UseMySQL {
err = c.renameMySQL(newName)
} else if config.Config.UsePostgreSQL {
err = c.renamePostgreSQL(newName)
}
if err != nil {
return err
}
} else {
if err := chkInMemUser(newName); err != nil {
gerr := util.Errorf(err.Error())
gerr.SetStatus(http.StatusConflict)
return gerr
}
ds := datastore.New()
if _, found := ds.Get("client", newName); found {
err := util.Errorf("Client %s already exists, cannot rename %s", newName, c.Name)
err.SetStatus(http.StatusConflict)
return err
}
ds.Delete("client", c.Name)
}
c.Name = newName
if config.UsingExternalSecrets() {
err := secret.SetPublicKey(c, pk)
if err != nil {
return util.CastErr(err)
}
}
return nil
}
// NewFromJSON builds a new client/user from a json object.
func NewFromJSON(jsonActor map[string]interface{}) (*Client, util.Gerror) {
actorName, nerr := util.ValidateAsString(jsonActor["name"])
if nerr != nil {
return nil, nerr
}
client, err := New(actorName)
if err != nil {
return nil, err
}
err = client.UpdateFromJSON(jsonActor)
if err != nil {
return nil, err
}
return client, nil
}
// UpdateFromJSON updates a client/user from a json object. Does a bunch of
// validations inside rather than in the handler.
func (c *Client) UpdateFromJSON(jsonActor map[string]interface{}) util.Gerror {
actorName, nerr := util.ValidateAsString(jsonActor["name"])
if nerr != nil {
return nerr
}
if c.Name != actorName {
err := util.Errorf("Client name %s and %s from JSON do not match", c.Name, actorName)
return err
}
/* Validations. */
/* Invalid top level elements */
validElements := []string{"name", "json_class", "chef_type", "validator", "org_name", "orgname", "public_key", "private_key", "admin", "certificate", "password", "node_name", "clientname"}
ValidElem:
for k := range jsonActor {
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
jsonActor["json_class"], verr = util.ValidateAsFieldString(jsonActor["json_class"])
if verr != nil {
if verr.Error() == "Field 'name' nil" {
jsonActor["json_class"] = c.JSONClass
} else {
return verr
}
} else {
if jsonActor["json_class"].(string) != "Chef::ApiClient" {
verr = util.Errorf("Field 'json_class' invalid")
return verr
}
}
jsonActor["chef_type"], verr = util.ValidateAsFieldString(jsonActor["chef_type"])
if verr != nil {
if verr.Error() == "Field 'name' nil" {
jsonActor["chef_type"] = c.ChefType
} else {
return verr
}
} else {
if jsonActor["chef_type"].(string) != "client" {
verr = util.Errorf("Field 'chef_type' invalid")
return verr
}
}
var ab, vb bool
if adminVal, ok := jsonActor["admin"]; ok {
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 c.Admin && !ab {
if c.isLastAdmin() {
verr = util.Errorf("Cannot remove admin status from the last admin")
verr.SetStatus(http.StatusForbidden)
return verr
}
}
}
if validatorVal, ok := jsonActor["validator"]; ok {
if vb, verr = util.ValidateAsBool(validatorVal); verr != nil {
return verr
}
}
if ab && vb {
verr = util.Errorf("Client can be either an admin or a validator, but not both.")
verr.SetStatus(http.StatusBadRequest)
return verr
}
c.Admin = ab
c.Validator = vb
c.ChefType = jsonActor["chef_type"].(string)
c.JSONClass = jsonActor["json_class"].(string)
return 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
}
// GetList returns a list of clients.
func GetList() []string {
var clientList []string
if config.UsingDB() {
clientList = getListSQL()
} else {
ds := datastore.New()
clientList = ds.GetList("client")
}
return clientList
}
// GenerateKeys makes a new set of RSA keys for the client. The new private key
// is saved with the client, the public key is given to the client and not saved
// on the server at all.
func (c *Client) GenerateKeys() (string, error) {
privPem, pubPem, err := chefcrypto.GenerateRSAKeys()
if err != nil {
return "", err
}
c.SetPublicKey(pubPem)
return privPem, nil
}
// GetName gives the client's name.
func (c *Client) GetName() string {
return c.Name
}
// URLType returns the base URL element for clients.
func (c *Client) URLType() string {
urlType := fmt.Sprintf("%ss", c.ChefType)
return urlType
}
func validateClientName(name string) util.Gerror {
if !util.ValidateName(name) {
err := util.Errorf("Invalid client name '%s' using regex: 'Malformed client name. Must be A-Z, a-z, 0-9, _, -, or .'.", name)
return err
}
return nil
}
/* Search indexing functions */
// DocID is for the indexer, to tell what it's identifier is.
func (c *Client) DocID() string {
return c.Name
}
// Index tells the indexer which collection of objects to place the client into.
func (c *Client) Index() string {
return "client"
}
// Flatten out the client so it's suitable for indexing.
func (c *Client) Flatten() map[string]interface{} {
return util.FlattenObj(c.flatExport())
}
/* Permission functions. Later role-based perms may be implemented, but for now
* it's just the basic admin/validator/user perms */
// IsAdmin returns true if the client is an admin. If use-auth is false, this
// always returns true.
func (c *Client) IsAdmin() bool {
if !useAuth() {
return true
}
return c.Admin
}
// IsValidator returns true if the client is a validator client. If use-auth is
// false, this always returns false.
func (c *Client) IsValidator() bool {
if !useAuth() {
return false
}
if c.ChefType == "client" && c.Validator {
return c.Validator
}
return false
}
// IsSelf returns true if the other actor provided is the same as the caller.
func (c *Client) IsSelf(other interface{}) bool {
if !useAuth() {
return true
}
if oc, ok := other.(*Client); ok {
if c.Name == oc.Name {
return true
}
}
return false
}
// IsUser always returns false for clients. Part of the Actor interface.
func (c *Client) IsUser() bool {
return false
}
// IsClient always returns true for clients. Part of the Actor interface.
func (c *Client) IsClient() bool {
return true
}
// PublicKey returns the client's public key. Part of the Actor interface.
func (c *Client) PublicKey() string {
if config.UsingExternalSecrets() {
pk, err := secret.GetPublicKey(c)
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 c.pubKey
}
// SetPublicKey sets the client's public key.
func (c *Client) SetPublicKey(pk interface{}) error {
switch pk := pk.(type) {
case string:
ok, err := ValidatePublicKey(pk)
if !ok {
return err
}
if config.UsingExternalSecrets() {
secret.SetPublicKey(c, pk)
} else {
c.pubKey = pk
}
default:
err := fmt.Errorf("invalid type %T for public key", pk)
return err
}
return nil
}
// CheckPermEdit checks to see if the client is trying to edit admin and
// validator attributes, and if it has permissions to do so.
func (c *Client) CheckPermEdit(clientData 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 := clientData[perm]; ok {
if a, _ := util.ValidateAsBool(av); a {
return gerr
}
}
return nil
}
/* a check to see if we should do perm checks */
func useAuth() bool {
return config.Config.UseAuth
}
func (c *Client) export() *privClient {
return &privClient{Name: &c.Name, NodeName: &c.NodeName, JSONClass: &c.JSONClass, ChefType: &c.ChefType, Validator: &c.Validator, Orgname: &c.Orgname, PublicKey: &c.pubKey, Admin: &c.Admin, Certificate: &c.Certificate}
}
func (c *Client) flatExport() *flatClient {
pk := c.PublicKey()
return &flatClient{Name: c.Name, NodeName: c.NodeName, JSONClass: c.JSONClass, ChefType: c.ChefType, Validator: c.Validator, Orgname: c.Orgname, PublicKey: pk, Admin: c.Admin, Certificate: c.Certificate}
}
func (c *Client) GobEncode() ([]byte, error) {
prv := c.export()
buf := new(bytes.Buffer)
decoder := gob.NewEncoder(buf)
if err := decoder.Encode(prv); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (c *Client) GobDecode(b []byte) error {
prv := c.export()
buf := bytes.NewReader(b)
encoder := gob.NewDecoder(buf)
err := encoder.Decode(prv)
if err != nil {
return err
}
return nil
}
// AllClients returns a slice of all the clients on this server.
func AllClients() []*Client {
var clients []*Client
if config.UsingDB() {
clients = allClientsSQL()
} else {
clientList := GetList()
for _, c := range clientList {
cl, err := Get(c)
if err != nil {
continue
}
clients = append(clients, cl)
}
}
return clients
}
// ExportAllClients returns all clients in a fashion suitable for exporting.
func ExportAllClients() []interface{} {
clients := AllClients()
export := make([]interface{}, len(clients))
for i, c := range clients {
export[i] = c.export()
}
return export
}
func chkInMemUser(name string) util.Gerror {
var err util.Gerror
ds := datastore.New()
if _, found := ds.Get("user", name); found {
err = util.Errorf("a user named %s was found that would conflict with this client", name)
err.SetStatus(http.StatusConflict)
}
return err
}
|