v3_auth_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Copyright 2017 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 integration
  15. import (
  16. "context"
  17. "fmt"
  18. "sync"
  19. "testing"
  20. "time"
  21. "go.etcd.io/etcd/auth/authpb"
  22. "go.etcd.io/etcd/clientv3"
  23. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  24. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  25. "go.etcd.io/etcd/pkg/testutil"
  26. )
  27. // TestV3AuthEmptyUserGet ensures that a get with an empty user will return an empty user error.
  28. func TestV3AuthEmptyUserGet(t *testing.T) {
  29. defer testutil.AfterTest(t)
  30. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  31. defer clus.Terminate(t)
  32. ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
  33. defer cancel()
  34. api := toGRPC(clus.Client(0))
  35. authSetupRoot(t, api.Auth)
  36. _, err := api.KV.Range(ctx, &pb.RangeRequest{Key: []byte("abc")})
  37. if !eqErrGRPC(err, rpctypes.ErrUserEmpty) {
  38. t.Fatalf("got %v, expected %v", err, rpctypes.ErrUserEmpty)
  39. }
  40. }
  41. // TestV3AuthTokenWithDisable tests that auth won't crash if
  42. // given a valid token when authentication is disabled
  43. func TestV3AuthTokenWithDisable(t *testing.T) {
  44. defer testutil.AfterTest(t)
  45. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  46. defer clus.Terminate(t)
  47. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  48. c, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "root", Password: "123"})
  49. if cerr != nil {
  50. t.Fatal(cerr)
  51. }
  52. defer c.Close()
  53. rctx, cancel := context.WithCancel(context.TODO())
  54. donec := make(chan struct{})
  55. go func() {
  56. defer close(donec)
  57. for rctx.Err() == nil {
  58. c.Put(rctx, "abc", "def")
  59. }
  60. }()
  61. time.Sleep(10 * time.Millisecond)
  62. if _, err := c.AuthDisable(context.TODO()); err != nil {
  63. t.Fatal(err)
  64. }
  65. time.Sleep(10 * time.Millisecond)
  66. cancel()
  67. <-donec
  68. }
  69. func TestV3AuthRevision(t *testing.T) {
  70. defer testutil.AfterTest(t)
  71. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  72. defer clus.Terminate(t)
  73. api := toGRPC(clus.Client(0))
  74. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  75. presp, perr := api.KV.Put(ctx, &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
  76. cancel()
  77. if perr != nil {
  78. t.Fatal(perr)
  79. }
  80. rev := presp.Header.Revision
  81. ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
  82. aresp, aerr := api.Auth.UserAdd(ctx, &pb.AuthUserAddRequest{Name: "root", Password: "123", Options: &authpb.UserAddOptions{NoPassword: false}})
  83. cancel()
  84. if aerr != nil {
  85. t.Fatal(aerr)
  86. }
  87. if aresp.Header.Revision != rev {
  88. t.Fatalf("revision expected %d, got %d", rev, aresp.Header.Revision)
  89. }
  90. }
  91. // TestV3AuthWithLeaseRevokeWithRoot ensures that granted leases
  92. // with root user be revoked after TTL.
  93. func TestV3AuthWithLeaseRevokeWithRoot(t *testing.T) {
  94. testV3AuthWithLeaseRevokeWithRoot(t, ClusterConfig{Size: 1})
  95. }
  96. // TestV3AuthWithLeaseRevokeWithRootJWT creates a lease with a JWT-token enabled cluster.
  97. // And tests if server is able to revoke expiry lease item.
  98. func TestV3AuthWithLeaseRevokeWithRootJWT(t *testing.T) {
  99. testV3AuthWithLeaseRevokeWithRoot(t, ClusterConfig{Size: 1, AuthToken: defaultTokenJWT})
  100. }
  101. func testV3AuthWithLeaseRevokeWithRoot(t *testing.T, ccfg ClusterConfig) {
  102. defer testutil.AfterTest(t)
  103. clus := NewClusterV3(t, &ccfg)
  104. defer clus.Terminate(t)
  105. api := toGRPC(clus.Client(0))
  106. authSetupRoot(t, api.Auth)
  107. rootc, cerr := clientv3.New(clientv3.Config{
  108. Endpoints: clus.Client(0).Endpoints(),
  109. Username: "root",
  110. Password: "123",
  111. })
  112. if cerr != nil {
  113. t.Fatal(cerr)
  114. }
  115. defer rootc.Close()
  116. leaseResp, err := rootc.Grant(context.TODO(), 2)
  117. if err != nil {
  118. t.Fatal(err)
  119. }
  120. leaseID := leaseResp.ID
  121. if _, err = rootc.Put(context.TODO(), "foo", "bar", clientv3.WithLease(leaseID)); err != nil {
  122. t.Fatal(err)
  123. }
  124. // wait for lease expire
  125. time.Sleep(3 * time.Second)
  126. tresp, terr := api.Lease.LeaseTimeToLive(
  127. context.TODO(),
  128. &pb.LeaseTimeToLiveRequest{
  129. ID: int64(leaseID),
  130. Keys: true,
  131. },
  132. )
  133. if terr != nil {
  134. t.Error(terr)
  135. }
  136. if len(tresp.Keys) > 0 || tresp.GrantedTTL != 0 {
  137. t.Errorf("lease %016x should have been revoked, got %+v", leaseID, tresp)
  138. }
  139. if tresp.TTL != -1 {
  140. t.Errorf("lease %016x should have been expired, got %+v", leaseID, tresp)
  141. }
  142. }
  143. type user struct {
  144. name string
  145. password string
  146. role string
  147. key string
  148. end string
  149. }
  150. func TestV3AuthWithLeaseRevoke(t *testing.T) {
  151. defer testutil.AfterTest(t)
  152. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  153. defer clus.Terminate(t)
  154. users := []user{
  155. {
  156. name: "user1",
  157. password: "user1-123",
  158. role: "role1",
  159. key: "k1",
  160. end: "k2",
  161. },
  162. }
  163. authSetupUsers(t, toGRPC(clus.Client(0)).Auth, users)
  164. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  165. rootc, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "root", Password: "123"})
  166. if cerr != nil {
  167. t.Fatal(cerr)
  168. }
  169. defer rootc.Close()
  170. leaseResp, err := rootc.Grant(context.TODO(), 90)
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. leaseID := leaseResp.ID
  175. // permission of k3 isn't granted to user1
  176. _, err = rootc.Put(context.TODO(), "k3", "val", clientv3.WithLease(leaseID))
  177. if err != nil {
  178. t.Fatal(err)
  179. }
  180. userc, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user1", Password: "user1-123"})
  181. if cerr != nil {
  182. t.Fatal(cerr)
  183. }
  184. defer userc.Close()
  185. _, err = userc.Revoke(context.TODO(), leaseID)
  186. if err == nil {
  187. t.Fatal("revoking from user1 should be failed with permission denied")
  188. }
  189. }
  190. func TestV3AuthWithLeaseAttach(t *testing.T) {
  191. defer testutil.AfterTest(t)
  192. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  193. defer clus.Terminate(t)
  194. users := []user{
  195. {
  196. name: "user1",
  197. password: "user1-123",
  198. role: "role1",
  199. key: "k1",
  200. end: "k3",
  201. },
  202. {
  203. name: "user2",
  204. password: "user2-123",
  205. role: "role2",
  206. key: "k2",
  207. end: "k4",
  208. },
  209. }
  210. authSetupUsers(t, toGRPC(clus.Client(0)).Auth, users)
  211. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  212. user1c, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user1", Password: "user1-123"})
  213. if cerr != nil {
  214. t.Fatal(cerr)
  215. }
  216. defer user1c.Close()
  217. user2c, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user2", Password: "user2-123"})
  218. if cerr != nil {
  219. t.Fatal(cerr)
  220. }
  221. defer user2c.Close()
  222. leaseResp, err := user1c.Grant(context.TODO(), 90)
  223. if err != nil {
  224. t.Fatal(err)
  225. }
  226. leaseID := leaseResp.ID
  227. // permission of k2 is also granted to user2
  228. _, err = user1c.Put(context.TODO(), "k2", "val", clientv3.WithLease(leaseID))
  229. if err != nil {
  230. t.Fatal(err)
  231. }
  232. _, err = user2c.Revoke(context.TODO(), leaseID)
  233. if err != nil {
  234. t.Fatal(err)
  235. }
  236. leaseResp, err = user1c.Grant(context.TODO(), 90)
  237. if err != nil {
  238. t.Fatal(err)
  239. }
  240. leaseID = leaseResp.ID
  241. // permission of k1 isn't granted to user2
  242. _, err = user1c.Put(context.TODO(), "k1", "val", clientv3.WithLease(leaseID))
  243. if err != nil {
  244. t.Fatal(err)
  245. }
  246. _, err = user2c.Revoke(context.TODO(), leaseID)
  247. if err == nil {
  248. t.Fatal("revoking from user2 should be failed with permission denied")
  249. }
  250. }
  251. func authSetupUsers(t *testing.T, auth pb.AuthClient, users []user) {
  252. for _, user := range users {
  253. if _, err := auth.UserAdd(context.TODO(), &pb.AuthUserAddRequest{Name: user.name, Password: user.password, Options: &authpb.UserAddOptions{NoPassword: false}}); err != nil {
  254. t.Fatal(err)
  255. }
  256. if _, err := auth.RoleAdd(context.TODO(), &pb.AuthRoleAddRequest{Name: user.role}); err != nil {
  257. t.Fatal(err)
  258. }
  259. if _, err := auth.UserGrantRole(context.TODO(), &pb.AuthUserGrantRoleRequest{User: user.name, Role: user.role}); err != nil {
  260. t.Fatal(err)
  261. }
  262. if len(user.key) == 0 {
  263. continue
  264. }
  265. perm := &authpb.Permission{
  266. PermType: authpb.READWRITE,
  267. Key: []byte(user.key),
  268. RangeEnd: []byte(user.end),
  269. }
  270. if _, err := auth.RoleGrantPermission(context.TODO(), &pb.AuthRoleGrantPermissionRequest{Name: user.role, Perm: perm}); err != nil {
  271. t.Fatal(err)
  272. }
  273. }
  274. }
  275. func authSetupRoot(t *testing.T, auth pb.AuthClient) {
  276. root := []user{
  277. {
  278. name: "root",
  279. password: "123",
  280. role: "root",
  281. key: "",
  282. },
  283. }
  284. authSetupUsers(t, auth, root)
  285. if _, err := auth.AuthEnable(context.TODO(), &pb.AuthEnableRequest{}); err != nil {
  286. t.Fatal(err)
  287. }
  288. }
  289. func TestV3AuthNonAuthorizedRPCs(t *testing.T) {
  290. defer testutil.AfterTest(t)
  291. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  292. defer clus.Terminate(t)
  293. nonAuthedKV := clus.Client(0).KV
  294. key := "foo"
  295. val := "bar"
  296. _, err := nonAuthedKV.Put(context.TODO(), key, val)
  297. if err != nil {
  298. t.Fatalf("couldn't put key (%v)", err)
  299. }
  300. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  301. respput, err := nonAuthedKV.Put(context.TODO(), key, val)
  302. if !eqErrGRPC(err, rpctypes.ErrGRPCUserEmpty) {
  303. t.Fatalf("could put key (%v), it should cause an error of permission denied", respput)
  304. }
  305. }
  306. func TestV3AuthOldRevConcurrent(t *testing.T) {
  307. defer testutil.AfterTest(t)
  308. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  309. defer clus.Terminate(t)
  310. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  311. c, cerr := clientv3.New(clientv3.Config{
  312. Endpoints: clus.Client(0).Endpoints(),
  313. DialTimeout: 5 * time.Second,
  314. Username: "root",
  315. Password: "123",
  316. })
  317. testutil.AssertNil(t, cerr)
  318. defer c.Close()
  319. var wg sync.WaitGroup
  320. f := func(i int) {
  321. defer wg.Done()
  322. role, user := fmt.Sprintf("test-role-%d", i), fmt.Sprintf("test-user-%d", i)
  323. _, err := c.RoleAdd(context.TODO(), role)
  324. testutil.AssertNil(t, err)
  325. _, err = c.RoleGrantPermission(context.TODO(), role, "", clientv3.GetPrefixRangeEnd(""), clientv3.PermissionType(clientv3.PermReadWrite))
  326. testutil.AssertNil(t, err)
  327. _, err = c.UserAdd(context.TODO(), user, "123")
  328. testutil.AssertNil(t, err)
  329. _, err = c.Put(context.TODO(), "a", "b")
  330. testutil.AssertNil(t, err)
  331. }
  332. // needs concurrency to trigger
  333. numRoles := 2
  334. wg.Add(numRoles)
  335. for i := 0; i < numRoles; i++ {
  336. go f(i)
  337. }
  338. wg.Wait()
  339. }