store.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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. for _, role := range user.Roles {
  355. resp.Roles = append(resp.Roles, role)
  356. }
  357. return &resp, nil
  358. }
  359. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  360. tx := as.be.BatchTx()
  361. tx.Lock()
  362. defer tx.Unlock()
  363. var resp pb.AuthUserListResponse
  364. users := getAllUsers(tx)
  365. for _, u := range users {
  366. resp.Users = append(resp.Users, string(u.Name))
  367. }
  368. return &resp, nil
  369. }
  370. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  371. tx := as.be.BatchTx()
  372. tx.Lock()
  373. defer tx.Unlock()
  374. user := getUser(tx, r.Name)
  375. if user == nil {
  376. return nil, ErrUserNotFound
  377. }
  378. updatedUser := &authpb.User{
  379. Name: user.Name,
  380. Password: user.Password,
  381. }
  382. for _, role := range user.Roles {
  383. if strings.Compare(role, r.Role) != 0 {
  384. updatedUser.Roles = append(updatedUser.Roles, role)
  385. }
  386. }
  387. if len(updatedUser.Roles) == len(user.Roles) {
  388. return nil, ErrRoleNotGranted
  389. }
  390. putUser(tx, updatedUser)
  391. as.invalidateCachedPerm(r.Name)
  392. as.commitRevision(tx)
  393. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  394. return &pb.AuthUserRevokeRoleResponse{}, nil
  395. }
  396. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  397. tx := as.be.BatchTx()
  398. tx.Lock()
  399. defer tx.Unlock()
  400. var resp pb.AuthRoleGetResponse
  401. role := getRole(tx, r.Role)
  402. if role == nil {
  403. return nil, ErrRoleNotFound
  404. }
  405. for _, perm := range role.KeyPermission {
  406. resp.Perm = append(resp.Perm, perm)
  407. }
  408. return &resp, nil
  409. }
  410. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  411. tx := as.be.BatchTx()
  412. tx.Lock()
  413. defer tx.Unlock()
  414. var resp pb.AuthRoleListResponse
  415. roles := getAllRoles(tx)
  416. for _, r := range roles {
  417. resp.Roles = append(resp.Roles, string(r.Name))
  418. }
  419. return &resp, nil
  420. }
  421. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  422. tx := as.be.BatchTx()
  423. tx.Lock()
  424. defer tx.Unlock()
  425. role := getRole(tx, r.Role)
  426. if role == nil {
  427. return nil, ErrRoleNotFound
  428. }
  429. updatedRole := &authpb.Role{
  430. Name: role.Name,
  431. }
  432. for _, perm := range role.KeyPermission {
  433. if !bytes.Equal(perm.Key, []byte(r.Key)) || !bytes.Equal(perm.RangeEnd, []byte(r.RangeEnd)) {
  434. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  435. }
  436. }
  437. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  438. return nil, ErrPermissionNotGranted
  439. }
  440. putRole(tx, updatedRole)
  441. // TODO(mitake): currently single role update invalidates every cache
  442. // It should be optimized.
  443. as.clearCachedPerm()
  444. as.commitRevision(tx)
  445. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  446. return &pb.AuthRoleRevokePermissionResponse{}, nil
  447. }
  448. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  449. // TODO(mitake): current scheme of role deletion allows existing users to have the deleted roles
  450. //
  451. // Assume a case like below:
  452. // create a role r1
  453. // create a user u1 and grant r1 to u1
  454. // delete r1
  455. //
  456. // After this sequence, u1 is still granted the role r1. So if admin create a new role with the name r1,
  457. // the new r1 is automatically granted u1.
  458. // In some cases, it would be confusing. So we need to provide an option for deleting the grant relation
  459. // from all users.
  460. tx := as.be.BatchTx()
  461. tx.Lock()
  462. defer tx.Unlock()
  463. role := getRole(tx, r.Role)
  464. if role == nil {
  465. return nil, ErrRoleNotFound
  466. }
  467. delRole(tx, r.Role)
  468. as.commitRevision(tx)
  469. plog.Noticef("deleted role %s", r.Role)
  470. return &pb.AuthRoleDeleteResponse{}, nil
  471. }
  472. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  473. tx := as.be.BatchTx()
  474. tx.Lock()
  475. defer tx.Unlock()
  476. role := getRole(tx, r.Name)
  477. if role != nil {
  478. return nil, ErrRoleAlreadyExist
  479. }
  480. newRole := &authpb.Role{
  481. Name: []byte(r.Name),
  482. }
  483. putRole(tx, newRole)
  484. as.commitRevision(tx)
  485. plog.Noticef("Role %s is created", r.Name)
  486. return &pb.AuthRoleAddResponse{}, nil
  487. }
  488. func (as *authStore) AuthInfoFromToken(token string) (*AuthInfo, bool) {
  489. as.simpleTokensMu.RLock()
  490. defer as.simpleTokensMu.RUnlock()
  491. t, ok := as.simpleTokens[token]
  492. if ok {
  493. as.simpleTokenKeeper.resetSimpleToken(token)
  494. }
  495. return &AuthInfo{Username: t, Revision: as.revision}, ok
  496. }
  497. type permSlice []*authpb.Permission
  498. func (perms permSlice) Len() int {
  499. return len(perms)
  500. }
  501. func (perms permSlice) Less(i, j int) bool {
  502. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  503. }
  504. func (perms permSlice) Swap(i, j int) {
  505. perms[i], perms[j] = perms[j], perms[i]
  506. }
  507. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  508. tx := as.be.BatchTx()
  509. tx.Lock()
  510. defer tx.Unlock()
  511. role := getRole(tx, r.Name)
  512. if role == nil {
  513. return nil, ErrRoleNotFound
  514. }
  515. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  516. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  517. })
  518. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  519. // update existing permission
  520. role.KeyPermission[idx].PermType = r.Perm.PermType
  521. } else {
  522. // append new permission to the role
  523. newPerm := &authpb.Permission{
  524. Key: []byte(r.Perm.Key),
  525. RangeEnd: []byte(r.Perm.RangeEnd),
  526. PermType: r.Perm.PermType,
  527. }
  528. role.KeyPermission = append(role.KeyPermission, newPerm)
  529. sort.Sort(permSlice(role.KeyPermission))
  530. }
  531. putRole(tx, role)
  532. // TODO(mitake): currently single role update invalidates every cache
  533. // It should be optimized.
  534. as.clearCachedPerm()
  535. as.commitRevision(tx)
  536. 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)])
  537. return &pb.AuthRoleGrantPermissionResponse{}, nil
  538. }
  539. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  540. // TODO(mitake): this function would be costly so we need a caching mechanism
  541. if !as.isAuthEnabled() {
  542. return nil
  543. }
  544. if revision < as.revision {
  545. return ErrAuthOldRevision
  546. }
  547. tx := as.be.BatchTx()
  548. tx.Lock()
  549. defer tx.Unlock()
  550. user := getUser(tx, userName)
  551. if user == nil {
  552. plog.Errorf("invalid user name %s for permission checking", userName)
  553. return ErrPermissionDenied
  554. }
  555. // root role should have permission on all ranges
  556. if hasRootRole(user) {
  557. return nil
  558. }
  559. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  560. return nil
  561. }
  562. return ErrPermissionDenied
  563. }
  564. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  565. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  566. }
  567. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  568. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  569. }
  570. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  571. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  572. }
  573. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  574. if !as.isAuthEnabled() {
  575. return nil
  576. }
  577. tx := as.be.BatchTx()
  578. tx.Lock()
  579. defer tx.Unlock()
  580. u := getUser(tx, authInfo.Username)
  581. if u == nil {
  582. return ErrUserNotFound
  583. }
  584. if !hasRootRole(u) {
  585. return ErrPermissionDenied
  586. }
  587. return nil
  588. }
  589. func getUser(tx backend.BatchTx, username string) *authpb.User {
  590. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  591. if len(vs) == 0 {
  592. return nil
  593. }
  594. user := &authpb.User{}
  595. err := user.Unmarshal(vs[0])
  596. if err != nil {
  597. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  598. }
  599. return user
  600. }
  601. func getAllUsers(tx backend.BatchTx) []*authpb.User {
  602. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  603. if len(vs) == 0 {
  604. return nil
  605. }
  606. var users []*authpb.User
  607. for _, v := range vs {
  608. user := &authpb.User{}
  609. err := user.Unmarshal(v)
  610. if err != nil {
  611. plog.Panicf("failed to unmarshal user struct: %s", err)
  612. }
  613. users = append(users, user)
  614. }
  615. return users
  616. }
  617. func putUser(tx backend.BatchTx, user *authpb.User) {
  618. b, err := user.Marshal()
  619. if err != nil {
  620. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  621. }
  622. tx.UnsafePut(authUsersBucketName, user.Name, b)
  623. }
  624. func delUser(tx backend.BatchTx, username string) {
  625. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  626. }
  627. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  628. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  629. if len(vs) == 0 {
  630. return nil
  631. }
  632. role := &authpb.Role{}
  633. err := role.Unmarshal(vs[0])
  634. if err != nil {
  635. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  636. }
  637. return role
  638. }
  639. func getAllRoles(tx backend.BatchTx) []*authpb.Role {
  640. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  641. if len(vs) == 0 {
  642. return nil
  643. }
  644. var roles []*authpb.Role
  645. for _, v := range vs {
  646. role := &authpb.Role{}
  647. err := role.Unmarshal(v)
  648. if err != nil {
  649. plog.Panicf("failed to unmarshal role struct: %s", err)
  650. }
  651. roles = append(roles, role)
  652. }
  653. return roles
  654. }
  655. func putRole(tx backend.BatchTx, role *authpb.Role) {
  656. b, err := role.Marshal()
  657. if err != nil {
  658. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  659. }
  660. tx.UnsafePut(authRolesBucketName, []byte(role.Name), b)
  661. }
  662. func delRole(tx backend.BatchTx, rolename string) {
  663. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  664. }
  665. func (as *authStore) isAuthEnabled() bool {
  666. as.enabledMu.RLock()
  667. defer as.enabledMu.RUnlock()
  668. return as.enabled
  669. }
  670. func NewAuthStore(be backend.Backend) *authStore {
  671. tx := be.BatchTx()
  672. tx.Lock()
  673. tx.UnsafeCreateBucket(authBucketName)
  674. tx.UnsafeCreateBucket(authUsersBucketName)
  675. tx.UnsafeCreateBucket(authRolesBucketName)
  676. as := &authStore{
  677. be: be,
  678. simpleTokens: make(map[string]string),
  679. revision: 0,
  680. }
  681. as.commitRevision(tx)
  682. tx.Unlock()
  683. be.ForceCommit()
  684. return as
  685. }
  686. func hasRootRole(u *authpb.User) bool {
  687. for _, r := range u.Roles {
  688. if r == rootRole {
  689. return true
  690. }
  691. }
  692. return false
  693. }
  694. func (as *authStore) commitRevision(tx backend.BatchTx) {
  695. as.revision++
  696. revBytes := make([]byte, revBytesLen)
  697. binary.BigEndian.PutUint64(revBytes, as.revision)
  698. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  699. }
  700. func getRevision(tx backend.BatchTx) uint64 {
  701. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  702. if len(vs) != 1 {
  703. plog.Panicf("failed to get the key of auth store revision")
  704. }
  705. return binary.BigEndian.Uint64(vs[0])
  706. }
  707. func (as *authStore) Revision() uint64 {
  708. return as.revision
  709. }