store.go 21 KB

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