store.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. // Copyright 2016 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 auth
  15. import (
  16. "bytes"
  17. "errors"
  18. "fmt"
  19. "sort"
  20. "strings"
  21. "sync"
  22. "github.com/coreos/etcd/auth/authpb"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. "github.com/coreos/etcd/mvcc/backend"
  25. "github.com/coreos/pkg/capnslog"
  26. "golang.org/x/crypto/bcrypt"
  27. "golang.org/x/net/context"
  28. )
  29. var (
  30. enableFlagKey = []byte("authEnabled")
  31. authEnabled = []byte{1}
  32. authDisabled = []byte{0}
  33. authBucketName = []byte("auth")
  34. authUsersBucketName = []byte("authUsers")
  35. authRolesBucketName = []byte("authRoles")
  36. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  37. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  38. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  39. ErrUserAlreadyExist = errors.New("auth: user already exists")
  40. ErrUserNotFound = errors.New("auth: user not found")
  41. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  42. ErrRoleNotFound = errors.New("auth: role not found")
  43. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  44. ErrPermissionDenied = errors.New("auth: permission denied")
  45. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  46. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  47. )
  48. const (
  49. rootUser = "root"
  50. rootRole = "root"
  51. )
  52. type AuthStore interface {
  53. // AuthEnable turns on the authentication feature
  54. AuthEnable() error
  55. // AuthDisable turns off the authentication feature
  56. AuthDisable()
  57. // Authenticate does authentication based on given user name and password
  58. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  59. // Recover recovers the state of auth store from the given backend
  60. Recover(b backend.Backend)
  61. // UserAdd adds a new user
  62. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  63. // UserDelete deletes a user
  64. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  65. // UserChangePassword changes a password of a user
  66. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  67. // UserGrantRole grants a role to the user
  68. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  69. // UserGet gets the detailed information of a users
  70. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  71. // UserRevokeRole revokes a role of a user
  72. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  73. // RoleAdd adds a new role
  74. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  75. // RoleGrantPermission grants a permission to a role
  76. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  77. // RoleGet gets the detailed information of a role
  78. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  79. // RoleRevokePermission gets the detailed information of a role
  80. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  81. // RoleDelete gets the detailed information of a role
  82. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  83. // UserList gets a list of all users
  84. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  85. // RoleList gets a list of all roles
  86. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  87. // UsernameFromToken gets a username from the given Token
  88. UsernameFromToken(token string) (string, bool)
  89. // IsPutPermitted checks put permission of the user
  90. IsPutPermitted(username string, key []byte) bool
  91. // IsRangePermitted checks range permission of the user
  92. IsRangePermitted(username string, key, rangeEnd []byte) bool
  93. // IsDeleteRangePermitted checks delete-range permission of the user
  94. IsDeleteRangePermitted(username string, key, rangeEnd []byte) bool
  95. // IsAdminPermitted checks admin permission of the user
  96. IsAdminPermitted(username string) bool
  97. // GenSimpleToken produces a simple random string
  98. GenSimpleToken() (string, error)
  99. }
  100. type authStore struct {
  101. be backend.Backend
  102. enabled bool
  103. enabledMu sync.RWMutex
  104. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  105. simpleTokensMu sync.RWMutex
  106. simpleTokens map[string]string // token -> username
  107. }
  108. func (as *authStore) AuthEnable() error {
  109. b := as.be
  110. tx := b.BatchTx()
  111. tx.Lock()
  112. defer func() {
  113. tx.Unlock()
  114. b.ForceCommit()
  115. }()
  116. u := getUser(tx, rootUser)
  117. if u == nil {
  118. return ErrRootUserNotExist
  119. }
  120. if !hasRootRole(u) {
  121. return ErrRootRoleNotExist
  122. }
  123. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  124. as.enabledMu.Lock()
  125. as.enabled = true
  126. as.enabledMu.Unlock()
  127. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  128. plog.Noticef("Authentication enabled")
  129. return nil
  130. }
  131. func (as *authStore) AuthDisable() {
  132. b := as.be
  133. tx := b.BatchTx()
  134. tx.Lock()
  135. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  136. tx.Unlock()
  137. b.ForceCommit()
  138. as.enabledMu.Lock()
  139. as.enabled = false
  140. as.enabledMu.Unlock()
  141. plog.Noticef("Authentication disabled")
  142. }
  143. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  144. // TODO(mitake): after adding jwt support, branching based on values of ctx is required
  145. index := ctx.Value("index").(uint64)
  146. simpleToken := ctx.Value("simpleToken").(string)
  147. tx := as.be.BatchTx()
  148. tx.Lock()
  149. defer tx.Unlock()
  150. user := getUser(tx, username)
  151. if user == nil {
  152. return nil, ErrAuthFailed
  153. }
  154. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  155. plog.Noticef("authentication failed, invalid password for user %s", username)
  156. return &pb.AuthenticateResponse{}, ErrAuthFailed
  157. }
  158. token := fmt.Sprintf("%s.%d", simpleToken, index)
  159. as.assignSimpleTokenToUser(username, token)
  160. plog.Infof("authorized %s, token is %s", username, token)
  161. return &pb.AuthenticateResponse{Token: token}, nil
  162. }
  163. func (as *authStore) Recover(be backend.Backend) {
  164. enabled := false
  165. as.be = be
  166. tx := be.BatchTx()
  167. tx.Lock()
  168. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  169. if len(vs) == 1 {
  170. if bytes.Equal(vs[0], authEnabled) {
  171. enabled = true
  172. }
  173. }
  174. tx.Unlock()
  175. as.enabledMu.Lock()
  176. as.enabled = enabled
  177. as.enabledMu.Unlock()
  178. }
  179. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  180. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  181. if err != nil {
  182. plog.Errorf("failed to hash password: %s", err)
  183. return nil, err
  184. }
  185. tx := as.be.BatchTx()
  186. tx.Lock()
  187. defer tx.Unlock()
  188. user := getUser(tx, r.Name)
  189. if user != nil {
  190. return nil, ErrUserAlreadyExist
  191. }
  192. newUser := &authpb.User{
  193. Name: []byte(r.Name),
  194. Password: hashed,
  195. }
  196. putUser(tx, newUser)
  197. plog.Noticef("added a new user: %s", r.Name)
  198. return &pb.AuthUserAddResponse{}, nil
  199. }
  200. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  201. tx := as.be.BatchTx()
  202. tx.Lock()
  203. defer tx.Unlock()
  204. user := getUser(tx, r.Name)
  205. if user == nil {
  206. return nil, ErrUserNotFound
  207. }
  208. delUser(tx, r.Name)
  209. plog.Noticef("deleted a user: %s", r.Name)
  210. return &pb.AuthUserDeleteResponse{}, nil
  211. }
  212. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  213. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  214. // If the cost is too high, we should move the encryption to outside of the raft
  215. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), bcrypt.DefaultCost)
  216. if err != nil {
  217. plog.Errorf("failed to hash password: %s", err)
  218. return nil, err
  219. }
  220. tx := as.be.BatchTx()
  221. tx.Lock()
  222. defer tx.Unlock()
  223. user := getUser(tx, r.Name)
  224. if user == nil {
  225. return nil, ErrUserNotFound
  226. }
  227. updatedUser := &authpb.User{
  228. Name: []byte(r.Name),
  229. Roles: user.Roles,
  230. Password: hashed,
  231. }
  232. putUser(tx, updatedUser)
  233. plog.Noticef("changed a password of a user: %s", r.Name)
  234. return &pb.AuthUserChangePasswordResponse{}, nil
  235. }
  236. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  237. tx := as.be.BatchTx()
  238. tx.Lock()
  239. defer tx.Unlock()
  240. user := getUser(tx, r.User)
  241. if user == nil {
  242. return nil, ErrUserNotFound
  243. }
  244. if r.Role != rootRole {
  245. role := getRole(tx, r.Role)
  246. if role == nil {
  247. return nil, ErrRoleNotFound
  248. }
  249. }
  250. idx := sort.SearchStrings(user.Roles, r.Role)
  251. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  252. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  253. return &pb.AuthUserGrantRoleResponse{}, nil
  254. }
  255. user.Roles = append(user.Roles, r.Role)
  256. sort.Sort(sort.StringSlice(user.Roles))
  257. putUser(tx, user)
  258. as.invalidateCachedPerm(r.User)
  259. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  260. return &pb.AuthUserGrantRoleResponse{}, nil
  261. }
  262. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  263. tx := as.be.BatchTx()
  264. tx.Lock()
  265. defer tx.Unlock()
  266. var resp pb.AuthUserGetResponse
  267. user := getUser(tx, r.Name)
  268. if user == nil {
  269. return nil, ErrUserNotFound
  270. }
  271. for _, role := range user.Roles {
  272. resp.Roles = append(resp.Roles, role)
  273. }
  274. return &resp, nil
  275. }
  276. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  277. tx := as.be.BatchTx()
  278. tx.Lock()
  279. defer tx.Unlock()
  280. var resp pb.AuthUserListResponse
  281. users := getAllUsers(tx)
  282. for _, u := range users {
  283. resp.Users = append(resp.Users, string(u.Name))
  284. }
  285. return &resp, nil
  286. }
  287. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  288. tx := as.be.BatchTx()
  289. tx.Lock()
  290. defer tx.Unlock()
  291. user := getUser(tx, r.Name)
  292. if user == nil {
  293. return nil, ErrUserNotFound
  294. }
  295. updatedUser := &authpb.User{
  296. Name: user.Name,
  297. Password: user.Password,
  298. }
  299. for _, role := range user.Roles {
  300. if strings.Compare(role, r.Role) != 0 {
  301. updatedUser.Roles = append(updatedUser.Roles, role)
  302. }
  303. }
  304. if len(updatedUser.Roles) == len(user.Roles) {
  305. return nil, ErrRoleNotGranted
  306. }
  307. putUser(tx, updatedUser)
  308. as.invalidateCachedPerm(r.Name)
  309. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  310. return &pb.AuthUserRevokeRoleResponse{}, nil
  311. }
  312. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  313. tx := as.be.BatchTx()
  314. tx.Lock()
  315. defer tx.Unlock()
  316. var resp pb.AuthRoleGetResponse
  317. role := getRole(tx, r.Role)
  318. if role == nil {
  319. return nil, ErrRoleNotFound
  320. }
  321. for _, perm := range role.KeyPermission {
  322. resp.Perm = append(resp.Perm, perm)
  323. }
  324. return &resp, nil
  325. }
  326. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  327. tx := as.be.BatchTx()
  328. tx.Lock()
  329. defer tx.Unlock()
  330. var resp pb.AuthRoleListResponse
  331. roles := getAllRoles(tx)
  332. for _, r := range roles {
  333. resp.Roles = append(resp.Roles, string(r.Name))
  334. }
  335. return &resp, nil
  336. }
  337. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  338. tx := as.be.BatchTx()
  339. tx.Lock()
  340. defer tx.Unlock()
  341. role := getRole(tx, r.Role)
  342. if role == nil {
  343. return nil, ErrRoleNotFound
  344. }
  345. updatedRole := &authpb.Role{
  346. Name: role.Name,
  347. }
  348. for _, perm := range role.KeyPermission {
  349. if !bytes.Equal(perm.Key, []byte(r.Key)) || !bytes.Equal(perm.RangeEnd, []byte(r.RangeEnd)) {
  350. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  351. }
  352. }
  353. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  354. return nil, ErrPermissionNotGranted
  355. }
  356. putRole(tx, updatedRole)
  357. // TODO(mitake): currently single role update invalidates every cache
  358. // It should be optimized.
  359. as.clearCachedPerm()
  360. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  361. return &pb.AuthRoleRevokePermissionResponse{}, nil
  362. }
  363. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  364. // TODO(mitake): current scheme of role deletion allows existing users to have the deleted roles
  365. //
  366. // Assume a case like below:
  367. // create a role r1
  368. // create a user u1 and grant r1 to u1
  369. // delete r1
  370. //
  371. // After this sequence, u1 is still granted the role r1. So if admin create a new role with the name r1,
  372. // the new r1 is automatically granted u1.
  373. // In some cases, it would be confusing. So we need to provide an option for deleting the grant relation
  374. // from all users.
  375. tx := as.be.BatchTx()
  376. tx.Lock()
  377. defer tx.Unlock()
  378. role := getRole(tx, r.Role)
  379. if role == nil {
  380. return nil, ErrRoleNotFound
  381. }
  382. delRole(tx, r.Role)
  383. plog.Noticef("deleted role %s", r.Role)
  384. return &pb.AuthRoleDeleteResponse{}, nil
  385. }
  386. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  387. tx := as.be.BatchTx()
  388. tx.Lock()
  389. defer tx.Unlock()
  390. role := getRole(tx, r.Name)
  391. if role != nil {
  392. return nil, ErrRoleAlreadyExist
  393. }
  394. newRole := &authpb.Role{
  395. Name: []byte(r.Name),
  396. }
  397. putRole(tx, newRole)
  398. plog.Noticef("Role %s is created", r.Name)
  399. return &pb.AuthRoleAddResponse{}, nil
  400. }
  401. func (as *authStore) UsernameFromToken(token string) (string, bool) {
  402. as.simpleTokensMu.RLock()
  403. defer as.simpleTokensMu.RUnlock()
  404. t, ok := as.simpleTokens[token]
  405. return t, ok
  406. }
  407. type permSlice []*authpb.Permission
  408. func (perms permSlice) Len() int {
  409. return len(perms)
  410. }
  411. func (perms permSlice) Less(i, j int) bool {
  412. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  413. }
  414. func (perms permSlice) Swap(i, j int) {
  415. perms[i], perms[j] = perms[j], perms[i]
  416. }
  417. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  418. tx := as.be.BatchTx()
  419. tx.Lock()
  420. defer tx.Unlock()
  421. role := getRole(tx, r.Name)
  422. if role == nil {
  423. return nil, ErrRoleNotFound
  424. }
  425. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  426. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  427. })
  428. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  429. // update existing permission
  430. role.KeyPermission[idx].PermType = r.Perm.PermType
  431. } else {
  432. // append new permission to the role
  433. newPerm := &authpb.Permission{
  434. Key: []byte(r.Perm.Key),
  435. RangeEnd: []byte(r.Perm.RangeEnd),
  436. PermType: r.Perm.PermType,
  437. }
  438. role.KeyPermission = append(role.KeyPermission, newPerm)
  439. sort.Sort(permSlice(role.KeyPermission))
  440. }
  441. putRole(tx, role)
  442. // TODO(mitake): currently single role update invalidates every cache
  443. // It should be optimized.
  444. as.clearCachedPerm()
  445. plog.Noticef("role %s's permission of key %s is updated as %s", r.Name, r.Perm.Key, authpb.Permission_Type_name[int32(r.Perm.PermType)])
  446. return &pb.AuthRoleGrantPermissionResponse{}, nil
  447. }
  448. func (as *authStore) isOpPermitted(userName string, key, rangeEnd []byte, permTyp authpb.Permission_Type) bool {
  449. // TODO(mitake): this function would be costly so we need a caching mechanism
  450. if !as.isAuthEnabled() {
  451. return true
  452. }
  453. tx := as.be.BatchTx()
  454. tx.Lock()
  455. defer tx.Unlock()
  456. user := getUser(tx, userName)
  457. if user == nil {
  458. plog.Errorf("invalid user name %s for permission checking", userName)
  459. return false
  460. }
  461. // root role should have permission on all ranges
  462. if hasRootRole(user) {
  463. return true
  464. }
  465. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  466. return true
  467. }
  468. return false
  469. }
  470. func (as *authStore) IsPutPermitted(username string, key []byte) bool {
  471. return as.isOpPermitted(username, key, nil, authpb.WRITE)
  472. }
  473. func (as *authStore) IsRangePermitted(username string, key, rangeEnd []byte) bool {
  474. return as.isOpPermitted(username, key, rangeEnd, authpb.READ)
  475. }
  476. func (as *authStore) IsDeleteRangePermitted(username string, key, rangeEnd []byte) bool {
  477. return as.isOpPermitted(username, key, rangeEnd, authpb.WRITE)
  478. }
  479. func (as *authStore) IsAdminPermitted(username string) bool {
  480. if !as.isAuthEnabled() {
  481. return true
  482. }
  483. tx := as.be.BatchTx()
  484. tx.Lock()
  485. defer tx.Unlock()
  486. u := getUser(tx, username)
  487. if u == nil {
  488. return false
  489. }
  490. return hasRootRole(u)
  491. }
  492. func getUser(tx backend.BatchTx, username string) *authpb.User {
  493. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  494. if len(vs) == 0 {
  495. return nil
  496. }
  497. user := &authpb.User{}
  498. err := user.Unmarshal(vs[0])
  499. if err != nil {
  500. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  501. }
  502. return user
  503. }
  504. func getAllUsers(tx backend.BatchTx) []*authpb.User {
  505. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  506. if len(vs) == 0 {
  507. return nil
  508. }
  509. var users []*authpb.User
  510. for _, v := range vs {
  511. user := &authpb.User{}
  512. err := user.Unmarshal(v)
  513. if err != nil {
  514. plog.Panicf("failed to unmarshal user struct: %s", err)
  515. }
  516. users = append(users, user)
  517. }
  518. return users
  519. }
  520. func putUser(tx backend.BatchTx, user *authpb.User) {
  521. b, err := user.Marshal()
  522. if err != nil {
  523. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  524. }
  525. tx.UnsafePut(authUsersBucketName, user.Name, b)
  526. }
  527. func delUser(tx backend.BatchTx, username string) {
  528. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  529. }
  530. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  531. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  532. if len(vs) == 0 {
  533. return nil
  534. }
  535. role := &authpb.Role{}
  536. err := role.Unmarshal(vs[0])
  537. if err != nil {
  538. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  539. }
  540. return role
  541. }
  542. func getAllRoles(tx backend.BatchTx) []*authpb.Role {
  543. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  544. if len(vs) == 0 {
  545. return nil
  546. }
  547. var roles []*authpb.Role
  548. for _, v := range vs {
  549. role := &authpb.Role{}
  550. err := role.Unmarshal(v)
  551. if err != nil {
  552. plog.Panicf("failed to unmarshal role struct: %s", err)
  553. }
  554. roles = append(roles, role)
  555. }
  556. return roles
  557. }
  558. func putRole(tx backend.BatchTx, role *authpb.Role) {
  559. b, err := role.Marshal()
  560. if err != nil {
  561. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  562. }
  563. tx.UnsafePut(authRolesBucketName, []byte(role.Name), b)
  564. }
  565. func delRole(tx backend.BatchTx, rolename string) {
  566. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  567. }
  568. func (as *authStore) isAuthEnabled() bool {
  569. as.enabledMu.RLock()
  570. defer as.enabledMu.RUnlock()
  571. return as.enabled
  572. }
  573. func NewAuthStore(be backend.Backend) *authStore {
  574. tx := be.BatchTx()
  575. tx.Lock()
  576. tx.UnsafeCreateBucket(authBucketName)
  577. tx.UnsafeCreateBucket(authUsersBucketName)
  578. tx.UnsafeCreateBucket(authRolesBucketName)
  579. tx.Unlock()
  580. be.ForceCommit()
  581. return &authStore{
  582. be: be,
  583. simpleTokens: make(map[string]string),
  584. }
  585. }
  586. func hasRootRole(u *authpb.User) bool {
  587. for _, r := range u.Roles {
  588. if r == rootRole {
  589. return true
  590. }
  591. }
  592. return false
  593. }