store.go 34 KB

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