store.go 24 KB

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