store_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. "context"
  17. "fmt"
  18. "os"
  19. "reflect"
  20. "strings"
  21. "sync"
  22. "testing"
  23. "time"
  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. "go.uber.org/zap"
  29. "golang.org/x/crypto/bcrypt"
  30. "google.golang.org/grpc/metadata"
  31. )
  32. func dummyIndexWaiter(index uint64) <-chan struct{} {
  33. ch := make(chan struct{})
  34. go func() {
  35. ch <- struct{}{}
  36. }()
  37. return ch
  38. }
  39. // TestNewAuthStoreRevision ensures newly auth store
  40. // keeps the old revision when there are no changes.
  41. func TestNewAuthStoreRevision(t *testing.T) {
  42. b, tPath := backend.NewDefaultTmpBackend()
  43. defer os.Remove(tPath)
  44. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. as := NewAuthStore(zap.NewExample(), b, tp, bcrypt.MinCost)
  49. err = enableAuthAndCreateRoot(as)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. old := as.Revision()
  54. as.Close()
  55. b.Close()
  56. // no changes to commit
  57. b2 := backend.NewDefaultBackend(tPath)
  58. as = NewAuthStore(zap.NewExample(), b2, tp, bcrypt.MinCost)
  59. new := as.Revision()
  60. as.Close()
  61. b2.Close()
  62. if old != new {
  63. t.Fatalf("expected revision %d, got %d", old, new)
  64. }
  65. }
  66. // TestNewAuthStoreBryptCost ensures that NewAuthStore uses default when given bcrypt-cost is invalid
  67. func TestNewAuthStoreBcryptCost(t *testing.T) {
  68. b, tPath := backend.NewDefaultTmpBackend()
  69. defer os.Remove(tPath)
  70. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  71. if err != nil {
  72. t.Fatal(err)
  73. }
  74. invalidCosts := [2]int{bcrypt.MinCost - 1, bcrypt.MaxCost + 1}
  75. for _, invalidCost := range invalidCosts {
  76. as := NewAuthStore(zap.NewExample(), b, tp, invalidCost)
  77. if as.BcryptCost() != bcrypt.DefaultCost {
  78. t.Fatalf("expected DefaultCost when bcryptcost is invalid")
  79. }
  80. as.Close()
  81. }
  82. b.Close()
  83. }
  84. func setupAuthStore(t *testing.T) (store *authStore, teardownfunc func(t *testing.T)) {
  85. b, tPath := backend.NewDefaultTmpBackend()
  86. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. as := NewAuthStore(zap.NewExample(), b, tp, bcrypt.MinCost)
  91. err = enableAuthAndCreateRoot(as)
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. // adds a new role
  96. _, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test"})
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. ua := &pb.AuthUserAddRequest{Name: "foo", Password: "bar", Options: &authpb.UserAddOptions{NoPassword: false}}
  101. _, err = as.UserAdd(ua) // add a non-existing user
  102. if err != nil {
  103. t.Fatal(err)
  104. }
  105. tearDown := func(_ *testing.T) {
  106. b.Close()
  107. os.Remove(tPath)
  108. as.Close()
  109. }
  110. return as, tearDown
  111. }
  112. func enableAuthAndCreateRoot(as *authStore) error {
  113. _, err := as.UserAdd(&pb.AuthUserAddRequest{Name: "root", Password: "root", Options: &authpb.UserAddOptions{NoPassword: false}})
  114. if err != nil {
  115. return err
  116. }
  117. _, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: "root"})
  118. if err != nil {
  119. return err
  120. }
  121. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "root", Role: "root"})
  122. if err != nil {
  123. return err
  124. }
  125. return as.AuthEnable()
  126. }
  127. func TestUserAdd(t *testing.T) {
  128. as, tearDown := setupAuthStore(t)
  129. defer tearDown(t)
  130. ua := &pb.AuthUserAddRequest{Name: "foo", Options: &authpb.UserAddOptions{NoPassword: false}}
  131. _, err := as.UserAdd(ua) // add an existing user
  132. if err == nil {
  133. t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err)
  134. }
  135. if err != ErrUserAlreadyExist {
  136. t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err)
  137. }
  138. ua = &pb.AuthUserAddRequest{Name: "", Options: &authpb.UserAddOptions{NoPassword: false}}
  139. _, err = as.UserAdd(ua) // add a user with empty name
  140. if err != ErrUserEmpty {
  141. t.Fatal(err)
  142. }
  143. }
  144. func TestRecover(t *testing.T) {
  145. as, tearDown := setupAuthStore(t)
  146. defer tearDown(t)
  147. as.enabled = false
  148. as.Recover(as.be)
  149. if !as.IsAuthEnabled() {
  150. t.Fatalf("expected auth enabled got disabled")
  151. }
  152. }
  153. func TestCheckPassword(t *testing.T) {
  154. as, tearDown := setupAuthStore(t)
  155. defer tearDown(t)
  156. // auth a non-existing user
  157. _, err := as.CheckPassword("foo-test", "bar")
  158. if err == nil {
  159. t.Fatalf("expected %v, got %v", ErrAuthFailed, err)
  160. }
  161. if err != ErrAuthFailed {
  162. t.Fatalf("expected %v, got %v", ErrAuthFailed, err)
  163. }
  164. // auth an existing user with correct password
  165. _, err = as.CheckPassword("foo", "bar")
  166. if err != nil {
  167. t.Fatal(err)
  168. }
  169. // auth an existing user but with wrong password
  170. _, err = as.CheckPassword("foo", "")
  171. if err == nil {
  172. t.Fatalf("expected %v, got %v", ErrAuthFailed, err)
  173. }
  174. if err != ErrAuthFailed {
  175. t.Fatalf("expected %v, got %v", ErrAuthFailed, err)
  176. }
  177. }
  178. func TestUserDelete(t *testing.T) {
  179. as, tearDown := setupAuthStore(t)
  180. defer tearDown(t)
  181. // delete an existing user
  182. ud := &pb.AuthUserDeleteRequest{Name: "foo"}
  183. _, err := as.UserDelete(ud)
  184. if err != nil {
  185. t.Fatal(err)
  186. }
  187. // delete a non-existing user
  188. _, err = as.UserDelete(ud)
  189. if err == nil {
  190. t.Fatalf("expected %v, got %v", ErrUserNotFound, err)
  191. }
  192. if err != ErrUserNotFound {
  193. t.Fatalf("expected %v, got %v", ErrUserNotFound, err)
  194. }
  195. }
  196. func TestUserChangePassword(t *testing.T) {
  197. as, tearDown := setupAuthStore(t)
  198. defer tearDown(t)
  199. ctx1 := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  200. _, err := as.Authenticate(ctx1, "foo", "bar")
  201. if err != nil {
  202. t.Fatal(err)
  203. }
  204. _, err = as.UserChangePassword(&pb.AuthUserChangePasswordRequest{Name: "foo", Password: "baz"})
  205. if err != nil {
  206. t.Fatal(err)
  207. }
  208. ctx2 := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(2)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  209. _, err = as.Authenticate(ctx2, "foo", "baz")
  210. if err != nil {
  211. t.Fatal(err)
  212. }
  213. // change a non-existing user
  214. _, err = as.UserChangePassword(&pb.AuthUserChangePasswordRequest{Name: "foo-test", Password: "bar"})
  215. if err == nil {
  216. t.Fatalf("expected %v, got %v", ErrUserNotFound, err)
  217. }
  218. if err != ErrUserNotFound {
  219. t.Fatalf("expected %v, got %v", ErrUserNotFound, err)
  220. }
  221. }
  222. func TestRoleAdd(t *testing.T) {
  223. as, tearDown := setupAuthStore(t)
  224. defer tearDown(t)
  225. // adds a new role
  226. _, err := as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test-1"})
  227. if err != nil {
  228. t.Fatal(err)
  229. }
  230. // add a role with empty name
  231. _, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: ""})
  232. if err != ErrRoleEmpty {
  233. t.Fatal(err)
  234. }
  235. }
  236. func TestUserGrant(t *testing.T) {
  237. as, tearDown := setupAuthStore(t)
  238. defer tearDown(t)
  239. // grants a role to the user
  240. _, err := as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test"})
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. // grants a role to a non-existing user
  245. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo-test", Role: "role-test"})
  246. if err == nil {
  247. t.Errorf("expected %v, got %v", ErrUserNotFound, err)
  248. }
  249. if err != ErrUserNotFound {
  250. t.Errorf("expected %v, got %v", ErrUserNotFound, err)
  251. }
  252. }
  253. func TestHasRole(t *testing.T) {
  254. as, tearDown := setupAuthStore(t)
  255. defer tearDown(t)
  256. // grants a role to the user
  257. _, err := as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test"})
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. // checks role reflects correctly
  262. hr := as.HasRole("foo", "role-test")
  263. if !hr {
  264. t.Fatal("expected role granted, got false")
  265. }
  266. // checks non existent role
  267. hr = as.HasRole("foo", "non-existent-role")
  268. if hr {
  269. t.Fatal("expected role not found, got true")
  270. }
  271. // checks non existent user
  272. hr = as.HasRole("nouser", "role-test")
  273. if hr {
  274. t.Fatal("expected user not found got true")
  275. }
  276. }
  277. func TestIsOpPermitted(t *testing.T) {
  278. as, tearDown := setupAuthStore(t)
  279. defer tearDown(t)
  280. // add new role
  281. _, err := as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test-1"})
  282. if err != nil {
  283. t.Fatal(err)
  284. }
  285. perm := &authpb.Permission{
  286. PermType: authpb.WRITE,
  287. Key: []byte("Keys"),
  288. RangeEnd: []byte("RangeEnd"),
  289. }
  290. _, err = as.RoleGrantPermission(&pb.AuthRoleGrantPermissionRequest{
  291. Name: "role-test-1",
  292. Perm: perm,
  293. })
  294. if err != nil {
  295. t.Fatal(err)
  296. }
  297. // grants a role to the user
  298. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test-1"})
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. // check permission reflected to user
  303. err = as.isOpPermitted("foo", as.Revision(), perm.Key, perm.RangeEnd, perm.PermType)
  304. if err != nil {
  305. t.Fatal(err)
  306. }
  307. }
  308. func TestGetUser(t *testing.T) {
  309. as, tearDown := setupAuthStore(t)
  310. defer tearDown(t)
  311. _, err := as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test"})
  312. if err != nil {
  313. t.Fatal(err)
  314. }
  315. u, err := as.UserGet(&pb.AuthUserGetRequest{Name: "foo"})
  316. if err != nil {
  317. t.Fatal(err)
  318. }
  319. if u == nil {
  320. t.Fatal("expect user not nil, got nil")
  321. }
  322. expected := []string{"role-test"}
  323. if !reflect.DeepEqual(expected, u.Roles) {
  324. t.Errorf("expected %v, got %v", expected, u.Roles)
  325. }
  326. // check non existent user
  327. _, err = as.UserGet(&pb.AuthUserGetRequest{Name: "nouser"})
  328. if err == nil {
  329. t.Errorf("expected %v, got %v", ErrUserNotFound, err)
  330. }
  331. }
  332. func TestListUsers(t *testing.T) {
  333. as, tearDown := setupAuthStore(t)
  334. defer tearDown(t)
  335. ua := &pb.AuthUserAddRequest{Name: "user1", Password: "pwd1", Options: &authpb.UserAddOptions{NoPassword: false}}
  336. _, err := as.UserAdd(ua) // add a non-existing user
  337. if err != nil {
  338. t.Fatal(err)
  339. }
  340. ul, err := as.UserList(&pb.AuthUserListRequest{})
  341. if err != nil {
  342. t.Fatal(err)
  343. }
  344. if !contains(ul.Users, "root") {
  345. t.Errorf("expected %v in %v", "root", ul.Users)
  346. }
  347. if !contains(ul.Users, "user1") {
  348. t.Errorf("expected %v in %v", "user1", ul.Users)
  349. }
  350. }
  351. func TestRoleGrantPermission(t *testing.T) {
  352. as, tearDown := setupAuthStore(t)
  353. defer tearDown(t)
  354. _, err := as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test-1"})
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. perm := &authpb.Permission{
  359. PermType: authpb.WRITE,
  360. Key: []byte("Keys"),
  361. RangeEnd: []byte("RangeEnd"),
  362. }
  363. _, err = as.RoleGrantPermission(&pb.AuthRoleGrantPermissionRequest{
  364. Name: "role-test-1",
  365. Perm: perm,
  366. })
  367. if err != nil {
  368. t.Error(err)
  369. }
  370. r, err := as.RoleGet(&pb.AuthRoleGetRequest{Role: "role-test-1"})
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. if !reflect.DeepEqual(perm, r.Perm[0]) {
  375. t.Errorf("expected %v, got %v", perm, r.Perm[0])
  376. }
  377. }
  378. func TestRoleRevokePermission(t *testing.T) {
  379. as, tearDown := setupAuthStore(t)
  380. defer tearDown(t)
  381. _, err := as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test-1"})
  382. if err != nil {
  383. t.Fatal(err)
  384. }
  385. perm := &authpb.Permission{
  386. PermType: authpb.WRITE,
  387. Key: []byte("Keys"),
  388. RangeEnd: []byte("RangeEnd"),
  389. }
  390. _, err = as.RoleGrantPermission(&pb.AuthRoleGrantPermissionRequest{
  391. Name: "role-test-1",
  392. Perm: perm,
  393. })
  394. if err != nil {
  395. t.Fatal(err)
  396. }
  397. _, err = as.RoleGet(&pb.AuthRoleGetRequest{Role: "role-test-1"})
  398. if err != nil {
  399. t.Fatal(err)
  400. }
  401. _, err = as.RoleRevokePermission(&pb.AuthRoleRevokePermissionRequest{
  402. Role: "role-test-1",
  403. Key: []byte("Keys"),
  404. RangeEnd: []byte("RangeEnd"),
  405. })
  406. if err != nil {
  407. t.Fatal(err)
  408. }
  409. var r *pb.AuthRoleGetResponse
  410. r, err = as.RoleGet(&pb.AuthRoleGetRequest{Role: "role-test-1"})
  411. if err != nil {
  412. t.Fatal(err)
  413. }
  414. if len(r.Perm) != 0 {
  415. t.Errorf("expected %v, got %v", 0, len(r.Perm))
  416. }
  417. }
  418. func TestUserRevokePermission(t *testing.T) {
  419. as, tearDown := setupAuthStore(t)
  420. defer tearDown(t)
  421. _, err := as.RoleAdd(&pb.AuthRoleAddRequest{Name: "role-test-1"})
  422. if err != nil {
  423. t.Fatal(err)
  424. }
  425. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test"})
  426. if err != nil {
  427. t.Fatal(err)
  428. }
  429. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: "foo", Role: "role-test-1"})
  430. if err != nil {
  431. t.Fatal(err)
  432. }
  433. u, err := as.UserGet(&pb.AuthUserGetRequest{Name: "foo"})
  434. if err != nil {
  435. t.Fatal(err)
  436. }
  437. expected := []string{"role-test", "role-test-1"}
  438. if !reflect.DeepEqual(expected, u.Roles) {
  439. t.Fatalf("expected %v, got %v", expected, u.Roles)
  440. }
  441. _, err = as.UserRevokeRole(&pb.AuthUserRevokeRoleRequest{Name: "foo", Role: "role-test-1"})
  442. if err != nil {
  443. t.Fatal(err)
  444. }
  445. u, err = as.UserGet(&pb.AuthUserGetRequest{Name: "foo"})
  446. if err != nil {
  447. t.Fatal(err)
  448. }
  449. expected = []string{"role-test"}
  450. if !reflect.DeepEqual(expected, u.Roles) {
  451. t.Errorf("expected %v, got %v", expected, u.Roles)
  452. }
  453. }
  454. func TestRoleDelete(t *testing.T) {
  455. as, tearDown := setupAuthStore(t)
  456. defer tearDown(t)
  457. _, err := as.RoleDelete(&pb.AuthRoleDeleteRequest{Role: "role-test"})
  458. if err != nil {
  459. t.Fatal(err)
  460. }
  461. rl, err := as.RoleList(&pb.AuthRoleListRequest{})
  462. if err != nil {
  463. t.Fatal(err)
  464. }
  465. expected := []string{"root"}
  466. if !reflect.DeepEqual(expected, rl.Roles) {
  467. t.Errorf("expected %v, got %v", expected, rl.Roles)
  468. }
  469. }
  470. func TestAuthInfoFromCtx(t *testing.T) {
  471. as, tearDown := setupAuthStore(t)
  472. defer tearDown(t)
  473. ctx := context.Background()
  474. ai, err := as.AuthInfoFromCtx(ctx)
  475. if err != nil && ai != nil {
  476. t.Errorf("expected (nil, nil), got (%v, %v)", ai, err)
  477. }
  478. // as if it came from RPC
  479. ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{"tokens": "dummy"}))
  480. ai, err = as.AuthInfoFromCtx(ctx)
  481. if err != nil && ai != nil {
  482. t.Errorf("expected (nil, nil), got (%v, %v)", ai, err)
  483. }
  484. ctx = context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  485. resp, err := as.Authenticate(ctx, "foo", "bar")
  486. if err != nil {
  487. t.Error(err)
  488. }
  489. ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: "Invalid Token"}))
  490. _, err = as.AuthInfoFromCtx(ctx)
  491. if err != ErrInvalidAuthToken {
  492. t.Errorf("expected %v, got %v", ErrInvalidAuthToken, err)
  493. }
  494. ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: "Invalid.Token"}))
  495. _, err = as.AuthInfoFromCtx(ctx)
  496. if err != ErrInvalidAuthToken {
  497. t.Errorf("expected %v, got %v", ErrInvalidAuthToken, err)
  498. }
  499. ctx = metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: resp.Token}))
  500. ai, err = as.AuthInfoFromCtx(ctx)
  501. if err != nil {
  502. t.Error(err)
  503. }
  504. if ai.Username != "foo" {
  505. t.Errorf("expected %v, got %v", "foo", ai.Username)
  506. }
  507. }
  508. func TestAuthDisable(t *testing.T) {
  509. as, tearDown := setupAuthStore(t)
  510. defer tearDown(t)
  511. as.AuthDisable()
  512. ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(2)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  513. _, err := as.Authenticate(ctx, "foo", "bar")
  514. if err != ErrAuthNotEnabled {
  515. t.Errorf("expected %v, got %v", ErrAuthNotEnabled, err)
  516. }
  517. // Disabling disabled auth to make sure it can return safely if store is already disabled.
  518. as.AuthDisable()
  519. _, err = as.Authenticate(ctx, "foo", "bar")
  520. if err != ErrAuthNotEnabled {
  521. t.Errorf("expected %v, got %v", ErrAuthNotEnabled, err)
  522. }
  523. }
  524. // TestAuthRevisionRace ensures that access to authStore.revision is thread-safe.
  525. func TestAuthInfoFromCtxRace(t *testing.T) {
  526. b, tPath := backend.NewDefaultTmpBackend()
  527. defer os.Remove(tPath)
  528. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  529. if err != nil {
  530. t.Fatal(err)
  531. }
  532. as := NewAuthStore(zap.NewExample(), b, tp, bcrypt.MinCost)
  533. defer as.Close()
  534. donec := make(chan struct{})
  535. go func() {
  536. defer close(donec)
  537. ctx := metadata.NewIncomingContext(context.Background(), metadata.New(map[string]string{rpctypes.TokenFieldNameGRPC: "test"}))
  538. as.AuthInfoFromCtx(ctx)
  539. }()
  540. as.UserAdd(&pb.AuthUserAddRequest{Name: "test", Options: &authpb.UserAddOptions{NoPassword: false}})
  541. <-donec
  542. }
  543. func TestIsAdminPermitted(t *testing.T) {
  544. as, tearDown := setupAuthStore(t)
  545. defer tearDown(t)
  546. err := as.IsAdminPermitted(&AuthInfo{Username: "root", Revision: 1})
  547. if err != nil {
  548. t.Errorf("expected nil, got %v", err)
  549. }
  550. // invalid user
  551. err = as.IsAdminPermitted(&AuthInfo{Username: "rooti", Revision: 1})
  552. if err != ErrUserNotFound {
  553. t.Errorf("expected %v, got %v", ErrUserNotFound, err)
  554. }
  555. // non-admin user
  556. err = as.IsAdminPermitted(&AuthInfo{Username: "foo", Revision: 1})
  557. if err != ErrPermissionDenied {
  558. t.Errorf("expected %v, got %v", ErrPermissionDenied, err)
  559. }
  560. // disabled auth should return nil
  561. as.AuthDisable()
  562. err = as.IsAdminPermitted(&AuthInfo{Username: "root", Revision: 1})
  563. if err != nil {
  564. t.Errorf("expected nil, got %v", err)
  565. }
  566. }
  567. func TestRecoverFromSnapshot(t *testing.T) {
  568. as, _ := setupAuthStore(t)
  569. ua := &pb.AuthUserAddRequest{Name: "foo", Options: &authpb.UserAddOptions{NoPassword: false}}
  570. _, err := as.UserAdd(ua) // add an existing user
  571. if err == nil {
  572. t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err)
  573. }
  574. if err != ErrUserAlreadyExist {
  575. t.Fatalf("expected %v, got %v", ErrUserAlreadyExist, err)
  576. }
  577. ua = &pb.AuthUserAddRequest{Name: "", Options: &authpb.UserAddOptions{NoPassword: false}}
  578. _, err = as.UserAdd(ua) // add a user with empty name
  579. if err != ErrUserEmpty {
  580. t.Fatal(err)
  581. }
  582. as.Close()
  583. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  584. if err != nil {
  585. t.Fatal(err)
  586. }
  587. as2 := NewAuthStore(zap.NewExample(), as.be, tp, bcrypt.MinCost)
  588. defer func(a *authStore) {
  589. a.Close()
  590. }(as2)
  591. if !as2.IsAuthEnabled() {
  592. t.Fatal("recovering authStore from existing backend failed")
  593. }
  594. ul, err := as.UserList(&pb.AuthUserListRequest{})
  595. if err != nil {
  596. t.Fatal(err)
  597. }
  598. if !contains(ul.Users, "root") {
  599. t.Errorf("expected %v in %v", "root", ul.Users)
  600. }
  601. }
  602. func contains(array []string, str string) bool {
  603. for _, s := range array {
  604. if s == str {
  605. return true
  606. }
  607. }
  608. return false
  609. }
  610. func TestHammerSimpleAuthenticate(t *testing.T) {
  611. // set TTL values low to try to trigger races
  612. oldTTL, oldTTLRes := simpleTokenTTL, simpleTokenTTLResolution
  613. defer func() {
  614. simpleTokenTTL = oldTTL
  615. simpleTokenTTLResolution = oldTTLRes
  616. }()
  617. simpleTokenTTL = 10 * time.Millisecond
  618. simpleTokenTTLResolution = simpleTokenTTL
  619. users := make(map[string]struct{})
  620. as, tearDown := setupAuthStore(t)
  621. defer tearDown(t)
  622. // create lots of users
  623. for i := 0; i < 50; i++ {
  624. u := fmt.Sprintf("user-%d", i)
  625. ua := &pb.AuthUserAddRequest{Name: u, Password: "123", Options: &authpb.UserAddOptions{NoPassword: false}}
  626. if _, err := as.UserAdd(ua); err != nil {
  627. t.Fatal(err)
  628. }
  629. users[u] = struct{}{}
  630. }
  631. // hammer on authenticate with lots of users
  632. for i := 0; i < 10; i++ {
  633. var wg sync.WaitGroup
  634. wg.Add(len(users))
  635. for u := range users {
  636. go func(user string) {
  637. defer wg.Done()
  638. token := fmt.Sprintf("%s(%d)", user, i)
  639. ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, token)
  640. if _, err := as.Authenticate(ctx, user, "123"); err != nil {
  641. t.Error(err)
  642. }
  643. if _, err := as.AuthInfoFromCtx(ctx); err != nil {
  644. t.Error(err)
  645. }
  646. }(u)
  647. }
  648. time.Sleep(time.Millisecond)
  649. wg.Wait()
  650. }
  651. }
  652. // TestRolesOrder tests authpb.User.Roles is sorted
  653. func TestRolesOrder(t *testing.T) {
  654. b, tPath := backend.NewDefaultTmpBackend()
  655. defer os.Remove(tPath)
  656. tp, err := NewTokenProvider(zap.NewExample(), tokenTypeSimple, dummyIndexWaiter)
  657. if err != nil {
  658. t.Fatal(err)
  659. }
  660. as := NewAuthStore(zap.NewExample(), b, tp, bcrypt.MinCost)
  661. err = enableAuthAndCreateRoot(as)
  662. if err != nil {
  663. t.Fatal(err)
  664. }
  665. username := "user"
  666. _, err = as.UserAdd(&pb.AuthUserAddRequest{Name: username, Password: "pass", Options: &authpb.UserAddOptions{NoPassword: false}})
  667. if err != nil {
  668. t.Fatal(err)
  669. }
  670. roles := []string{"role1", "role2", "abc", "xyz", "role3"}
  671. for _, role := range roles {
  672. _, err = as.RoleAdd(&pb.AuthRoleAddRequest{Name: role})
  673. if err != nil {
  674. t.Fatal(err)
  675. }
  676. _, err = as.UserGrantRole(&pb.AuthUserGrantRoleRequest{User: username, Role: role})
  677. if err != nil {
  678. t.Fatal(err)
  679. }
  680. }
  681. user, err := as.UserGet(&pb.AuthUserGetRequest{Name: username})
  682. if err != nil {
  683. t.Fatal(err)
  684. }
  685. for i := 1; i < len(user.Roles); i++ {
  686. if strings.Compare(user.Roles[i-1], user.Roles[i]) != -1 {
  687. t.Errorf("User.Roles isn't sorted (%s vs %s)", user.Roles[i-1], user.Roles[i])
  688. }
  689. }
  690. }
  691. func TestAuthInfoFromCtxWithRootSimple(t *testing.T) {
  692. testAuthInfoFromCtxWithRoot(t, tokenTypeSimple)
  693. }
  694. func TestAuthInfoFromCtxWithRootJWT(t *testing.T) {
  695. opts := testJWTOpts()
  696. testAuthInfoFromCtxWithRoot(t, opts)
  697. }
  698. // testAuthInfoFromCtxWithRoot ensures "WithRoot" properly embeds token in the context.
  699. func testAuthInfoFromCtxWithRoot(t *testing.T, opts string) {
  700. b, tPath := backend.NewDefaultTmpBackend()
  701. defer os.Remove(tPath)
  702. tp, err := NewTokenProvider(zap.NewExample(), opts, dummyIndexWaiter)
  703. if err != nil {
  704. t.Fatal(err)
  705. }
  706. as := NewAuthStore(zap.NewExample(), b, tp, bcrypt.MinCost)
  707. defer as.Close()
  708. if err = enableAuthAndCreateRoot(as); err != nil {
  709. t.Fatal(err)
  710. }
  711. ctx := context.Background()
  712. ctx = as.WithRoot(ctx)
  713. ai, aerr := as.AuthInfoFromCtx(ctx)
  714. if aerr != nil {
  715. t.Error(err)
  716. }
  717. if ai == nil {
  718. t.Error("expected non-nil *AuthInfo")
  719. }
  720. if ai.Username != "root" {
  721. t.Errorf("expected user name 'root', got %+v", ai)
  722. }
  723. }
  724. func TestUserNoPasswordAdd(t *testing.T) {
  725. as, tearDown := setupAuthStore(t)
  726. defer tearDown(t)
  727. username := "usernopass"
  728. ua := &pb.AuthUserAddRequest{Name: username, Options: &authpb.UserAddOptions{NoPassword: true}}
  729. _, err := as.UserAdd(ua)
  730. if err != nil {
  731. t.Fatal(err)
  732. }
  733. ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  734. _, err = as.Authenticate(ctx, username, "")
  735. if err != ErrAuthFailed {
  736. t.Fatalf("expected %v, got %v", ErrAuthFailed, err)
  737. }
  738. }