store.go 22 KB

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