auth.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package v2auth implements etcd authentication.
  15. package v2auth
  16. import (
  17. "context"
  18. "encoding/json"
  19. "fmt"
  20. "net/http"
  21. "path"
  22. "reflect"
  23. "sort"
  24. "strings"
  25. "time"
  26. "go.etcd.io/etcd/etcdserver"
  27. "go.etcd.io/etcd/etcdserver/api/v2error"
  28. "go.etcd.io/etcd/etcdserver/etcdserverpb"
  29. "go.etcd.io/etcd/pkg/types"
  30. "github.com/coreos/pkg/capnslog"
  31. "go.uber.org/zap"
  32. "golang.org/x/crypto/bcrypt"
  33. )
  34. const (
  35. // StorePermsPrefix is the internal prefix of the storage layer dedicated to storing user data.
  36. StorePermsPrefix = "/2"
  37. // RootRoleName is the name of the ROOT role, with privileges to manage the cluster.
  38. RootRoleName = "root"
  39. // GuestRoleName is the name of the role that defines the privileges of an unauthenticated user.
  40. GuestRoleName = "guest"
  41. )
  42. var (
  43. plog = capnslog.NewPackageLogger("go.etcd.io/etcd/v3", "etcdserver/auth")
  44. )
  45. var rootRole = Role{
  46. Role: RootRoleName,
  47. Permissions: Permissions{
  48. KV: RWPermission{
  49. Read: []string{"/*"},
  50. Write: []string{"/*"},
  51. },
  52. },
  53. }
  54. var guestRole = Role{
  55. Role: GuestRoleName,
  56. Permissions: Permissions{
  57. KV: RWPermission{
  58. Read: []string{"/*"},
  59. Write: []string{"/*"},
  60. },
  61. },
  62. }
  63. type doer interface {
  64. Do(context.Context, etcdserverpb.Request) (etcdserver.Response, error)
  65. }
  66. type Store interface {
  67. AllUsers() ([]string, error)
  68. GetUser(name string) (User, error)
  69. CreateOrUpdateUser(user User) (out User, created bool, err error)
  70. CreateUser(user User) (User, error)
  71. DeleteUser(name string) error
  72. UpdateUser(user User) (User, error)
  73. AllRoles() ([]string, error)
  74. GetRole(name string) (Role, error)
  75. CreateRole(role Role) error
  76. DeleteRole(name string) error
  77. UpdateRole(role Role) (Role, error)
  78. AuthEnabled() bool
  79. EnableAuth() error
  80. DisableAuth() error
  81. PasswordStore
  82. }
  83. type PasswordStore interface {
  84. CheckPassword(user User, password string) bool
  85. HashPassword(password string) (string, error)
  86. }
  87. type store struct {
  88. lg *zap.Logger
  89. server doer
  90. timeout time.Duration
  91. ensuredOnce bool
  92. PasswordStore
  93. }
  94. type User struct {
  95. User string `json:"user"`
  96. Password string `json:"password,omitempty"`
  97. Roles []string `json:"roles"`
  98. Grant []string `json:"grant,omitempty"`
  99. Revoke []string `json:"revoke,omitempty"`
  100. }
  101. type Role struct {
  102. Role string `json:"role"`
  103. Permissions Permissions `json:"permissions"`
  104. Grant *Permissions `json:"grant,omitempty"`
  105. Revoke *Permissions `json:"revoke,omitempty"`
  106. }
  107. type Permissions struct {
  108. KV RWPermission `json:"kv"`
  109. }
  110. func (p *Permissions) IsEmpty() bool {
  111. return p == nil || (len(p.KV.Read) == 0 && len(p.KV.Write) == 0)
  112. }
  113. type RWPermission struct {
  114. Read []string `json:"read"`
  115. Write []string `json:"write"`
  116. }
  117. type Error struct {
  118. Status int
  119. Errmsg string
  120. }
  121. func (ae Error) Error() string { return ae.Errmsg }
  122. func (ae Error) HTTPStatus() int { return ae.Status }
  123. func authErr(hs int, s string, v ...interface{}) Error {
  124. return Error{Status: hs, Errmsg: fmt.Sprintf("auth: "+s, v...)}
  125. }
  126. func NewStore(lg *zap.Logger, server doer, timeout time.Duration) Store {
  127. s := &store{
  128. lg: lg,
  129. server: server,
  130. timeout: timeout,
  131. PasswordStore: passwordStore{},
  132. }
  133. return s
  134. }
  135. // passwordStore implements PasswordStore using bcrypt to hash user passwords
  136. type passwordStore struct{}
  137. func (passwordStore) CheckPassword(user User, password string) bool {
  138. err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
  139. return err == nil
  140. }
  141. func (passwordStore) HashPassword(password string) (string, error) {
  142. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  143. return string(hash), err
  144. }
  145. func (s *store) AllUsers() ([]string, error) {
  146. resp, err := s.requestResource("/users/", false)
  147. if err != nil {
  148. if e, ok := err.(*v2error.Error); ok {
  149. if e.ErrorCode == v2error.EcodeKeyNotFound {
  150. return []string{}, nil
  151. }
  152. }
  153. return nil, err
  154. }
  155. var nodes []string
  156. for _, n := range resp.Event.Node.Nodes {
  157. _, user := path.Split(n.Key)
  158. nodes = append(nodes, user)
  159. }
  160. sort.Strings(nodes)
  161. return nodes, nil
  162. }
  163. func (s *store) GetUser(name string) (User, error) { return s.getUser(name, false) }
  164. // CreateOrUpdateUser should be only used for creating the new user or when you are not
  165. // sure if it is a create or update. (When only password is passed in, we are not sure
  166. // if it is a update or create)
  167. func (s *store) CreateOrUpdateUser(user User) (out User, created bool, err error) {
  168. _, err = s.getUser(user.User, true)
  169. if err == nil {
  170. out, err = s.UpdateUser(user)
  171. return out, false, err
  172. }
  173. u, err := s.CreateUser(user)
  174. return u, true, err
  175. }
  176. func (s *store) CreateUser(user User) (User, error) {
  177. // Attach root role to root user.
  178. if user.User == "root" {
  179. user = attachRootRole(user)
  180. }
  181. u, err := s.createUserInternal(user)
  182. if err == nil {
  183. if s.lg != nil {
  184. s.lg.Info("created a user", zap.String("user-name", user.User))
  185. } else {
  186. plog.Noticef("created user %s", user.User)
  187. }
  188. }
  189. return u, err
  190. }
  191. func (s *store) createUserInternal(user User) (User, error) {
  192. if user.Password == "" {
  193. return user, authErr(http.StatusBadRequest, "Cannot create user %s with an empty password", user.User)
  194. }
  195. hash, err := s.HashPassword(user.Password)
  196. if err != nil {
  197. return user, err
  198. }
  199. user.Password = hash
  200. _, err = s.createResource("/users/"+user.User, user)
  201. if err != nil {
  202. if e, ok := err.(*v2error.Error); ok {
  203. if e.ErrorCode == v2error.EcodeNodeExist {
  204. return user, authErr(http.StatusConflict, "User %s already exists.", user.User)
  205. }
  206. }
  207. }
  208. return user, err
  209. }
  210. func (s *store) DeleteUser(name string) error {
  211. if s.AuthEnabled() && name == "root" {
  212. return authErr(http.StatusForbidden, "Cannot delete root user while auth is enabled.")
  213. }
  214. err := s.deleteResource("/users/" + name)
  215. if err != nil {
  216. if e, ok := err.(*v2error.Error); ok {
  217. if e.ErrorCode == v2error.EcodeKeyNotFound {
  218. return authErr(http.StatusNotFound, "User %s does not exist", name)
  219. }
  220. }
  221. return err
  222. }
  223. if s.lg != nil {
  224. s.lg.Info("deleted a user", zap.String("user-name", name))
  225. } else {
  226. plog.Noticef("deleted user %s", name)
  227. }
  228. return nil
  229. }
  230. func (s *store) UpdateUser(user User) (User, error) {
  231. old, err := s.getUser(user.User, true)
  232. if err != nil {
  233. if e, ok := err.(*v2error.Error); ok {
  234. if e.ErrorCode == v2error.EcodeKeyNotFound {
  235. return user, authErr(http.StatusNotFound, "User %s doesn't exist.", user.User)
  236. }
  237. }
  238. return old, err
  239. }
  240. newUser, err := old.merge(s.lg, user, s.PasswordStore)
  241. if err != nil {
  242. return old, err
  243. }
  244. if reflect.DeepEqual(old, newUser) {
  245. return old, authErr(http.StatusBadRequest, "User not updated. Use grant/revoke/password to update the user.")
  246. }
  247. _, err = s.updateResource("/users/"+user.User, newUser)
  248. if err == nil {
  249. if s.lg != nil {
  250. s.lg.Info("updated a user", zap.String("user-name", user.User))
  251. } else {
  252. plog.Noticef("updated user %s", user.User)
  253. }
  254. }
  255. return newUser, err
  256. }
  257. func (s *store) AllRoles() ([]string, error) {
  258. nodes := []string{RootRoleName}
  259. resp, err := s.requestResource("/roles/", false)
  260. if err != nil {
  261. if e, ok := err.(*v2error.Error); ok {
  262. if e.ErrorCode == v2error.EcodeKeyNotFound {
  263. return nodes, nil
  264. }
  265. }
  266. return nil, err
  267. }
  268. for _, n := range resp.Event.Node.Nodes {
  269. _, role := path.Split(n.Key)
  270. nodes = append(nodes, role)
  271. }
  272. sort.Strings(nodes)
  273. return nodes, nil
  274. }
  275. func (s *store) GetRole(name string) (Role, error) { return s.getRole(name, false) }
  276. func (s *store) CreateRole(role Role) error {
  277. if role.Role == RootRoleName {
  278. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  279. }
  280. _, err := s.createResource("/roles/"+role.Role, role)
  281. if err != nil {
  282. if e, ok := err.(*v2error.Error); ok {
  283. if e.ErrorCode == v2error.EcodeNodeExist {
  284. return authErr(http.StatusConflict, "Role %s already exists.", role.Role)
  285. }
  286. }
  287. }
  288. if err == nil {
  289. if s.lg != nil {
  290. s.lg.Info("created a new role", zap.String("role-name", role.Role))
  291. } else {
  292. plog.Noticef("created new role %s", role.Role)
  293. }
  294. }
  295. return err
  296. }
  297. func (s *store) DeleteRole(name string) error {
  298. if name == RootRoleName {
  299. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", name)
  300. }
  301. err := s.deleteResource("/roles/" + name)
  302. if err != nil {
  303. if e, ok := err.(*v2error.Error); ok {
  304. if e.ErrorCode == v2error.EcodeKeyNotFound {
  305. return authErr(http.StatusNotFound, "Role %s doesn't exist.", name)
  306. }
  307. }
  308. }
  309. if err == nil {
  310. if s.lg != nil {
  311. s.lg.Info("delete a new role", zap.String("role-name", name))
  312. } else {
  313. plog.Noticef("deleted role %s", name)
  314. }
  315. }
  316. return err
  317. }
  318. func (s *store) UpdateRole(role Role) (Role, error) {
  319. if role.Role == RootRoleName {
  320. return Role{}, authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  321. }
  322. old, err := s.getRole(role.Role, true)
  323. if err != nil {
  324. if e, ok := err.(*v2error.Error); ok {
  325. if e.ErrorCode == v2error.EcodeKeyNotFound {
  326. return role, authErr(http.StatusNotFound, "Role %s doesn't exist.", role.Role)
  327. }
  328. }
  329. return old, err
  330. }
  331. newRole, err := old.merge(s.lg, role)
  332. if err != nil {
  333. return old, err
  334. }
  335. if reflect.DeepEqual(old, newRole) {
  336. return old, authErr(http.StatusBadRequest, "Role not updated. Use grant/revoke to update the role.")
  337. }
  338. _, err = s.updateResource("/roles/"+role.Role, newRole)
  339. if err == nil {
  340. if s.lg != nil {
  341. s.lg.Info("updated a new role", zap.String("role-name", role.Role))
  342. } else {
  343. plog.Noticef("updated role %s", role.Role)
  344. }
  345. }
  346. return newRole, err
  347. }
  348. func (s *store) AuthEnabled() bool {
  349. return s.detectAuth()
  350. }
  351. func (s *store) EnableAuth() error {
  352. if s.AuthEnabled() {
  353. return authErr(http.StatusConflict, "already enabled")
  354. }
  355. if _, err := s.getUser("root", true); err != nil {
  356. return authErr(http.StatusConflict, "No root user available, please create one")
  357. }
  358. if _, err := s.getRole(GuestRoleName, true); err != nil {
  359. if s.lg != nil {
  360. s.lg.Info(
  361. "no guest role access found; creating default",
  362. zap.String("role-name", GuestRoleName),
  363. )
  364. } else {
  365. plog.Printf("no guest role access found, creating default")
  366. }
  367. if err := s.CreateRole(guestRole); err != nil {
  368. if s.lg != nil {
  369. s.lg.Warn(
  370. "failed to create a guest role; aborting auth enable",
  371. zap.String("role-name", GuestRoleName),
  372. zap.Error(err),
  373. )
  374. } else {
  375. plog.Errorf("error creating guest role. aborting auth enable.")
  376. }
  377. return err
  378. }
  379. }
  380. if err := s.enableAuth(); err != nil {
  381. if s.lg != nil {
  382. s.lg.Warn("failed to enable auth", zap.Error(err))
  383. } else {
  384. plog.Errorf("error enabling auth (%v)", err)
  385. }
  386. return err
  387. }
  388. if s.lg != nil {
  389. s.lg.Info("enabled auth")
  390. } else {
  391. plog.Noticef("auth: enabled auth")
  392. }
  393. return nil
  394. }
  395. func (s *store) DisableAuth() error {
  396. if !s.AuthEnabled() {
  397. return authErr(http.StatusConflict, "already disabled")
  398. }
  399. err := s.disableAuth()
  400. if err == nil {
  401. if s.lg != nil {
  402. s.lg.Info("disabled auth")
  403. } else {
  404. plog.Noticef("auth: disabled auth")
  405. }
  406. } else {
  407. if s.lg != nil {
  408. s.lg.Warn("failed to disable auth", zap.Error(err))
  409. } else {
  410. plog.Errorf("error disabling auth (%v)", err)
  411. }
  412. }
  413. return err
  414. }
  415. // merge applies the properties of the passed-in User to the User on which it
  416. // is called and returns a new User with these modifications applied. Think of
  417. // all Users as immutable sets of data. Merge allows you to perform the set
  418. // operations (desired grants and revokes) atomically
  419. func (ou User) merge(lg *zap.Logger, nu User, s PasswordStore) (User, error) {
  420. var out User
  421. if ou.User != nu.User {
  422. return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", ou.User, nu.User)
  423. }
  424. out.User = ou.User
  425. if nu.Password != "" {
  426. hash, err := s.HashPassword(nu.Password)
  427. if err != nil {
  428. return ou, err
  429. }
  430. out.Password = hash
  431. } else {
  432. out.Password = ou.Password
  433. }
  434. currentRoles := types.NewUnsafeSet(ou.Roles...)
  435. for _, g := range nu.Grant {
  436. if currentRoles.Contains(g) {
  437. if lg != nil {
  438. lg.Warn(
  439. "attempted to grant a duplicate role for a user",
  440. zap.String("user-name", nu.User),
  441. zap.String("role-name", g),
  442. )
  443. } else {
  444. plog.Noticef("granting duplicate role %s for user %s", g, nu.User)
  445. }
  446. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, nu.User))
  447. }
  448. currentRoles.Add(g)
  449. }
  450. for _, r := range nu.Revoke {
  451. if !currentRoles.Contains(r) {
  452. if lg != nil {
  453. lg.Warn(
  454. "attempted to revoke a ungranted role for a user",
  455. zap.String("user-name", nu.User),
  456. zap.String("role-name", r),
  457. )
  458. } else {
  459. plog.Noticef("revoking ungranted role %s for user %s", r, nu.User)
  460. }
  461. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, nu.User))
  462. }
  463. currentRoles.Remove(r)
  464. }
  465. out.Roles = currentRoles.Values()
  466. sort.Strings(out.Roles)
  467. return out, nil
  468. }
  469. // merge for a role works the same as User above -- atomic Role application to
  470. // each of the substructures.
  471. func (r Role) merge(lg *zap.Logger, n Role) (Role, error) {
  472. var out Role
  473. var err error
  474. if r.Role != n.Role {
  475. return out, authErr(http.StatusConflict, "Merging role with conflicting names: %s %s", r.Role, n.Role)
  476. }
  477. out.Role = r.Role
  478. out.Permissions, err = r.Permissions.Grant(n.Grant)
  479. if err != nil {
  480. return out, err
  481. }
  482. out.Permissions, err = out.Permissions.Revoke(lg, n.Revoke)
  483. return out, err
  484. }
  485. func (r Role) HasKeyAccess(key string, write bool) bool {
  486. if r.Role == RootRoleName {
  487. return true
  488. }
  489. return r.Permissions.KV.HasAccess(key, write)
  490. }
  491. func (r Role) HasRecursiveAccess(key string, write bool) bool {
  492. if r.Role == RootRoleName {
  493. return true
  494. }
  495. return r.Permissions.KV.HasRecursiveAccess(key, write)
  496. }
  497. // Grant adds a set of permissions to the permission object on which it is called,
  498. // returning a new permission object.
  499. func (p Permissions) Grant(n *Permissions) (Permissions, error) {
  500. var out Permissions
  501. var err error
  502. if n == nil {
  503. return p, nil
  504. }
  505. out.KV, err = p.KV.Grant(n.KV)
  506. return out, err
  507. }
  508. // Revoke removes a set of permissions to the permission object on which it is called,
  509. // returning a new permission object.
  510. func (p Permissions) Revoke(lg *zap.Logger, n *Permissions) (Permissions, error) {
  511. var out Permissions
  512. var err error
  513. if n == nil {
  514. return p, nil
  515. }
  516. out.KV, err = p.KV.Revoke(lg, n.KV)
  517. return out, err
  518. }
  519. // Grant adds a set of permissions to the permission object on which it is called,
  520. // returning a new permission object.
  521. func (rw RWPermission) Grant(n RWPermission) (RWPermission, error) {
  522. var out RWPermission
  523. currentRead := types.NewUnsafeSet(rw.Read...)
  524. for _, r := range n.Read {
  525. if currentRead.Contains(r) {
  526. return out, authErr(http.StatusConflict, "Granting duplicate read permission %s", r)
  527. }
  528. currentRead.Add(r)
  529. }
  530. currentWrite := types.NewUnsafeSet(rw.Write...)
  531. for _, w := range n.Write {
  532. if currentWrite.Contains(w) {
  533. return out, authErr(http.StatusConflict, "Granting duplicate write permission %s", w)
  534. }
  535. currentWrite.Add(w)
  536. }
  537. out.Read = currentRead.Values()
  538. out.Write = currentWrite.Values()
  539. sort.Strings(out.Read)
  540. sort.Strings(out.Write)
  541. return out, nil
  542. }
  543. // Revoke removes a set of permissions to the permission object on which it is called,
  544. // returning a new permission object.
  545. func (rw RWPermission) Revoke(lg *zap.Logger, n RWPermission) (RWPermission, error) {
  546. var out RWPermission
  547. currentRead := types.NewUnsafeSet(rw.Read...)
  548. for _, r := range n.Read {
  549. if !currentRead.Contains(r) {
  550. if lg != nil {
  551. lg.Info(
  552. "revoking ungranted read permission",
  553. zap.String("read-permission", r),
  554. )
  555. } else {
  556. plog.Noticef("revoking ungranted read permission %s", r)
  557. }
  558. continue
  559. }
  560. currentRead.Remove(r)
  561. }
  562. currentWrite := types.NewUnsafeSet(rw.Write...)
  563. for _, w := range n.Write {
  564. if !currentWrite.Contains(w) {
  565. if lg != nil {
  566. lg.Info(
  567. "revoking ungranted write permission",
  568. zap.String("write-permission", w),
  569. )
  570. } else {
  571. plog.Noticef("revoking ungranted write permission %s", w)
  572. }
  573. continue
  574. }
  575. currentWrite.Remove(w)
  576. }
  577. out.Read = currentRead.Values()
  578. out.Write = currentWrite.Values()
  579. sort.Strings(out.Read)
  580. sort.Strings(out.Write)
  581. return out, nil
  582. }
  583. func (rw RWPermission) HasAccess(key string, write bool) bool {
  584. var list []string
  585. if write {
  586. list = rw.Write
  587. } else {
  588. list = rw.Read
  589. }
  590. for _, pat := range list {
  591. match, err := simpleMatch(pat, key)
  592. if err == nil && match {
  593. return true
  594. }
  595. }
  596. return false
  597. }
  598. func (rw RWPermission) HasRecursiveAccess(key string, write bool) bool {
  599. list := rw.Read
  600. if write {
  601. list = rw.Write
  602. }
  603. for _, pat := range list {
  604. match, err := prefixMatch(pat, key)
  605. if err == nil && match {
  606. return true
  607. }
  608. }
  609. return false
  610. }
  611. func simpleMatch(pattern string, key string) (match bool, err error) {
  612. if pattern[len(pattern)-1] == '*' {
  613. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  614. }
  615. return key == pattern, nil
  616. }
  617. func prefixMatch(pattern string, key string) (match bool, err error) {
  618. if pattern[len(pattern)-1] != '*' {
  619. return false, nil
  620. }
  621. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  622. }
  623. func attachRootRole(u User) User {
  624. inRoles := false
  625. for _, r := range u.Roles {
  626. if r == RootRoleName {
  627. inRoles = true
  628. break
  629. }
  630. }
  631. if !inRoles {
  632. u.Roles = append(u.Roles, RootRoleName)
  633. }
  634. return u
  635. }
  636. func (s *store) getUser(name string, quorum bool) (User, error) {
  637. resp, err := s.requestResource("/users/"+name, quorum)
  638. if err != nil {
  639. if e, ok := err.(*v2error.Error); ok {
  640. if e.ErrorCode == v2error.EcodeKeyNotFound {
  641. return User{}, authErr(http.StatusNotFound, "User %s does not exist.", name)
  642. }
  643. }
  644. return User{}, err
  645. }
  646. var u User
  647. err = json.Unmarshal([]byte(*resp.Event.Node.Value), &u)
  648. if err != nil {
  649. return u, err
  650. }
  651. // Attach root role to root user.
  652. if u.User == "root" {
  653. u = attachRootRole(u)
  654. }
  655. return u, nil
  656. }
  657. func (s *store) getRole(name string, quorum bool) (Role, error) {
  658. if name == RootRoleName {
  659. return rootRole, nil
  660. }
  661. resp, err := s.requestResource("/roles/"+name, quorum)
  662. if err != nil {
  663. if e, ok := err.(*v2error.Error); ok {
  664. if e.ErrorCode == v2error.EcodeKeyNotFound {
  665. return Role{}, authErr(http.StatusNotFound, "Role %s does not exist.", name)
  666. }
  667. }
  668. return Role{}, err
  669. }
  670. var r Role
  671. err = json.Unmarshal([]byte(*resp.Event.Node.Value), &r)
  672. return r, err
  673. }