v3_auth_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "github.com/coreos/etcd/auth/authpb"
  22. "github.com/coreos/etcd/clientv3"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  24. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  25. "github.com/coreos/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"})
  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. defer testutil.AfterTest(t)
  95. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  96. defer clus.Terminate(t)
  97. api := toGRPC(clus.Client(0))
  98. authSetupRoot(t, api.Auth)
  99. rootc, cerr := clientv3.New(clientv3.Config{
  100. Endpoints: clus.Client(0).Endpoints(),
  101. Username: "root",
  102. Password: "123",
  103. })
  104. if cerr != nil {
  105. t.Fatal(cerr)
  106. }
  107. defer rootc.Close()
  108. leaseResp, err := rootc.Grant(context.TODO(), 2)
  109. if err != nil {
  110. t.Fatal(err)
  111. }
  112. leaseID := leaseResp.ID
  113. if _, err = rootc.Put(context.TODO(), "foo", "bar", clientv3.WithLease(leaseID)); err != nil {
  114. t.Fatal(err)
  115. }
  116. // wait for lease expire
  117. time.Sleep(3 * time.Second)
  118. tresp, terr := api.Lease.LeaseTimeToLive(
  119. context.TODO(),
  120. &pb.LeaseTimeToLiveRequest{
  121. ID: int64(leaseID),
  122. Keys: true,
  123. },
  124. )
  125. if terr != nil {
  126. t.Error(terr)
  127. }
  128. if len(tresp.Keys) > 0 || tresp.GrantedTTL != 0 {
  129. t.Errorf("lease %016x should have been revoked, got %+v", leaseID, tresp)
  130. }
  131. if tresp.TTL != -1 {
  132. t.Errorf("lease %016x should have been expired, got %+v", leaseID, tresp)
  133. }
  134. }
  135. type user struct {
  136. name string
  137. password string
  138. role string
  139. key string
  140. end string
  141. }
  142. func TestV3AuthWithLeaseRevoke(t *testing.T) {
  143. defer testutil.AfterTest(t)
  144. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  145. defer clus.Terminate(t)
  146. users := []user{
  147. {
  148. name: "user1",
  149. password: "user1-123",
  150. role: "role1",
  151. key: "k1",
  152. end: "k2",
  153. },
  154. }
  155. authSetupUsers(t, toGRPC(clus.Client(0)).Auth, users)
  156. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  157. rootc, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "root", Password: "123"})
  158. if cerr != nil {
  159. t.Fatal(cerr)
  160. }
  161. defer rootc.Close()
  162. leaseResp, err := rootc.Grant(context.TODO(), 90)
  163. if err != nil {
  164. t.Fatal(err)
  165. }
  166. leaseID := leaseResp.ID
  167. // permission of k3 isn't granted to user1
  168. _, err = rootc.Put(context.TODO(), "k3", "val", clientv3.WithLease(leaseID))
  169. if err != nil {
  170. t.Fatal(err)
  171. }
  172. userc, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user1", Password: "user1-123"})
  173. if cerr != nil {
  174. t.Fatal(cerr)
  175. }
  176. defer userc.Close()
  177. _, err = userc.Revoke(context.TODO(), leaseID)
  178. if err == nil {
  179. t.Fatal("revoking from user1 should be failed with permission denied")
  180. }
  181. }
  182. func TestV3AuthWithLeaseAttach(t *testing.T) {
  183. defer testutil.AfterTest(t)
  184. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  185. defer clus.Terminate(t)
  186. users := []user{
  187. {
  188. name: "user1",
  189. password: "user1-123",
  190. role: "role1",
  191. key: "k1",
  192. end: "k3",
  193. },
  194. {
  195. name: "user2",
  196. password: "user2-123",
  197. role: "role2",
  198. key: "k2",
  199. end: "k4",
  200. },
  201. }
  202. authSetupUsers(t, toGRPC(clus.Client(0)).Auth, users)
  203. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  204. user1c, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user1", Password: "user1-123"})
  205. if cerr != nil {
  206. t.Fatal(cerr)
  207. }
  208. defer user1c.Close()
  209. user2c, cerr := clientv3.New(clientv3.Config{Endpoints: clus.Client(0).Endpoints(), Username: "user2", Password: "user2-123"})
  210. if cerr != nil {
  211. t.Fatal(cerr)
  212. }
  213. defer user2c.Close()
  214. leaseResp, err := user1c.Grant(context.TODO(), 90)
  215. if err != nil {
  216. t.Fatal(err)
  217. }
  218. leaseID := leaseResp.ID
  219. // permission of k2 is also granted to user2
  220. _, err = user1c.Put(context.TODO(), "k2", "val", clientv3.WithLease(leaseID))
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. _, err = user2c.Revoke(context.TODO(), leaseID)
  225. if err != nil {
  226. t.Fatal(err)
  227. }
  228. leaseResp, err = user1c.Grant(context.TODO(), 90)
  229. if err != nil {
  230. t.Fatal(err)
  231. }
  232. leaseID = leaseResp.ID
  233. // permission of k1 isn't granted to user2
  234. _, err = user1c.Put(context.TODO(), "k1", "val", clientv3.WithLease(leaseID))
  235. if err != nil {
  236. t.Fatal(err)
  237. }
  238. _, err = user2c.Revoke(context.TODO(), leaseID)
  239. if err == nil {
  240. t.Fatal("revoking from user2 should be failed with permission denied")
  241. }
  242. }
  243. func authSetupUsers(t *testing.T, auth pb.AuthClient, users []user) {
  244. for _, user := range users {
  245. if _, err := auth.UserAdd(context.TODO(), &pb.AuthUserAddRequest{Name: user.name, Password: user.password}); err != nil {
  246. t.Fatal(err)
  247. }
  248. if _, err := auth.RoleAdd(context.TODO(), &pb.AuthRoleAddRequest{Name: user.role}); err != nil {
  249. t.Fatal(err)
  250. }
  251. if _, err := auth.UserGrantRole(context.TODO(), &pb.AuthUserGrantRoleRequest{User: user.name, Role: user.role}); err != nil {
  252. t.Fatal(err)
  253. }
  254. if len(user.key) == 0 {
  255. continue
  256. }
  257. perm := &authpb.Permission{
  258. PermType: authpb.READWRITE,
  259. Key: []byte(user.key),
  260. RangeEnd: []byte(user.end),
  261. }
  262. if _, err := auth.RoleGrantPermission(context.TODO(), &pb.AuthRoleGrantPermissionRequest{Name: user.role, Perm: perm}); err != nil {
  263. t.Fatal(err)
  264. }
  265. }
  266. }
  267. func authSetupRoot(t *testing.T, auth pb.AuthClient) {
  268. root := []user{
  269. {
  270. name: "root",
  271. password: "123",
  272. role: "root",
  273. key: "",
  274. },
  275. }
  276. authSetupUsers(t, auth, root)
  277. if _, err := auth.AuthEnable(context.TODO(), &pb.AuthEnableRequest{}); err != nil {
  278. t.Fatal(err)
  279. }
  280. }
  281. func TestV3AuthNonAuthorizedRPCs(t *testing.T) {
  282. defer testutil.AfterTest(t)
  283. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  284. defer clus.Terminate(t)
  285. nonAuthedKV := clus.Client(0).KV
  286. key := "foo"
  287. val := "bar"
  288. _, err := nonAuthedKV.Put(context.TODO(), key, val)
  289. if err != nil {
  290. t.Fatalf("couldn't put key (%v)", err)
  291. }
  292. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  293. respput, err := nonAuthedKV.Put(context.TODO(), key, val)
  294. if !eqErrGRPC(err, rpctypes.ErrGRPCUserEmpty) {
  295. t.Fatalf("could put key (%v), it should cause an error of permission denied", respput)
  296. }
  297. }
  298. func TestV3AuthOldRevConcurrent(t *testing.T) {
  299. defer testutil.AfterTest(t)
  300. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  301. defer clus.Terminate(t)
  302. authSetupRoot(t, toGRPC(clus.Client(0)).Auth)
  303. c, cerr := clientv3.New(clientv3.Config{
  304. Endpoints: clus.Client(0).Endpoints(),
  305. DialTimeout: 5 * time.Second,
  306. Username: "root",
  307. Password: "123",
  308. })
  309. testutil.AssertNil(t, cerr)
  310. defer c.Close()
  311. var wg sync.WaitGroup
  312. f := func(i int) {
  313. defer wg.Done()
  314. role, user := fmt.Sprintf("test-role-%d", i), fmt.Sprintf("test-user-%d", i)
  315. _, err := c.RoleAdd(context.TODO(), role)
  316. testutil.AssertNil(t, err)
  317. _, err = c.RoleGrantPermission(context.TODO(), role, "", clientv3.GetPrefixRangeEnd(""), clientv3.PermissionType(clientv3.PermReadWrite))
  318. testutil.AssertNil(t, err)
  319. _, err = c.UserAdd(context.TODO(), user, "123")
  320. testutil.AssertNil(t, err)
  321. _, err = c.Put(context.TODO(), "a", "b")
  322. testutil.AssertNil(t, err)
  323. }
  324. // needs concurrency to trigger
  325. numRoles := 2
  326. wg.Add(numRoles)
  327. for i := 0; i < numRoles; i++ {
  328. go f(i)
  329. }
  330. wg.Wait()
  331. }