store.go 35 KB

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