github.com/dbernstein1/tyk@v2.9.0-beta9-dl-apic+incompatible/gateway/batch_requests_test.go (about)

     1  package gateway
     2  
     3  import (
     4  	"crypto/tls"
     5  	"crypto/x509"
     6  	"encoding/base64"
     7  	"encoding/json"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"net/http/httptest"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/TykTechnologies/tyk/apidef"
    15  	"github.com/TykTechnologies/tyk/config"
    16  	"github.com/TykTechnologies/tyk/test"
    17  )
    18  
    19  const testBatchRequest = `{
    20  	"requests": [
    21  	{
    22  		"method": "GET",
    23  		"headers": {
    24  			"test-header-1": "test-1",
    25  			"test-header-2": "test-2"
    26  		},
    27  		"relative_url": "get/?param1=this"
    28  	},
    29  	{
    30  		"method": "POST",
    31  		"body": "TEST BODY",
    32  		"relative_url": "post/"
    33  	},
    34  	{
    35  		"method": "PUT",
    36  		"relative_url": "put/"
    37  	}
    38  	],
    39  	"suppress_parallel_execution": true
    40  }`
    41  
    42  func TestBatch(t *testing.T) {
    43  	ts := StartTest()
    44  	defer ts.Close()
    45  
    46  	BuildAndLoadAPI(func(spec *APISpec) {
    47  		spec.Proxy.ListenPath = "/v1/"
    48  		spec.EnableBatchRequestSupport = true
    49  	})
    50  
    51  	ts.Run(t, []test.TestCase{
    52  		{Method: "POST", Path: "/v1/tyk/batch/", Data: `{"requests":[]}`, Code: 200, BodyMatch: "[]"},
    53  		{Method: "POST", Path: "/v1/tyk/batch/", Data: "malformed", Code: 400},
    54  		{Method: "POST", Path: "/v1/tyk/batch/", Data: testBatchRequest, Code: 200},
    55  	}...)
    56  
    57  	resp, _ := ts.Do(test.TestCase{Method: "POST", Path: "/v1/tyk/batch/", Data: testBatchRequest})
    58  	if resp != nil {
    59  		body, _ := ioutil.ReadAll(resp.Body)
    60  		defer resp.Body.Close()
    61  
    62  		var batchResponse []map[string]json.RawMessage
    63  		if err := json.Unmarshal(body, &batchResponse); err != nil {
    64  			t.Fatal(err)
    65  		}
    66  
    67  		if len(batchResponse) != 3 {
    68  			t.Errorf("Length not match: %d", len(batchResponse))
    69  		}
    70  
    71  		if string(batchResponse[0]["relative_url"]) != `"get/?param1=this"` {
    72  			t.Error("Url order not match:", string(batchResponse[0]["relative_url"]))
    73  		}
    74  	}
    75  }
    76  
    77  var virtBatchTest = `function batchTest (request, session, config) {
    78  	// Set up a response object
    79  	var response = {
    80  		Body: "",
    81  		Headers: {
    82  			"content-type": "application/json"
    83  		},
    84  		Code: 202
    85  	}
    86  
    87  	// Batch request
    88  	var batch = {
    89  		"requests": [
    90  			{
    91  				"method": "GET",
    92  				"headers": {},
    93  				"body": "",
    94  				"relative_url": "{upstream_URL}"
    95  			},
    96  			{
    97  				"method": "GET",
    98  				"headers": {},
    99  				"body": "",
   100  				"relative_url": "{upstream_URL}"
   101  			}
   102  		],
   103  		"suppress_parallel_execution": false
   104  	}
   105  
   106  	var newBody = TykBatchRequest(JSON.stringify(batch))
   107  	var asJS = JSON.parse(newBody)
   108  	for (var i in asJS) {
   109  		if (asJS[i].code == 0){
   110  			response.Code = 500
   111  		}
   112  	}
   113  	return TykJsResponse(response, session.meta_data)
   114  }`
   115  
   116  func TestVirtualEndpointBatch(t *testing.T) {
   117  	_, _, combinedClientPEM, clientCert := genCertificate(&x509.Certificate{})
   118  	clientCert.Leaf, _ = x509.ParseCertificate(clientCert.Certificate[0])
   119  
   120  	upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
   121  	}))
   122  
   123  	// Mutual TLS protected upstream
   124  	pool := x509.NewCertPool()
   125  	pool.AddCert(clientCert.Leaf)
   126  	upstream.TLS = &tls.Config{
   127  		ClientAuth:         tls.RequireAndVerifyClientCert,
   128  		ClientCAs:          pool,
   129  		InsecureSkipVerify: true,
   130  	}
   131  
   132  	upstream.StartTLS()
   133  	defer upstream.Close()
   134  
   135  	clientCertID, _ := CertificateManager.Add(combinedClientPEM, "")
   136  	defer CertificateManager.Delete(clientCertID)
   137  
   138  	virtBatchTest = strings.Replace(virtBatchTest, "{upstream_URL}", upstream.URL, 2)
   139  	defer upstream.Close()
   140  
   141  	upstreamHost := strings.TrimPrefix(upstream.URL, "https://")
   142  
   143  	globalConf := config.Global()
   144  	globalConf.Security.Certificates.Upstream = map[string]string{upstreamHost: clientCertID}
   145  	config.SetGlobal(globalConf)
   146  
   147  	defer ResetTestConfig()
   148  
   149  	ts := StartTest()
   150  	defer ts.Close()
   151  
   152  	BuildAndLoadAPI(func(spec *APISpec) {
   153  		spec.Proxy.ListenPath = "/"
   154  		virtualMeta := apidef.VirtualMeta{
   155  			ResponseFunctionName: "batchTest",
   156  			FunctionSourceType:   "blob",
   157  			FunctionSourceURI:    base64.StdEncoding.EncodeToString([]byte(virtBatchTest)),
   158  			Path:                 "/virt",
   159  			Method:               "GET",
   160  		}
   161  		UpdateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
   162  			v.UseExtendedPaths = true
   163  			v.ExtendedPaths = apidef.ExtendedPathsSet{
   164  				Virtual: []apidef.VirtualMeta{virtualMeta},
   165  			}
   166  		})
   167  	})
   168  
   169  	t.Run("Skip verification", func(t *testing.T) {
   170  		globalConf := config.Global()
   171  		globalConf.ProxySSLInsecureSkipVerify = true
   172  		config.SetGlobal(globalConf)
   173  
   174  		ts.Run(t, test.TestCase{Path: "/virt", Code: 202})
   175  	})
   176  
   177  	t.Run("Verification required", func(t *testing.T) {
   178  		globalConf := config.Global()
   179  		globalConf.ProxySSLInsecureSkipVerify = false
   180  		config.SetGlobal(globalConf)
   181  
   182  		ts.Run(t, test.TestCase{Path: "/virt", Code: 500})
   183  	})
   184  
   185  }