store.go 35 KB

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