store.go 22 KB

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