v3_curl_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 e2e
  15. import (
  16. "encoding/base64"
  17. "encoding/json"
  18. "fmt"
  19. "path"
  20. "strconv"
  21. "testing"
  22. epb "go.etcd.io/etcd/etcdserver/api/v3election/v3electionpb"
  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. "github.com/grpc-ecosystem/grpc-gateway/runtime"
  27. )
  28. // TODO: remove /v3beta tests in 3.5 release
  29. var apiPrefix = []string{"/v3", "/v3beta"}
  30. func TestV3CurlPutGetNoTLS(t *testing.T) {
  31. for _, p := range apiPrefix {
  32. testCtl(t, testV3CurlPutGet, withApiPrefix(p), withCfg(configNoTLS))
  33. }
  34. }
  35. func TestV3CurlPutGetAutoTLS(t *testing.T) {
  36. for _, p := range apiPrefix {
  37. testCtl(t, testV3CurlPutGet, withApiPrefix(p), withCfg(configAutoTLS))
  38. }
  39. }
  40. func TestV3CurlPutGetAllTLS(t *testing.T) {
  41. for _, p := range apiPrefix {
  42. testCtl(t, testV3CurlPutGet, withApiPrefix(p), withCfg(configTLS))
  43. }
  44. }
  45. func TestV3CurlPutGetPeerTLS(t *testing.T) {
  46. for _, p := range apiPrefix {
  47. testCtl(t, testV3CurlPutGet, withApiPrefix(p), withCfg(configPeerTLS))
  48. }
  49. }
  50. func TestV3CurlPutGetClientTLS(t *testing.T) {
  51. for _, p := range apiPrefix {
  52. testCtl(t, testV3CurlPutGet, withApiPrefix(p), withCfg(configClientTLS))
  53. }
  54. }
  55. func TestV3CurlWatch(t *testing.T) {
  56. for _, p := range apiPrefix {
  57. testCtl(t, testV3CurlWatch, withApiPrefix(p))
  58. }
  59. }
  60. func TestV3CurlTxn(t *testing.T) {
  61. for _, p := range apiPrefix {
  62. testCtl(t, testV3CurlTxn, withApiPrefix(p))
  63. }
  64. }
  65. func TestV3CurlAuth(t *testing.T) {
  66. for _, p := range apiPrefix {
  67. testCtl(t, testV3CurlAuth, withApiPrefix(p))
  68. }
  69. }
  70. func TestV3CurlAuthClientTLSCertAuth(t *testing.T) {
  71. for _, p := range apiPrefix {
  72. testCtl(t, testV3CurlAuth, withApiPrefix(p), withCfg(configClientTLSCertAuthWithNoCN))
  73. }
  74. }
  75. func testV3CurlPutGet(cx ctlCtx) {
  76. var (
  77. key = []byte("foo")
  78. value = []byte("bar") // this will be automatically base64-encoded by Go
  79. expectPut = `"revision":"`
  80. expectGet = `"value":"`
  81. )
  82. putData, err := json.Marshal(&pb.PutRequest{
  83. Key: key,
  84. Value: value,
  85. })
  86. if err != nil {
  87. cx.t.Fatal(err)
  88. }
  89. rangeData, err := json.Marshal(&pb.RangeRequest{
  90. Key: key,
  91. })
  92. if err != nil {
  93. cx.t.Fatal(err)
  94. }
  95. p := cx.apiPrefix
  96. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/put"), value: string(putData), expected: expectPut}); err != nil {
  97. cx.t.Fatalf("failed testV3CurlPutGet put with curl using prefix (%s) (%v)", p, err)
  98. }
  99. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/range"), value: string(rangeData), expected: expectGet}); err != nil {
  100. cx.t.Fatalf("failed testV3CurlPutGet get with curl using prefix (%s) (%v)", p, err)
  101. }
  102. if cx.cfg.clientTLS == clientTLSAndNonTLS {
  103. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/range"), value: string(rangeData), expected: expectGet, isTLS: true}); err != nil {
  104. cx.t.Fatalf("failed testV3CurlPutGet get with curl using prefix (%s) (%v)", p, err)
  105. }
  106. }
  107. }
  108. func testV3CurlWatch(cx ctlCtx) {
  109. // store "bar" into "foo"
  110. putreq, err := json.Marshal(&pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
  111. if err != nil {
  112. cx.t.Fatal(err)
  113. }
  114. // watch for first update to "foo"
  115. wcr := &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}
  116. wreq, err := json.Marshal(wcr)
  117. if err != nil {
  118. cx.t.Fatal(err)
  119. }
  120. // marshaling the grpc to json gives:
  121. // "{"RequestUnion":{"CreateRequest":{"key":"Zm9v","start_revision":1}}}"
  122. // but the gprc-gateway expects a different format..
  123. wstr := `{"create_request" : ` + string(wreq) + "}"
  124. p := cx.apiPrefix
  125. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/put"), value: string(putreq), expected: "revision"}); err != nil {
  126. cx.t.Fatalf("failed testV3CurlWatch put with curl using prefix (%s) (%v)", p, err)
  127. }
  128. // expects "bar", timeout after 2 seconds since stream waits forever
  129. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/watch"), value: wstr, expected: `"YmFy"`, timeout: 2}); err != nil {
  130. cx.t.Fatalf("failed testV3CurlWatch watch with curl using prefix (%s) (%v)", p, err)
  131. }
  132. }
  133. func testV3CurlTxn(cx ctlCtx) {
  134. txn := &pb.TxnRequest{
  135. Compare: []*pb.Compare{
  136. {
  137. Key: []byte("foo"),
  138. Result: pb.Compare_EQUAL,
  139. Target: pb.Compare_CREATE,
  140. TargetUnion: &pb.Compare_CreateRevision{CreateRevision: 0},
  141. },
  142. },
  143. Success: []*pb.RequestOp{
  144. {
  145. Request: &pb.RequestOp_RequestPut{
  146. RequestPut: &pb.PutRequest{
  147. Key: []byte("foo"),
  148. Value: []byte("bar"),
  149. },
  150. },
  151. },
  152. },
  153. }
  154. m := &runtime.JSONPb{}
  155. jsonDat, jerr := m.Marshal(txn)
  156. if jerr != nil {
  157. cx.t.Fatal(jerr)
  158. }
  159. expected := `"succeeded":true,"responses":[{"response_put":{"header":{"revision":"2"}}}]`
  160. p := cx.apiPrefix
  161. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/txn"), value: string(jsonDat), expected: expected}); err != nil {
  162. cx.t.Fatalf("failed testV3CurlTxn txn with curl using prefix (%s) (%v)", p, err)
  163. }
  164. // was crashing etcd server
  165. malformed := `{"compare":[{"result":0,"target":1,"key":"Zm9v","TargetUnion":null}],"success":[{"Request":{"RequestPut":{"key":"Zm9v","value":"YmFy"}}}]}`
  166. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/txn"), value: malformed, expected: "error"}); err != nil {
  167. cx.t.Fatalf("failed testV3CurlTxn put with curl using prefix (%s) (%v)", p, err)
  168. }
  169. }
  170. func testV3CurlAuth(cx ctlCtx) {
  171. p := cx.apiPrefix
  172. // create root user
  173. rootuser, err := json.Marshal(&pb.AuthUserAddRequest{Name: string("root"), Password: string("toor")})
  174. testutil.AssertNil(cx.t, err)
  175. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/user/add"), value: string(rootuser), expected: "revision"}); err != nil {
  176. cx.t.Fatalf("failed testV3CurlAuth add user with curl (%v)", err)
  177. }
  178. // create non root user
  179. nonrootuser, err := json.Marshal(&pb.AuthUserAddRequest{Name: string("example.com"), Password: string("example")})
  180. testutil.AssertNil(cx.t, err)
  181. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/user/add"), value: string(nonrootuser), expected: "revision"}); err != nil {
  182. cx.t.Fatalf("failed testV3CurlAuth add user with curl (%v)", err)
  183. }
  184. // create root role
  185. rolereq, err := json.Marshal(&pb.AuthRoleAddRequest{Name: string("root")})
  186. testutil.AssertNil(cx.t, err)
  187. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/role/add"), value: string(rolereq), expected: "revision"}); err != nil {
  188. cx.t.Fatalf("failed testV3CurlAuth create role with curl using prefix (%s) (%v)", p, err)
  189. }
  190. // grant root role
  191. grantroleroot, err := json.Marshal(&pb.AuthUserGrantRoleRequest{User: string("root"), Role: string("root")})
  192. testutil.AssertNil(cx.t, err)
  193. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/user/grant"), value: string(grantroleroot), expected: "revision"}); err != nil {
  194. cx.t.Fatalf("failed testV3CurlAuth grant role with curl using prefix (%s) (%v)", p, err)
  195. }
  196. // grant non root user root role
  197. grantrole, err := json.Marshal(&pb.AuthUserGrantRoleRequest{User: string("example.com"), Role: string("root")})
  198. testutil.AssertNil(cx.t, err)
  199. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/user/grant"), value: string(grantrole), expected: "revision"}); err != nil {
  200. cx.t.Fatalf("failed testV3CurlAuth grant role with curl using prefix (%s) (%v)", p, err)
  201. }
  202. // enable auth
  203. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/auth/enable"), value: string("{}"), expected: "revision"}); err != nil {
  204. cx.t.Fatalf("failed testV3CurlAuth enable auth with curl using prefix (%s) (%v)", p, err)
  205. }
  206. // put "bar" into "foo"
  207. putreq, err := json.Marshal(&pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
  208. testutil.AssertNil(cx.t, err)
  209. // fail put no auth
  210. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/put"), value: string(putreq), expected: "error"}); err != nil {
  211. cx.t.Fatalf("failed testV3CurlAuth no auth put with curl using prefix (%s) (%v)", p, err)
  212. }
  213. // auth request
  214. authreq, err := json.Marshal(&pb.AuthenticateRequest{Name: string("root"), Password: string("toor")})
  215. testutil.AssertNil(cx.t, err)
  216. var (
  217. authHeader string
  218. cmdArgs []string
  219. lineFunc = func(txt string) bool { return true }
  220. )
  221. cmdArgs = cURLPrefixArgs(cx.epc, "POST", cURLReq{endpoint: path.Join(p, "/auth/authenticate"), value: string(authreq)})
  222. proc, err := spawnCmd(cmdArgs)
  223. testutil.AssertNil(cx.t, err)
  224. cURLRes, err := proc.ExpectFunc(lineFunc)
  225. testutil.AssertNil(cx.t, err)
  226. authRes := make(map[string]interface{})
  227. testutil.AssertNil(cx.t, json.Unmarshal([]byte(cURLRes), &authRes))
  228. token, ok := authRes[rpctypes.TokenFieldNameGRPC].(string)
  229. if !ok {
  230. cx.t.Fatalf("failed invalid token in authenticate response with curl")
  231. }
  232. authHeader = "Authorization: " + token
  233. // put with auth
  234. if err = cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, "/kv/put"), value: string(putreq), header: authHeader, expected: "revision"}); err != nil {
  235. cx.t.Fatalf("failed testV3CurlAuth auth put with curl using prefix (%s) (%v)", p, err)
  236. }
  237. }
  238. func TestV3CurlCampaignNoTLS(t *testing.T) {
  239. for _, p := range apiPrefix {
  240. testCtl(t, testV3CurlCampaign, withApiPrefix(p), withCfg(configNoTLS))
  241. }
  242. }
  243. func testV3CurlCampaign(cx ctlCtx) {
  244. cdata, err := json.Marshal(&epb.CampaignRequest{
  245. Name: []byte("/election-prefix"),
  246. Value: []byte("v1"),
  247. })
  248. if err != nil {
  249. cx.t.Fatal(err)
  250. }
  251. cargs := cURLPrefixArgs(cx.epc, "POST", cURLReq{
  252. endpoint: path.Join(cx.apiPrefix, "/election/campaign"),
  253. value: string(cdata),
  254. })
  255. lines, err := spawnWithExpectLines(cargs, `"leader":{"name":"`)
  256. if err != nil {
  257. cx.t.Fatalf("failed post campaign request (%s) (%v)", cx.apiPrefix, err)
  258. }
  259. if len(lines) != 1 {
  260. cx.t.Fatalf("len(lines) expected 1, got %+v", lines)
  261. }
  262. var cresp campaignResponse
  263. if err = json.Unmarshal([]byte(lines[0]), &cresp); err != nil {
  264. cx.t.Fatalf("failed to unmarshal campaign response %v", err)
  265. }
  266. ndata, err := base64.StdEncoding.DecodeString(cresp.Leader.Name)
  267. if err != nil {
  268. cx.t.Fatalf("failed to decode leader key %v", err)
  269. }
  270. kdata, err := base64.StdEncoding.DecodeString(cresp.Leader.Key)
  271. if err != nil {
  272. cx.t.Fatalf("failed to decode leader key %v", err)
  273. }
  274. rev, _ := strconv.ParseInt(cresp.Leader.Rev, 10, 64)
  275. lease, _ := strconv.ParseInt(cresp.Leader.Lease, 10, 64)
  276. pdata, err := json.Marshal(&epb.ProclaimRequest{
  277. Leader: &epb.LeaderKey{
  278. Name: ndata,
  279. Key: kdata,
  280. Rev: rev,
  281. Lease: lease,
  282. },
  283. Value: []byte("v2"),
  284. })
  285. if err != nil {
  286. cx.t.Fatal(err)
  287. }
  288. if err = cURLPost(cx.epc, cURLReq{
  289. endpoint: path.Join(cx.apiPrefix, "/election/proclaim"),
  290. value: string(pdata),
  291. expected: `"revision":`,
  292. }); err != nil {
  293. cx.t.Fatalf("failed post proclaim request (%s) (%v)", cx.apiPrefix, err)
  294. }
  295. }
  296. func TestV3CurlProclaimMissiongLeaderKeyNoTLS(t *testing.T) {
  297. for _, p := range apiPrefix {
  298. testCtl(t, testV3CurlProclaimMissiongLeaderKey, withApiPrefix(p), withCfg(configNoTLS))
  299. }
  300. }
  301. func testV3CurlProclaimMissiongLeaderKey(cx ctlCtx) {
  302. pdata, err := json.Marshal(&epb.ProclaimRequest{Value: []byte("v2")})
  303. if err != nil {
  304. cx.t.Fatal(err)
  305. }
  306. if err = cURLPost(cx.epc, cURLReq{
  307. endpoint: path.Join(cx.apiPrefix, "/election/proclaim"),
  308. value: string(pdata),
  309. expected: `{"error":"\"leader\" field must be provided","code":2}`,
  310. }); err != nil {
  311. cx.t.Fatalf("failed post proclaim request (%s) (%v)", cx.apiPrefix, err)
  312. }
  313. }
  314. func TestV3CurlResignMissiongLeaderKeyNoTLS(t *testing.T) {
  315. for _, p := range apiPrefix {
  316. testCtl(t, testV3CurlResignMissiongLeaderKey, withApiPrefix(p), withCfg(configNoTLS))
  317. }
  318. }
  319. func testV3CurlResignMissiongLeaderKey(cx ctlCtx) {
  320. if err := cURLPost(cx.epc, cURLReq{
  321. endpoint: path.Join(cx.apiPrefix, "/election/resign"),
  322. value: `{}`,
  323. expected: `{"error":"\"leader\" field must be provided","code":2}`,
  324. }); err != nil {
  325. cx.t.Fatalf("failed post resign request (%s) (%v)", cx.apiPrefix, err)
  326. }
  327. }
  328. // to manually decode; JSON marshals integer fields with
  329. // string types, so can't unmarshal with epb.CampaignResponse
  330. type campaignResponse struct {
  331. Leader struct {
  332. Name string `json:"name,omitempty"`
  333. Key string `json:"key,omitempty"`
  334. Rev string `json:"rev,omitempty"`
  335. Lease string `json:"lease,omitempty"`
  336. } `json:"leader,omitempty"`
  337. }
  338. func cURLWithExpected(cx ctlCtx, tests []v3cURLTest) error {
  339. p := cx.apiPrefix
  340. for _, t := range tests {
  341. value := fmt.Sprintf("%v", t.value)
  342. if err := cURLPost(cx.epc, cURLReq{endpoint: path.Join(p, t.endpoint), value: value, expected: t.expected}); err != nil {
  343. return fmt.Errorf("prefix (%s) endpoint (%s): error (%v), wanted %v", p, t.endpoint, err, t.expected)
  344. }
  345. }
  346. return nil
  347. }