v3_curl_test.go 13 KB

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