v3_curl_test.go 12 KB

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