store.go 22 KB

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