store.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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. "context"
  18. "encoding/binary"
  19. "errors"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "github.com/coreos/etcd/auth/authpb"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  26. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/mvcc/backend"
  28. "github.com/coreos/pkg/capnslog"
  29. "go.uber.org/zap"
  30. "golang.org/x/crypto/bcrypt"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/metadata"
  33. "google.golang.org/grpc/peer"
  34. )
  35. var (
  36. enableFlagKey = []byte("authEnabled")
  37. authEnabled = []byte{1}
  38. authDisabled = []byte{0}
  39. revisionKey = []byte("authRevision")
  40. authBucketName = []byte("auth")
  41. authUsersBucketName = []byte("authUsers")
  42. authRolesBucketName = []byte("authRoles")
  43. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  44. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  45. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  46. ErrUserAlreadyExist = errors.New("auth: user already exists")
  47. ErrUserEmpty = errors.New("auth: user name is empty")
  48. ErrUserNotFound = errors.New("auth: user not found")
  49. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  50. ErrRoleNotFound = errors.New("auth: role not found")
  51. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  52. ErrPermissionDenied = errors.New("auth: permission denied")
  53. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  54. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  55. ErrAuthNotEnabled = errors.New("auth: authentication is not enabled")
  56. ErrAuthOldRevision = errors.New("auth: revision in header is old")
  57. ErrInvalidAuthToken = errors.New("auth: invalid auth token")
  58. ErrInvalidAuthOpts = errors.New("auth: invalid auth options")
  59. ErrInvalidAuthMgmt = errors.New("auth: invalid auth management")
  60. )
  61. const (
  62. rootUser = "root"
  63. rootRole = "root"
  64. revBytesLen = 8
  65. )
  66. type AuthInfo struct {
  67. Username string
  68. Revision uint64
  69. }
  70. // AuthenticateParamIndex is used for a key of context in the parameters of Authenticate()
  71. type AuthenticateParamIndex struct{}
  72. // AuthenticateParamSimpleTokenPrefix is used for a key of context in the parameters of Authenticate()
  73. type AuthenticateParamSimpleTokenPrefix struct{}
  74. // AuthStore defines auth storage interface.
  75. type AuthStore interface {
  76. // AuthEnable turns on the authentication feature
  77. AuthEnable() error
  78. // AuthDisable turns off the authentication feature
  79. AuthDisable()
  80. // IsAuthEnabled returns true if the authentication feature is enabled.
  81. IsAuthEnabled() bool
  82. // Authenticate does authentication based on given user name and password
  83. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  84. // Recover recovers the state of auth store from the given backend
  85. Recover(b backend.Backend)
  86. // UserAdd adds a new user
  87. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  88. // UserDelete deletes a user
  89. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  90. // UserChangePassword changes a password of a user
  91. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  92. // UserGrantRole grants a role to the user
  93. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  94. // UserGet gets the detailed information of a users
  95. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  96. // UserRevokeRole revokes a role of a user
  97. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  98. // RoleAdd adds a new role
  99. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  100. // RoleGrantPermission grants a permission to a role
  101. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  102. // RoleGet gets the detailed information of a role
  103. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  104. // RoleRevokePermission gets the detailed information of a role
  105. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  106. // RoleDelete gets the detailed information of a role
  107. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  108. // UserList gets a list of all users
  109. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  110. // RoleList gets a list of all roles
  111. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  112. // IsPutPermitted checks put permission of the user
  113. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  114. // IsRangePermitted checks range permission of the user
  115. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  116. // IsDeleteRangePermitted checks delete-range permission of the user
  117. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  118. // IsAdminPermitted checks admin permission of the user
  119. IsAdminPermitted(authInfo *AuthInfo) error
  120. // GenTokenPrefix produces a random string in a case of simple token
  121. // in a case of JWT, it produces an empty string
  122. GenTokenPrefix() (string, error)
  123. // Revision gets current revision of authStore
  124. Revision() uint64
  125. // CheckPassword checks a given pair of username and password is correct
  126. CheckPassword(username, password string) (uint64, error)
  127. // Close does cleanup of AuthStore
  128. Close() error
  129. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  130. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  131. // AuthInfoFromTLS gets AuthInfo from TLS info of gRPC's context
  132. AuthInfoFromTLS(ctx context.Context) *AuthInfo
  133. // WithRoot generates and installs a token that can be used as a root credential
  134. WithRoot(ctx context.Context) context.Context
  135. // HasRole checks that user has role
  136. HasRole(user, role string) bool
  137. }
  138. type TokenProvider interface {
  139. info(ctx context.Context, token string, revision uint64) (*AuthInfo, bool)
  140. assign(ctx context.Context, username string, revision uint64) (string, error)
  141. enable()
  142. disable()
  143. invalidateUser(string)
  144. genTokenPrefix() (string, error)
  145. }
  146. type authStore struct {
  147. // atomic operations; need 64-bit align, or 32-bit tests will crash
  148. revision uint64
  149. lg *zap.Logger
  150. be backend.Backend
  151. enabled bool
  152. enabledMu sync.RWMutex
  153. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  154. tokenProvider TokenProvider
  155. bcryptCost int // the algorithm cost / strength for hashing auth passwords
  156. }
  157. func (as *authStore) AuthEnable() error {
  158. as.enabledMu.Lock()
  159. defer as.enabledMu.Unlock()
  160. if as.enabled {
  161. if as.lg != nil {
  162. as.lg.Info("authentication is already enabled; ignored auth enable request")
  163. } else {
  164. plog.Noticef("Authentication already enabled")
  165. }
  166. return nil
  167. }
  168. b := as.be
  169. tx := b.BatchTx()
  170. tx.Lock()
  171. defer func() {
  172. tx.Unlock()
  173. b.ForceCommit()
  174. }()
  175. u := getUser(as.lg, tx, rootUser)
  176. if u == nil {
  177. return ErrRootUserNotExist
  178. }
  179. if !hasRootRole(u) {
  180. return ErrRootRoleNotExist
  181. }
  182. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  183. as.enabled = true
  184. as.tokenProvider.enable()
  185. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  186. as.setRevision(getRevision(tx))
  187. if as.lg != nil {
  188. as.lg.Info("enabled authentication")
  189. } else {
  190. plog.Noticef("Authentication enabled")
  191. }
  192. return nil
  193. }
  194. func (as *authStore) AuthDisable() {
  195. as.enabledMu.Lock()
  196. defer as.enabledMu.Unlock()
  197. if !as.enabled {
  198. return
  199. }
  200. b := as.be
  201. tx := b.BatchTx()
  202. tx.Lock()
  203. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  204. as.commitRevision(tx)
  205. tx.Unlock()
  206. b.ForceCommit()
  207. as.enabled = false
  208. as.tokenProvider.disable()
  209. if as.lg != nil {
  210. as.lg.Info("disabled authentication")
  211. } else {
  212. plog.Noticef("Authentication disabled")
  213. }
  214. }
  215. func (as *authStore) Close() error {
  216. as.enabledMu.Lock()
  217. defer as.enabledMu.Unlock()
  218. if !as.enabled {
  219. return nil
  220. }
  221. as.tokenProvider.disable()
  222. return nil
  223. }
  224. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  225. if !as.IsAuthEnabled() {
  226. return nil, ErrAuthNotEnabled
  227. }
  228. tx := as.be.BatchTx()
  229. tx.Lock()
  230. defer tx.Unlock()
  231. user := getUser(as.lg, tx, username)
  232. if user == nil {
  233. return nil, ErrAuthFailed
  234. }
  235. // Password checking is already performed in the API layer, so we don't need to check for now.
  236. // Staleness of password can be detected with OCC in the API layer, too.
  237. token, err := as.tokenProvider.assign(ctx, username, as.Revision())
  238. if err != nil {
  239. return nil, err
  240. }
  241. if as.lg != nil {
  242. as.lg.Debug(
  243. "authenticated a user",
  244. zap.String("user-name", username),
  245. zap.String("token", token),
  246. )
  247. } else {
  248. plog.Debugf("authorized %s, token is %s", username, token)
  249. }
  250. return &pb.AuthenticateResponse{Token: token}, nil
  251. }
  252. func (as *authStore) CheckPassword(username, password string) (uint64, error) {
  253. if !as.IsAuthEnabled() {
  254. return 0, ErrAuthNotEnabled
  255. }
  256. tx := as.be.BatchTx()
  257. tx.Lock()
  258. defer tx.Unlock()
  259. user := getUser(as.lg, tx, username)
  260. if user == nil {
  261. return 0, ErrAuthFailed
  262. }
  263. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  264. if as.lg != nil {
  265. as.lg.Info("invalid password", zap.String("user-name", username))
  266. } else {
  267. plog.Noticef("authentication failed, invalid password for user %s", username)
  268. }
  269. return 0, ErrAuthFailed
  270. }
  271. return getRevision(tx), nil
  272. }
  273. func (as *authStore) Recover(be backend.Backend) {
  274. enabled := false
  275. as.be = be
  276. tx := be.BatchTx()
  277. tx.Lock()
  278. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  279. if len(vs) == 1 {
  280. if bytes.Equal(vs[0], authEnabled) {
  281. enabled = true
  282. }
  283. }
  284. as.setRevision(getRevision(tx))
  285. tx.Unlock()
  286. as.enabledMu.Lock()
  287. as.enabled = enabled
  288. as.enabledMu.Unlock()
  289. }
  290. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  291. if len(r.Name) == 0 {
  292. return nil, ErrUserEmpty
  293. }
  294. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), as.bcryptCost)
  295. if err != nil {
  296. if as.lg != nil {
  297. as.lg.Warn(
  298. "failed to bcrypt hash password",
  299. zap.String("user-name", r.Name),
  300. zap.Error(err),
  301. )
  302. } else {
  303. plog.Errorf("failed to hash password: %s", err)
  304. }
  305. return nil, err
  306. }
  307. tx := as.be.BatchTx()
  308. tx.Lock()
  309. defer tx.Unlock()
  310. user := getUser(as.lg, tx, r.Name)
  311. if user != nil {
  312. return nil, ErrUserAlreadyExist
  313. }
  314. newUser := &authpb.User{
  315. Name: []byte(r.Name),
  316. Password: hashed,
  317. }
  318. putUser(as.lg, tx, newUser)
  319. as.commitRevision(tx)
  320. if as.lg != nil {
  321. as.lg.Info("added a user", zap.String("user-name", r.Name))
  322. } else {
  323. plog.Noticef("added a new user: %s", r.Name)
  324. }
  325. return &pb.AuthUserAddResponse{}, nil
  326. }
  327. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  328. if as.enabled && r.Name == rootUser {
  329. if as.lg != nil {
  330. as.lg.Warn("cannot delete 'root' user", zap.String("user-name", r.Name))
  331. } else {
  332. plog.Errorf("the user root must not be deleted")
  333. }
  334. return nil, ErrInvalidAuthMgmt
  335. }
  336. tx := as.be.BatchTx()
  337. tx.Lock()
  338. defer tx.Unlock()
  339. user := getUser(as.lg, tx, r.Name)
  340. if user == nil {
  341. return nil, ErrUserNotFound
  342. }
  343. delUser(tx, r.Name)
  344. as.commitRevision(tx)
  345. as.invalidateCachedPerm(r.Name)
  346. as.tokenProvider.invalidateUser(r.Name)
  347. if as.lg != nil {
  348. as.lg.Info(
  349. "deleted a user",
  350. zap.String("user-name", r.Name),
  351. zap.Strings("user-roles", user.Roles),
  352. )
  353. } else {
  354. plog.Noticef("deleted a user: %s", r.Name)
  355. }
  356. return &pb.AuthUserDeleteResponse{}, nil
  357. }
  358. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  359. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  360. // If the cost is too high, we should move the encryption to outside of the raft
  361. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), as.bcryptCost)
  362. if err != nil {
  363. if as.lg != nil {
  364. as.lg.Warn(
  365. "failed to bcrypt hash password",
  366. zap.String("user-name", r.Name),
  367. zap.Error(err),
  368. )
  369. } else {
  370. plog.Errorf("failed to hash password: %s", err)
  371. }
  372. return nil, err
  373. }
  374. tx := as.be.BatchTx()
  375. tx.Lock()
  376. defer tx.Unlock()
  377. user := getUser(as.lg, tx, r.Name)
  378. if user == nil {
  379. return nil, ErrUserNotFound
  380. }
  381. updatedUser := &authpb.User{
  382. Name: []byte(r.Name),
  383. Roles: user.Roles,
  384. Password: hashed,
  385. }
  386. putUser(as.lg, tx, updatedUser)
  387. as.commitRevision(tx)
  388. as.invalidateCachedPerm(r.Name)
  389. as.tokenProvider.invalidateUser(r.Name)
  390. if as.lg != nil {
  391. as.lg.Info(
  392. "changed a password of a user",
  393. zap.String("user-name", r.Name),
  394. zap.Strings("user-roles", user.Roles),
  395. )
  396. } else {
  397. plog.Noticef("changed a password of a user: %s", r.Name)
  398. }
  399. return &pb.AuthUserChangePasswordResponse{}, nil
  400. }
  401. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  402. tx := as.be.BatchTx()
  403. tx.Lock()
  404. defer tx.Unlock()
  405. user := getUser(as.lg, tx, r.User)
  406. if user == nil {
  407. return nil, ErrUserNotFound
  408. }
  409. if r.Role != rootRole {
  410. role := getRole(tx, r.Role)
  411. if role == nil {
  412. return nil, ErrRoleNotFound
  413. }
  414. }
  415. idx := sort.SearchStrings(user.Roles, r.Role)
  416. if idx < len(user.Roles) && user.Roles[idx] == r.Role {
  417. if as.lg != nil {
  418. as.lg.Warn(
  419. "ignored grant role request to a user",
  420. zap.String("user-name", r.User),
  421. zap.Strings("user-roles", user.Roles),
  422. zap.String("duplicate-role-name", r.Role),
  423. )
  424. } else {
  425. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  426. }
  427. return &pb.AuthUserGrantRoleResponse{}, nil
  428. }
  429. user.Roles = append(user.Roles, r.Role)
  430. sort.Strings(user.Roles)
  431. putUser(as.lg, tx, user)
  432. as.invalidateCachedPerm(r.User)
  433. as.commitRevision(tx)
  434. if as.lg != nil {
  435. as.lg.Info(
  436. "granted a role to a user",
  437. zap.String("user-name", r.User),
  438. zap.Strings("user-roles", user.Roles),
  439. zap.String("added-role-name", r.Role),
  440. )
  441. } else {
  442. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  443. }
  444. return &pb.AuthUserGrantRoleResponse{}, nil
  445. }
  446. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  447. tx := as.be.BatchTx()
  448. tx.Lock()
  449. user := getUser(as.lg, tx, r.Name)
  450. tx.Unlock()
  451. if user == nil {
  452. return nil, ErrUserNotFound
  453. }
  454. var resp pb.AuthUserGetResponse
  455. resp.Roles = append(resp.Roles, user.Roles...)
  456. return &resp, nil
  457. }
  458. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  459. tx := as.be.BatchTx()
  460. tx.Lock()
  461. users := getAllUsers(as.lg, tx)
  462. tx.Unlock()
  463. resp := &pb.AuthUserListResponse{Users: make([]string, len(users))}
  464. for i := range users {
  465. resp.Users[i] = string(users[i].Name)
  466. }
  467. return resp, nil
  468. }
  469. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  470. if as.enabled && r.Name == rootUser && r.Role == rootRole {
  471. if as.lg != nil {
  472. as.lg.Warn(
  473. "'root' user cannot revoke 'root' role",
  474. zap.String("user-name", r.Name),
  475. zap.String("role-name", r.Role),
  476. )
  477. } else {
  478. plog.Errorf("the role root must not be revoked from the user root")
  479. }
  480. return nil, ErrInvalidAuthMgmt
  481. }
  482. tx := as.be.BatchTx()
  483. tx.Lock()
  484. defer tx.Unlock()
  485. user := getUser(as.lg, tx, r.Name)
  486. if user == nil {
  487. return nil, ErrUserNotFound
  488. }
  489. updatedUser := &authpb.User{
  490. Name: user.Name,
  491. Password: user.Password,
  492. }
  493. for _, role := range user.Roles {
  494. if role != r.Role {
  495. updatedUser.Roles = append(updatedUser.Roles, role)
  496. }
  497. }
  498. if len(updatedUser.Roles) == len(user.Roles) {
  499. return nil, ErrRoleNotGranted
  500. }
  501. putUser(as.lg, tx, updatedUser)
  502. as.invalidateCachedPerm(r.Name)
  503. as.commitRevision(tx)
  504. if as.lg != nil {
  505. as.lg.Info(
  506. "revoked a role from a user",
  507. zap.String("user-name", r.Name),
  508. zap.Strings("old-user-roles", user.Roles),
  509. zap.Strings("new-user-roles", updatedUser.Roles),
  510. zap.String("revoked-role-name", r.Role),
  511. )
  512. } else {
  513. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  514. }
  515. return &pb.AuthUserRevokeRoleResponse{}, nil
  516. }
  517. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  518. tx := as.be.BatchTx()
  519. tx.Lock()
  520. defer tx.Unlock()
  521. var resp pb.AuthRoleGetResponse
  522. role := getRole(tx, r.Role)
  523. if role == nil {
  524. return nil, ErrRoleNotFound
  525. }
  526. resp.Perm = append(resp.Perm, role.KeyPermission...)
  527. return &resp, nil
  528. }
  529. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  530. tx := as.be.BatchTx()
  531. tx.Lock()
  532. roles := getAllRoles(as.lg, tx)
  533. tx.Unlock()
  534. resp := &pb.AuthRoleListResponse{Roles: make([]string, len(roles))}
  535. for i := range roles {
  536. resp.Roles[i] = string(roles[i].Name)
  537. }
  538. return resp, nil
  539. }
  540. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  541. tx := as.be.BatchTx()
  542. tx.Lock()
  543. defer tx.Unlock()
  544. role := getRole(tx, r.Role)
  545. if role == nil {
  546. return nil, ErrRoleNotFound
  547. }
  548. updatedRole := &authpb.Role{
  549. Name: role.Name,
  550. }
  551. for _, perm := range role.KeyPermission {
  552. if !bytes.Equal(perm.Key, r.Key) || !bytes.Equal(perm.RangeEnd, r.RangeEnd) {
  553. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  554. }
  555. }
  556. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  557. return nil, ErrPermissionNotGranted
  558. }
  559. putRole(as.lg, tx, updatedRole)
  560. // TODO(mitake): currently single role update invalidates every cache
  561. // It should be optimized.
  562. as.clearCachedPerm()
  563. as.commitRevision(tx)
  564. if as.lg != nil {
  565. as.lg.Info(
  566. "revoked a permission on range",
  567. zap.String("role-name", r.Role),
  568. zap.String("key", string(r.Key)),
  569. zap.String("range-end", string(r.RangeEnd)),
  570. )
  571. } else {
  572. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  573. }
  574. return &pb.AuthRoleRevokePermissionResponse{}, nil
  575. }
  576. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  577. if as.enabled && r.Role == rootRole {
  578. if as.lg != nil {
  579. as.lg.Warn("cannot delete 'root' role", zap.String("role-name", r.Role))
  580. } else {
  581. plog.Errorf("the role root must not be deleted")
  582. }
  583. return nil, ErrInvalidAuthMgmt
  584. }
  585. tx := as.be.BatchTx()
  586. tx.Lock()
  587. defer tx.Unlock()
  588. role := getRole(tx, r.Role)
  589. if role == nil {
  590. return nil, ErrRoleNotFound
  591. }
  592. delRole(tx, r.Role)
  593. users := getAllUsers(as.lg, tx)
  594. for _, user := range users {
  595. updatedUser := &authpb.User{
  596. Name: user.Name,
  597. Password: user.Password,
  598. }
  599. for _, role := range user.Roles {
  600. if role != r.Role {
  601. updatedUser.Roles = append(updatedUser.Roles, role)
  602. }
  603. }
  604. if len(updatedUser.Roles) == len(user.Roles) {
  605. continue
  606. }
  607. putUser(as.lg, tx, updatedUser)
  608. as.invalidateCachedPerm(string(user.Name))
  609. }
  610. as.commitRevision(tx)
  611. if as.lg != nil {
  612. as.lg.Info("deleted a role", zap.String("role-name", r.Role))
  613. } else {
  614. plog.Noticef("deleted role %s", r.Role)
  615. }
  616. return &pb.AuthRoleDeleteResponse{}, nil
  617. }
  618. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  619. tx := as.be.BatchTx()
  620. tx.Lock()
  621. defer tx.Unlock()
  622. role := getRole(tx, r.Name)
  623. if role != nil {
  624. return nil, ErrRoleAlreadyExist
  625. }
  626. newRole := &authpb.Role{
  627. Name: []byte(r.Name),
  628. }
  629. putRole(as.lg, tx, newRole)
  630. as.commitRevision(tx)
  631. if as.lg != nil {
  632. as.lg.Info("created a role", zap.String("role-name", r.Name))
  633. } else {
  634. plog.Noticef("Role %s is created", r.Name)
  635. }
  636. return &pb.AuthRoleAddResponse{}, nil
  637. }
  638. func (as *authStore) authInfoFromToken(ctx context.Context, token string) (*AuthInfo, bool) {
  639. return as.tokenProvider.info(ctx, token, as.Revision())
  640. }
  641. type permSlice []*authpb.Permission
  642. func (perms permSlice) Len() int {
  643. return len(perms)
  644. }
  645. func (perms permSlice) Less(i, j int) bool {
  646. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  647. }
  648. func (perms permSlice) Swap(i, j int) {
  649. perms[i], perms[j] = perms[j], perms[i]
  650. }
  651. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  652. tx := as.be.BatchTx()
  653. tx.Lock()
  654. defer tx.Unlock()
  655. role := getRole(tx, r.Name)
  656. if role == nil {
  657. return nil, ErrRoleNotFound
  658. }
  659. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  660. return bytes.Compare(role.KeyPermission[i].Key, r.Perm.Key) >= 0
  661. })
  662. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  663. // update existing permission
  664. role.KeyPermission[idx].PermType = r.Perm.PermType
  665. } else {
  666. // append new permission to the role
  667. newPerm := &authpb.Permission{
  668. Key: r.Perm.Key,
  669. RangeEnd: r.Perm.RangeEnd,
  670. PermType: r.Perm.PermType,
  671. }
  672. role.KeyPermission = append(role.KeyPermission, newPerm)
  673. sort.Sort(permSlice(role.KeyPermission))
  674. }
  675. putRole(as.lg, tx, role)
  676. // TODO(mitake): currently single role update invalidates every cache
  677. // It should be optimized.
  678. as.clearCachedPerm()
  679. as.commitRevision(tx)
  680. if as.lg != nil {
  681. as.lg.Info(
  682. "granted/updated a permission to a user",
  683. zap.String("user-name", r.Name),
  684. zap.String("permission-name", authpb.Permission_Type_name[int32(r.Perm.PermType)]),
  685. )
  686. } else {
  687. 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)])
  688. }
  689. return &pb.AuthRoleGrantPermissionResponse{}, nil
  690. }
  691. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  692. // TODO(mitake): this function would be costly so we need a caching mechanism
  693. if !as.IsAuthEnabled() {
  694. return nil
  695. }
  696. // only gets rev == 0 when passed AuthInfo{}; no user given
  697. if revision == 0 {
  698. return ErrUserEmpty
  699. }
  700. if revision < as.Revision() {
  701. return ErrAuthOldRevision
  702. }
  703. tx := as.be.BatchTx()
  704. tx.Lock()
  705. defer tx.Unlock()
  706. user := getUser(as.lg, tx, userName)
  707. if user == nil {
  708. if as.lg != nil {
  709. as.lg.Warn("cannot find a user for permission check", zap.String("user-name", userName))
  710. } else {
  711. plog.Errorf("invalid user name %s for permission checking", userName)
  712. }
  713. return ErrPermissionDenied
  714. }
  715. // root role should have permission on all ranges
  716. if hasRootRole(user) {
  717. return nil
  718. }
  719. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  720. return nil
  721. }
  722. return ErrPermissionDenied
  723. }
  724. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  725. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  726. }
  727. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  728. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  729. }
  730. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  731. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  732. }
  733. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  734. if !as.IsAuthEnabled() {
  735. return nil
  736. }
  737. if authInfo == nil {
  738. return ErrUserEmpty
  739. }
  740. tx := as.be.BatchTx()
  741. tx.Lock()
  742. u := getUser(as.lg, tx, authInfo.Username)
  743. tx.Unlock()
  744. if u == nil {
  745. return ErrUserNotFound
  746. }
  747. if !hasRootRole(u) {
  748. return ErrPermissionDenied
  749. }
  750. return nil
  751. }
  752. func getUser(lg *zap.Logger, tx backend.BatchTx, username string) *authpb.User {
  753. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  754. if len(vs) == 0 {
  755. return nil
  756. }
  757. user := &authpb.User{}
  758. err := user.Unmarshal(vs[0])
  759. if err != nil {
  760. if lg != nil {
  761. lg.Panic(
  762. "failed to unmarshal 'authpb.User'",
  763. zap.String("user-name", username),
  764. zap.Error(err),
  765. )
  766. } else {
  767. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  768. }
  769. }
  770. return user
  771. }
  772. func getAllUsers(lg *zap.Logger, tx backend.BatchTx) []*authpb.User {
  773. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  774. if len(vs) == 0 {
  775. return nil
  776. }
  777. users := make([]*authpb.User, len(vs))
  778. for i := range vs {
  779. user := &authpb.User{}
  780. err := user.Unmarshal(vs[i])
  781. if err != nil {
  782. if lg != nil {
  783. lg.Panic("failed to unmarshal 'authpb.User'", zap.Error(err))
  784. } else {
  785. plog.Panicf("failed to unmarshal user struct: %s", err)
  786. }
  787. }
  788. users[i] = user
  789. }
  790. return users
  791. }
  792. func putUser(lg *zap.Logger, tx backend.BatchTx, user *authpb.User) {
  793. b, err := user.Marshal()
  794. if err != nil {
  795. if lg != nil {
  796. lg.Panic("failed to unmarshal 'authpb.User'", zap.Error(err))
  797. } else {
  798. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  799. }
  800. }
  801. tx.UnsafePut(authUsersBucketName, user.Name, b)
  802. }
  803. func delUser(tx backend.BatchTx, username string) {
  804. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  805. }
  806. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  807. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  808. if len(vs) == 0 {
  809. return nil
  810. }
  811. role := &authpb.Role{}
  812. err := role.Unmarshal(vs[0])
  813. if err != nil {
  814. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  815. }
  816. return role
  817. }
  818. func getAllRoles(lg *zap.Logger, tx backend.BatchTx) []*authpb.Role {
  819. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  820. if len(vs) == 0 {
  821. return nil
  822. }
  823. roles := make([]*authpb.Role, len(vs))
  824. for i := range vs {
  825. role := &authpb.Role{}
  826. err := role.Unmarshal(vs[i])
  827. if err != nil {
  828. if lg != nil {
  829. lg.Panic("failed to unmarshal 'authpb.Role'", zap.Error(err))
  830. } else {
  831. plog.Panicf("failed to unmarshal role struct: %s", err)
  832. }
  833. }
  834. roles[i] = role
  835. }
  836. return roles
  837. }
  838. func putRole(lg *zap.Logger, tx backend.BatchTx, role *authpb.Role) {
  839. b, err := role.Marshal()
  840. if err != nil {
  841. if lg != nil {
  842. lg.Panic(
  843. "failed to marshal 'authpb.Role'",
  844. zap.String("role-name", string(role.Name)),
  845. zap.Error(err),
  846. )
  847. } else {
  848. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  849. }
  850. }
  851. tx.UnsafePut(authRolesBucketName, role.Name, b)
  852. }
  853. func delRole(tx backend.BatchTx, rolename string) {
  854. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  855. }
  856. func (as *authStore) IsAuthEnabled() bool {
  857. as.enabledMu.RLock()
  858. defer as.enabledMu.RUnlock()
  859. return as.enabled
  860. }
  861. // NewAuthStore creates a new AuthStore.
  862. func NewAuthStore(lg *zap.Logger, be backend.Backend, tp TokenProvider, bcryptCost int) *authStore {
  863. if bcryptCost < bcrypt.MinCost || bcryptCost > bcrypt.MaxCost {
  864. if lg != nil {
  865. lg.Warn(
  866. "use default bcrypt cost instead of the invalid given cost",
  867. zap.Int("min-cost", bcrypt.MinCost),
  868. zap.Int("max-cost", bcrypt.MaxCost),
  869. zap.Int("default-cost", bcrypt.DefaultCost),
  870. zap.Int("given-cost", bcryptCost))
  871. } else {
  872. plog.Warningf("Use default bcrypt-cost %d instead of the invalid value %d",
  873. bcrypt.DefaultCost, bcryptCost)
  874. }
  875. bcryptCost = bcrypt.DefaultCost
  876. }
  877. tx := be.BatchTx()
  878. tx.Lock()
  879. tx.UnsafeCreateBucket(authBucketName)
  880. tx.UnsafeCreateBucket(authUsersBucketName)
  881. tx.UnsafeCreateBucket(authRolesBucketName)
  882. enabled := false
  883. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  884. if len(vs) == 1 {
  885. if bytes.Equal(vs[0], authEnabled) {
  886. enabled = true
  887. }
  888. }
  889. as := &authStore{
  890. revision: getRevision(tx),
  891. lg: lg,
  892. be: be,
  893. enabled: enabled,
  894. rangePermCache: make(map[string]*unifiedRangePermissions),
  895. tokenProvider: tp,
  896. bcryptCost: bcryptCost,
  897. }
  898. if enabled {
  899. as.tokenProvider.enable()
  900. }
  901. if as.Revision() == 0 {
  902. as.commitRevision(tx)
  903. }
  904. tx.Unlock()
  905. be.ForceCommit()
  906. return as
  907. }
  908. func hasRootRole(u *authpb.User) bool {
  909. // u.Roles is sorted in UserGrantRole(), so we can use binary search.
  910. idx := sort.SearchStrings(u.Roles, rootRole)
  911. return idx != len(u.Roles) && u.Roles[idx] == rootRole
  912. }
  913. func (as *authStore) commitRevision(tx backend.BatchTx) {
  914. atomic.AddUint64(&as.revision, 1)
  915. revBytes := make([]byte, revBytesLen)
  916. binary.BigEndian.PutUint64(revBytes, as.Revision())
  917. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  918. }
  919. func getRevision(tx backend.BatchTx) uint64 {
  920. _, vs := tx.UnsafeRange(authBucketName, revisionKey, nil, 0)
  921. if len(vs) != 1 {
  922. // this can happen in the initialization phase
  923. return 0
  924. }
  925. return binary.BigEndian.Uint64(vs[0])
  926. }
  927. func (as *authStore) setRevision(rev uint64) {
  928. atomic.StoreUint64(&as.revision, rev)
  929. }
  930. func (as *authStore) Revision() uint64 {
  931. return atomic.LoadUint64(&as.revision)
  932. }
  933. func (as *authStore) AuthInfoFromTLS(ctx context.Context) (ai *AuthInfo) {
  934. peer, ok := peer.FromContext(ctx)
  935. if !ok || peer == nil || peer.AuthInfo == nil {
  936. return nil
  937. }
  938. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  939. for _, chains := range tlsInfo.State.VerifiedChains {
  940. if len(chains) < 1 {
  941. continue
  942. }
  943. ai = &AuthInfo{
  944. Username: chains[0].Subject.CommonName,
  945. Revision: as.Revision(),
  946. }
  947. if as.lg != nil {
  948. as.lg.Debug(
  949. "found command name",
  950. zap.String("common-name", ai.Username),
  951. zap.String("user-name", ai.Username),
  952. zap.Uint64("revision", ai.Revision),
  953. )
  954. } else {
  955. plog.Debugf("found common name %s", ai.Username)
  956. }
  957. break
  958. }
  959. return ai
  960. }
  961. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  962. md, ok := metadata.FromIncomingContext(ctx)
  963. if !ok {
  964. return nil, nil
  965. }
  966. //TODO(mitake|hexfusion) review unifying key names
  967. ts, ok := md[rpctypes.TokenFieldNameGRPC]
  968. if !ok {
  969. ts, ok = md[rpctypes.TokenFieldNameSwagger]
  970. }
  971. if !ok {
  972. return nil, nil
  973. }
  974. token := ts[0]
  975. authInfo, uok := as.authInfoFromToken(ctx, token)
  976. if !uok {
  977. if as.lg != nil {
  978. as.lg.Warn("invalid auth token", zap.String("token", token))
  979. } else {
  980. plog.Warningf("invalid auth token: %s", token)
  981. }
  982. return nil, ErrInvalidAuthToken
  983. }
  984. return authInfo, nil
  985. }
  986. func (as *authStore) GenTokenPrefix() (string, error) {
  987. return as.tokenProvider.genTokenPrefix()
  988. }
  989. func decomposeOpts(lg *zap.Logger, optstr string) (string, map[string]string, error) {
  990. opts := strings.Split(optstr, ",")
  991. tokenType := opts[0]
  992. typeSpecificOpts := make(map[string]string)
  993. for i := 1; i < len(opts); i++ {
  994. pair := strings.Split(opts[i], "=")
  995. if len(pair) != 2 {
  996. if lg != nil {
  997. lg.Warn("invalid token option", zap.String("option", optstr))
  998. } else {
  999. plog.Errorf("invalid token specific option: %s", optstr)
  1000. }
  1001. return "", nil, ErrInvalidAuthOpts
  1002. }
  1003. if _, ok := typeSpecificOpts[pair[0]]; ok {
  1004. if lg != nil {
  1005. lg.Warn(
  1006. "invalid token option",
  1007. zap.String("option", optstr),
  1008. zap.String("duplicate-parameter", pair[0]),
  1009. )
  1010. } else {
  1011. plog.Errorf("invalid token specific option, duplicated parameters (%s): %s", pair[0], optstr)
  1012. }
  1013. return "", nil, ErrInvalidAuthOpts
  1014. }
  1015. typeSpecificOpts[pair[0]] = pair[1]
  1016. }
  1017. return tokenType, typeSpecificOpts, nil
  1018. }
  1019. // NewTokenProvider creates a new token provider.
  1020. func NewTokenProvider(
  1021. lg *zap.Logger,
  1022. tokenOpts string,
  1023. indexWaiter func(uint64) <-chan struct{}) (TokenProvider, error) {
  1024. tokenType, typeSpecificOpts, err := decomposeOpts(lg, tokenOpts)
  1025. if err != nil {
  1026. return nil, ErrInvalidAuthOpts
  1027. }
  1028. switch tokenType {
  1029. case "simple":
  1030. if lg != nil {
  1031. lg.Warn("simple token is not cryptographically signed")
  1032. } else {
  1033. plog.Warningf("simple token is not cryptographically signed")
  1034. }
  1035. return newTokenProviderSimple(lg, indexWaiter), nil
  1036. case "jwt":
  1037. return newTokenProviderJWT(lg, typeSpecificOpts)
  1038. case "":
  1039. return newTokenProviderNop()
  1040. default:
  1041. if lg != nil {
  1042. lg.Warn(
  1043. "unknown token type",
  1044. zap.String("type", tokenType),
  1045. zap.Error(ErrInvalidAuthOpts),
  1046. )
  1047. } else {
  1048. plog.Errorf("unknown token type: %s", tokenType)
  1049. }
  1050. return nil, ErrInvalidAuthOpts
  1051. }
  1052. }
  1053. func (as *authStore) WithRoot(ctx context.Context) context.Context {
  1054. if !as.IsAuthEnabled() {
  1055. return ctx
  1056. }
  1057. var ctxForAssign context.Context
  1058. if ts := as.tokenProvider.(*tokenSimple); ts != nil {
  1059. ctx1 := context.WithValue(ctx, AuthenticateParamIndex{}, uint64(0))
  1060. prefix, err := ts.genTokenPrefix()
  1061. if err != nil {
  1062. if as.lg != nil {
  1063. as.lg.Warn(
  1064. "failed to generate prefix of internally used token",
  1065. zap.Error(err),
  1066. )
  1067. } else {
  1068. plog.Errorf("failed to generate prefix of internally used token")
  1069. }
  1070. return ctx
  1071. }
  1072. ctxForAssign = context.WithValue(ctx1, AuthenticateParamSimpleTokenPrefix{}, prefix)
  1073. } else {
  1074. ctxForAssign = ctx
  1075. }
  1076. token, err := as.tokenProvider.assign(ctxForAssign, "root", as.Revision())
  1077. if err != nil {
  1078. // this must not happen
  1079. if as.lg != nil {
  1080. as.lg.Warn(
  1081. "failed to assign token for lease revoking",
  1082. zap.Error(err),
  1083. )
  1084. } else {
  1085. plog.Errorf("failed to assign token for lease revoking: %s", err)
  1086. }
  1087. return ctx
  1088. }
  1089. mdMap := map[string]string{
  1090. rpctypes.TokenFieldNameGRPC: token,
  1091. }
  1092. tokenMD := metadata.New(mdMap)
  1093. // use "mdIncomingKey{}" since it's called from local etcdserver
  1094. return metadata.NewIncomingContext(ctx, tokenMD)
  1095. }
  1096. func (as *authStore) HasRole(user, role string) bool {
  1097. tx := as.be.BatchTx()
  1098. tx.Lock()
  1099. u := getUser(as.lg, tx, user)
  1100. tx.Unlock()
  1101. if u == nil {
  1102. if as.lg != nil {
  1103. as.lg.Warn(
  1104. "'has-role' requested for non-existing user",
  1105. zap.String("user-name", user),
  1106. zap.String("role-name", role),
  1107. )
  1108. } else {
  1109. plog.Warningf("tried to check user %s has role %s, but user %s doesn't exist", user, role, user)
  1110. }
  1111. return false
  1112. }
  1113. for _, r := range u.Roles {
  1114. if role == r {
  1115. return true
  1116. }
  1117. }
  1118. return false
  1119. }
  1120. func (as *authStore) BcryptCost() int {
  1121. return as.bcryptCost
  1122. }