You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shenyu.apache.org by xi...@apache.org on 2022/02/01 15:04:23 UTC
[incubator-shenyu] branch master updated: feature(Integrated-Test): add combination integrated test for Request Plugins (#2821)
This is an automated email from the ASF dual-hosted git repository.
xiaoyu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-shenyu.git
The following commit(s) were added to refs/heads/master by this push:
new 4f9fa94 feature(Integrated-Test): add combination integrated test for Request Plugins (#2821)
4f9fa94 is described below
commit 4f9fa94ac71c4572f0b274315a0e43f48f978ab0
Author: luoxiaolong <28...@qq.com>
AuthorDate: Tue Feb 1 23:04:06 2022 +0800
feature(Integrated-Test): add combination integrated test for Request Plugins (#2821)
---
.../http/controller/HttpTestController.java | 22 +-
.../docker-compose.yml | 2 +
.../shenyu-integrated-test-combination/pom.xml | 34 +-
.../src/main/resources/application-local.yml | 2 +-
.../test/combination/MultiRequestPluginTest.java | 523 +++++++++++++++++++--
.../common/dto/ModifyResponseDTO.java | 111 +++++
.../integratedtest/common/helper/HttpHelper.java | 104 ++--
7 files changed, 720 insertions(+), 78 deletions(-)
diff --git a/shenyu-examples/shenyu-examples-http/src/main/java/org/apache/shenyu/examples/http/controller/HttpTestController.java b/shenyu-examples/shenyu-examples-http/src/main/java/org/apache/shenyu/examples/http/controller/HttpTestController.java
index 181bcda..e64de76 100644
--- a/shenyu-examples/shenyu-examples-http/src/main/java/org/apache/shenyu/examples/http/controller/HttpTestController.java
+++ b/shenyu-examples/shenyu-examples-http/src/main/java/org/apache/shenyu/examples/http/controller/HttpTestController.java
@@ -82,8 +82,8 @@ public class HttpTestController {
/**
* Find by page user dto.
*
- * @param keyword the keyword
- * @param page the page
+ * @param keyword the keyword
+ * @param page the page
* @param pageSize the page size
* @return the user dto
*/
@@ -95,7 +95,7 @@ public class HttpTestController {
/**
* Gets path variable.
*
- * @param id the id
+ * @param id the id
* @param name the name
* @return the path variable
*/
@@ -120,7 +120,7 @@ public class HttpTestController {
/**
* Put path variable and body string.
*
- * @param id the id
+ * @param id the id
* @param userDTO the user dto
* @return the string
*/
@@ -240,6 +240,20 @@ public class HttpTestController {
return Mono.just(GsonUtils.getInstance().toJson(body));
}
+
+ @PostMapping(path = "/modifyRequest")
+ public Map<String, Object> modifyRequest(@RequestBody final UserDTO userDTO,
+ @CookieValue(value = "cookie", defaultValue = "") final String cookie,
+ @RequestHeader(value = "requestHeader", defaultValue = "") final String requestHeader,
+ @RequestParam(value = "requestParameter", defaultValue = "") final String requestParameter) {
+ Map<String, Object> result = new HashMap<>();
+ result.put("body", userDTO);
+ result.put("cookie", cookie);
+ result.put("header", requestHeader);
+ result.put("parameter", requestParameter);
+ return result;
+ }
+
private UserDTO buildUser(final String id, final String name) {
UserDTO userDTO = new UserDTO();
userDTO.setUserId(id);
diff --git a/shenyu-integrated-test/shenyu-integrated-test-combination/docker-compose.yml b/shenyu-integrated-test/shenyu-integrated-test-combination/docker-compose.yml
index 23b5916..c13413f 100644
--- a/shenyu-integrated-test/shenyu-integrated-test-combination/docker-compose.yml
+++ b/shenyu-integrated-test/shenyu-integrated-test-combination/docker-compose.yml
@@ -106,6 +106,8 @@ services:
resources:
limits:
memory: 2048M
+ environment:
+ - shenyu.sync.websocket.urls=ws://shenyu-admin:9095/websocket
depends_on:
shenyu-admin:
condition: service_healthy
diff --git a/shenyu-integrated-test/shenyu-integrated-test-combination/pom.xml b/shenyu-integrated-test/shenyu-integrated-test-combination/pom.xml
index 26753fb..60f779e 100644
--- a/shenyu-integrated-test/shenyu-integrated-test-combination/pom.xml
+++ b/shenyu-integrated-test/shenyu-integrated-test-combination/pom.xml
@@ -98,8 +98,40 @@
<version>${project.version}</version>
</dependency>
<!-- shenyu ratelimiter plugin end-->
+
+ <!-- shenyu rewrite plugin start-->
+ <dependency>
+ <groupId>org.apache.shenyu</groupId>
+ <artifactId>shenyu-spring-boot-starter-plugin-rewrite</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <!-- shenyu rewrite plugin end-->
+
+ <!-- apache shenyu redirect plugin start-->
+ <dependency>
+ <groupId>org.apache.shenyu</groupId>
+ <artifactId>shenyu-spring-boot-starter-plugin-redirect</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <!-- apache shenyu redirect plugin end-->
+
+ <!-- shenyu jwt plugin starter-->
+ <dependency>
+ <groupId>org.apache.shenyu</groupId>
+ <artifactId>shenyu-spring-boot-starter-plugin-jwt</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <!-- shenyu jwt plugin end-->
+
+ <!-- apache shenyu request plugin start-->
+ <dependency>
+ <groupId>org.apache.shenyu</groupId>
+ <artifactId>shenyu-spring-boot-starter-plugin-request</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <!-- apache shenyu request plugin end-->
</dependencies>
-
+
<profiles>
<profile>
<id>it</id>
diff --git a/shenyu-integrated-test/shenyu-integrated-test-combination/src/main/resources/application-local.yml b/shenyu-integrated-test/shenyu-integrated-test-combination/src/main/resources/application-local.yml
index c35f578..ebc493a 100644
--- a/shenyu-integrated-test/shenyu-integrated-test-combination/src/main/resources/application-local.yml
+++ b/shenyu-integrated-test/shenyu-integrated-test-combination/src/main/resources/application-local.yml
@@ -35,7 +35,7 @@ shenyu:
enabled: true
sync:
websocket:
- urls: ws://shenyu-admin:9095/websocket
+ urls: ws://localhost:9095/websocket
exclude:
enabled: true
paths:
diff --git a/shenyu-integrated-test/shenyu-integrated-test-combination/src/test/java/org/apache/shenyu/integrated/test/combination/MultiRequestPluginTest.java b/shenyu-integrated-test/shenyu-integrated-test-combination/src/test/java/org/apache/shenyu/integrated/test/combination/MultiRequestPluginTest.java
index cf4aeab..03ddcd0 100644
--- a/shenyu-integrated-test/shenyu-integrated-test-combination/src/test/java/org/apache/shenyu/integrated/test/combination/MultiRequestPluginTest.java
+++ b/shenyu-integrated-test/shenyu-integrated-test-combination/src/test/java/org/apache/shenyu/integrated/test/combination/MultiRequestPluginTest.java
@@ -17,62 +17,126 @@
package org.apache.shenyu.integrated.test.combination;
-import com.google.gson.JsonObject;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.shenyu.common.dto.ConditionData;
-import org.apache.shenyu.common.dto.convert.rule.RuleHandle;
+import org.apache.shenyu.common.dto.PluginData;
+import org.apache.shenyu.common.dto.convert.rule.RateLimiterHandle;
+import org.apache.shenyu.common.dto.convert.rule.RedirectHandle;
+import org.apache.shenyu.common.dto.convert.rule.RequestHandle;
+import org.apache.shenyu.common.dto.convert.rule.RewriteHandle;
import org.apache.shenyu.common.dto.convert.rule.impl.ParamMappingRuleHandle;
import org.apache.shenyu.common.enums.OperatorEnum;
import org.apache.shenyu.common.enums.ParamTypeEnum;
import org.apache.shenyu.common.enums.PluginEnum;
import org.apache.shenyu.common.utils.JsonUtils;
import org.apache.shenyu.integratedtest.common.AbstractPluginDataInit;
-import org.apache.shenyu.integratedtest.common.dto.UserDTO;
+import org.apache.shenyu.integratedtest.common.dto.AdminResponse;
+import org.apache.shenyu.integratedtest.common.dto.ModifyResponseDTO;
import org.apache.shenyu.integratedtest.common.helper.HttpHelper;
import org.apache.shenyu.plugin.cryptor.handler.CryptorRuleHandler;
import org.apache.shenyu.plugin.cryptor.strategy.RsaStrategy;
+import org.apache.shenyu.web.controller.LocalPluginController;
import org.apache.shenyu.web.controller.LocalPluginController.RuleLocalData;
import org.junit.Test;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import java.util.Base64;
+import com.google.common.reflect.TypeToken;
+import com.google.gson.JsonObject;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
/**
* The integrated test for combination plugins about request.
*/
public final class MultiRequestPluginTest extends AbstractPluginDataInit {
- private static final String RSA_PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvEXyUDh5qliWhM6KrpTFi1OXumoJQzMfSr8XjfKa/kHKb1uxr7N8lJd3I850m2IYrxckFCQW6nrnRKctm"
- + "iMgZQIDAQABAkBEFbdvMz0sUST9mgOk5sAZhn1UOIxo9M/YJArMlnNehqQs3Pv8RD6ASisgs19XnBhcUNdl2ecfxddp7OVQ6PVxAiEA+XagQdbwkFrEjUsPqPQTweKkc7aoVGJfifEGWvCKtAcCIQDBNN0K5vlVV5YKnA5WtDAN"
- + "K31oRGjTJe5D94IRYRHlMwIgQUH++jo4BAs6j5urJQ90e6vGSV7m+ewiAfvDJdb28dECIQCW9r9grWlVDcLnN1jc1p5VLA4pUoq1sYWjBdpTyg05kQIhAJUSfs1+gDFtCRekCwvn5QEnxJVJXD6SQPAPkEHS9Drb";
+ private static final String RSA_PRIVATE_KEY =
+ "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvEXyUDh5qliWhM6KrpTFi1OXumoJQzMfSr8XjfKa/kHKb1uxr7N8lJd3I850m2IYrxckFCQW6nrnRKctm"
+ + "iMgZQIDAQABAkBEFbdvMz0sUST9mgOk5sAZhn1UOIxo9M/YJArMlnNehqQs3Pv8RD6ASisgs19XnBhcUNdl2ecfxddp7OVQ6PVxAiEA"
+ + "+XagQdbwkFrEjUsPqPQTweKkc7aoVGJfifEGWvCKtAcCIQDBNN0K5vlVV5YKnA5WtDAN"
+ + "K31oRGjTJe5D94IRYRHlMwIgQUH++jo4BAs6j5urJQ90e6vGSV7m+ewiAfvDJdb28dECIQCW9r9grWlVDcLnN1jc1p5VLA4pUoq1sYWjBdpTyg05kQIhAJUSfs1"
+ + "+gDFtCRekCwvn5QEnxJVJXD6SQPAPkEHS9Drb";
- private static final String RSA_PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALxF8lA4eapYloTOiq6UxYtTl7pqCUMzH0q/F43ymv5Bym9bsa+zfJSXdyPOdJtiGK8XJBQkFup650SnLZojIGUCAwEAAQ==";
+ private static final String RSA_PUBLIC_KEY =
+ "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALxF8lA4eapYloTOiq6UxYtTl7pqCUMzH0q/F43ymv5Bym9bsa+zfJSXdyPOdJtiGK8XJBQkFup650SnLZojIGUCAwEAAQ==";
- private static final String TEST_PATH = "/http/test/payment";
+ private static final String TEST_MODIFY_REQUEST = "/http/test/modifyRequest";
+
+ private static final String TEST_REDIRECT_URL = "/shenyu/plugin/saveOrUpdate";
private static final String TEST_USER_ID = "10001";
private static final String TEST_USER_NAME = "user_name";
+ private static final String AFTER_REWRITING_PATH = "/test/modifyRequest";
+
private static final RsaStrategy RSA_STRATEGY = new RsaStrategy();
private void setupParamMapping() throws IOException {
String paramMappingRet = initPlugin(PluginEnum.PARAM_MAPPING.getName(), "{\"ruleHandlePageType\":\"custom\"}");
assertThat(paramMappingRet, is("success"));
- String selectorAndRulesRet4ParamMapping = initSelectorAndRules(PluginEnum.PARAM_MAPPING.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4ParamMapping());
+ String selectorAndRulesRet4ParamMapping =
+ initSelectorAndRules(PluginEnum.PARAM_MAPPING.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4ParamMapping());
assertThat(selectorAndRulesRet4ParamMapping, is("success"));
}
private void setupCryptorRequest() throws IOException {
String cryptorRequestRet = initPlugin(PluginEnum.CRYPTOR_REQUEST.getName(), null);
assertThat(cryptorRequestRet, is("success"));
- String selectorAndRulesResult = initSelectorAndRules(PluginEnum.CRYPTOR_REQUEST.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4CryptorRequest());
+ String selectorAndRulesResult =
+ initSelectorAndRules(PluginEnum.CRYPTOR_REQUEST.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4CryptorRequest());
+ assertThat(selectorAndRulesResult, is("success"));
+ }
+
+ private void setupRewrite() throws IOException {
+ String paramMappingRet = initPlugin(PluginEnum.REWRITE.getName(), "{\"ruleHandlePageType\":\"custom\"}");
+ assertThat(paramMappingRet, is("success"));
+ String selectorAndRulesRet4ParamMapping =
+ initSelectorAndRules(PluginEnum.REWRITE.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4Rewrite());
+ assertThat(selectorAndRulesRet4ParamMapping, is("success"));
+ }
+
+ private void setupRedirect() throws IOException {
+ String paramMappingRet = initPlugin(PluginEnum.REDIRECT.getName(), "{\"ruleHandlePageType\":\"custom\"}");
+ assertThat(paramMappingRet, is("success"));
+ String selectorAndRulesRet4ParamMapping =
+ initSelectorAndRules(PluginEnum.REDIRECT.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4Redirect());
+ assertThat(selectorAndRulesRet4ParamMapping, is("success"));
+ }
+
+ private void setupRateLimiter(final String algorithmName) throws IOException {
+ String paramMappingRet = initPlugin(PluginEnum.RATE_LIMITER.getName(),
+ "{\"mode\":\"standalone\",\"master\":\"mymaster\",\"url\":\"shenyu-redis:6379\",\"password\":\"abc\"}");
+ assertThat(paramMappingRet, is("success"));
+ String selectorAndRulesResult = initSelectorAndRules(PluginEnum.RATE_LIMITER.getName(), "", buildSelectorConditionList(),
+ buildRuleLocalDataList4RateLimiter(algorithmName));
+ assertThat(selectorAndRulesResult, is("success"));
+ }
+
+ private void setupRequest() throws IOException {
+ String paramMappingRet = initPlugin(PluginEnum.REQUEST.getName(), null);
+ assertThat(paramMappingRet, is("success"));
+ String selectorAndRulesResult =
+ initSelectorAndRules(PluginEnum.REQUEST.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4Request());
+ assertThat(selectorAndRulesResult, is("success"));
+ }
+
+ private void setupJWT() throws IOException {
+ String pluginResult = initPlugin(PluginEnum.JWT.getName(), "{\"secretKey\":\"key00000\"}");
+ assertThat(pluginResult, is("success"));
+ String selectorAndRulesResult =
+ initSelectorAndRules(PluginEnum.JWT.getName(), "", buildSelectorConditionList(), buildRuleLocalDataList4JWT());
assertThat(selectorAndRulesResult, is("success"));
}
@@ -81,18 +145,324 @@ public final class MultiRequestPluginTest extends AbstractPluginDataInit {
*/
@Test
public void testCryptorRequestAndParamMapping() throws Exception {
- setupParamMapping();
- setupCryptorRequest();
+ try {
+ setupParamMapping();
+ setupCryptorRequest();
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, ModifyResponseDTO.class);
+ byte[] inputByte = Base64.getMimeDecoder().decode(actualUser.getBody().getUserName());
+ assertThat(RSA_STRATEGY.decrypt(RSA_PRIVATE_KEY, inputByte), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+ } finally {
+ cleanParamMapping();
+ cleanCryptorRequest();
+ }
+ }
+
+ /**
+ * The combination test of Rewrite plugin and param mapping plugin.
+ */
+ @Test
+ public void testRewriteAndParamMapping() throws Exception {
+ try {
+ setupParamMapping();
+ setupRewrite();
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+ } finally {
+ cleanParamMapping();
+ cleanRewrite();
+ }
+ }
+
+ /**
+ * The combination test of Redirect plugin and param mapping plugin.
+ */
+ @Test
+ public void testRedirectAndParamMapping() throws Exception {
+ try {
+ setupParamMapping();
+ setupRedirect();
+
+ PluginData pluginData = new PluginData();
+ pluginData.setEnabled(true);
+ pluginData.setName(PluginEnum.REDIRECT.getName());
+ pluginData.setConfig("{\"ruleHandlePageType\":\"custom\"}");
+
+ String response = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, pluginData, String.class);
+ assertThat(response, is("success"));
+ } finally {
+ cleanParamMapping();
+ cleanRedirect();
+ }
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with slidingWindow.
+ */
+ @Test
+ public void testSlidingWindowAndRewrite() throws IOException, InterruptedException {
+ testRateLimiterAndRewrite("slidingWindow");
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with leakyBucket.
+ */
+ @Test
+ public void testLeakyBucketAndRewrite() throws IOException, InterruptedException {
+ testRateLimiterAndRewrite("leakyBucket");
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with tokenBucket.
+ */
+ @Test
+ public void testTokenBucketAndRewrite() throws IOException, InterruptedException {
+ testRateLimiterAndRewrite("tokenBucket");
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with leakyBucket.
+ */
+ @Test
+ public void testLeakyBucketAndRedirect() throws IOException, InterruptedException {
+ testRateLimiterAndRedirect("leakyBucket");
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with tokenBucket.
+ */
+ @Test
+ public void testTokenBucketAndRedirect() throws IOException, InterruptedException {
+ testRateLimiterAndRedirect("tokenBucket");
+ }
+
+ /**
+ * The combination test of Rewrite plugin and RateLimiter plugin with slidingWindow.
+ */
+ @Test
+ public void testSlidingWindowAndRedirect() throws IOException, InterruptedException {
+ testRateLimiterAndRedirect("slidingWindow");
+ }
+
+ /**
+ * The combination test of Request plugin and Rewrite plugin.
+ */
+ @Test
+ public void testRequestAndRewrite() throws IOException {
+ try {
+ setupRequest();
+ setupRewrite();
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ request.addProperty("userName", TEST_USER_NAME);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+
+ assertThat(actualUser.getCookie(), is("cookie"));
+ assertThat(actualUser.getHeader(), is("requestHeader"));
+ assertThat(actualUser.getParameter(), is("requestParameter"));
+ } finally {
+ cleanRequest();
+ cleanRewrite();
+ }
+ }
+
+ /**
+ * The combination test of Request plugin and Redirect plugin.
+ */
+ @Test
+ public void testRequestAndRedirect() throws IOException {
+ try {
+ setupRequest();
+ setupRedirect();
+
+ PluginData pluginData = new PluginData();
+ pluginData.setEnabled(true);
+ pluginData.setName(PluginEnum.REDIRECT.getName());
+ pluginData.setConfig("{\"ruleHandlePageType\":\"custom\"}");
+
+ String response = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, pluginData, String.class);
+ assertThat(response, is("success"));
+ } finally {
+ cleanRequest();
+ cleanRedirect();
+ }
+ }
+
+ /**
+ * The combination test of JWT plugin and Redirect plugin.
+ */
+ @Test
+ public void testJWTAndRedirect() throws IOException {
+ try {
+ setupJWT();
+ setupRedirect();
+
+ final String key = "key00000";
+ final String token = Jwts.builder().setId("1001").signWith(SignatureAlgorithm.HS256, key.getBytes(StandardCharsets.UTF_8)).compact();
+ Map<String, Object> headers = new HashMap<>();
+ headers.put("token", token);
+ PluginData pluginData = new PluginData();
+ pluginData.setEnabled(true);
+ pluginData.setName(PluginEnum.REDIRECT.getName());
+ pluginData.setConfig("{\"ruleHandlePageType\":\"custom\"}");
+
+ String response = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, headers, pluginData, String.class);
+ assertThat(response, is("success"));
+ } finally {
+ setupJWT();
+ cleanRedirect();
+ }
+ }
+
+ /**
+ * The combination test of JWT plugin and RateLimiter plugin with tokenBucket.
+ */
+ @Test
+ public void testJWTAndTokenBucket() throws IOException, InterruptedException {
+ testRateLimiterAndJWT("tokenBucket");
+ }
+
+ /**
+ * The combination test of JWT plugin and RateLimiter plugin with slidingWindow.
+ */
+ @Test
+ public void testJWTAndSlidingWindow() throws IOException, InterruptedException {
+ testRateLimiterAndJWT("slidingWindow");
+ }
+
+ /**
+ * The combination test of JWT plugin and RateLimiter plugin with leakyBucket.
+ */
+ @Test
+ public void testJWTAndLeakyBucket() throws IOException, InterruptedException {
+ testRateLimiterAndJWT("leakyBucket");
+ }
+
+ /**
+ * The combination test of JWT plugin and Rewrite plugin.
+ */
+ @Test
+ public void testJWTAndRewrite() throws IOException {
+ try {
+ setupJWT();
+ setupRewrite();
+
+ final String key = "key00000";
+ final String token = Jwts.builder().setId("1001").signWith(SignatureAlgorithm.HS256, key.getBytes(StandardCharsets.UTF_8)).compact();
+ Map<String, Object> headers = new HashMap<>();
+ headers.put("token", token);
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ request.addProperty("userName", TEST_USER_NAME);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, headers, request, ModifyResponseDTO.class);
+
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+ } finally {
+ cleanJWT();
+ cleanRewrite();
+ }
+ }
+
+ private void testRateLimiterAndRedirect(final String algorithmName) throws IOException, InterruptedException {
+ try {
+ setupRateLimiter(algorithmName);
+ setupRedirect();
+
+ PluginData pluginData = new PluginData();
+ pluginData.setEnabled(true);
+ pluginData.setName(PluginEnum.REDIRECT.getName());
+ pluginData.setConfig("{\"ruleHandlePageType\":\"custom\"}");
+
+ String response = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, pluginData, String.class);
+ assertThat(response, is("success"));
+
+ AdminResponse<Object> errorRsp = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, pluginData, new TypeToken<AdminResponse<Object>>() {
+ }.getType());
+ assertThat(errorRsp.getMessage(), is("You have been restricted, please try again later!"));
+ assertThat(errorRsp.getCode(), is(429));
+
+ Thread.sleep(2000);
+
+ response = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, pluginData, String.class);
+ assertThat(response, is("success"));
+ } finally {
+ cleanRateLimiter();
+ cleanRedirect();
+ }
+ }
+
+ private void testRateLimiterAndRewrite(final String algorithmName) throws IOException, InterruptedException {
+ try {
+ setupRateLimiter(algorithmName);
+ setupRewrite();
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ request.addProperty("userName", TEST_USER_NAME);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+
+ AdminResponse<Object> errorRsp = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, new TypeToken<AdminResponse<Object>>() {
+ }.getType());
+ assertThat(errorRsp.getMessage(), is("You have been restricted, please try again later!"));
+ assertThat(errorRsp.getCode(), is(429));
- JsonObject request = new JsonObject();
- request.addProperty("userId", TEST_USER_ID);
- UserDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_PATH, request, UserDTO.class);
- byte[] inputByte = Base64.getMimeDecoder().decode(actualUser.getUserName());
- assertThat(RSA_STRATEGY.decrypt(RSA_PRIVATE_KEY, inputByte), is(TEST_USER_NAME));
- assertThat(actualUser.getUserId(), is(TEST_USER_ID));
+ Thread.sleep(2000);
- cleanParamMapping();
- cleanCryptorRequest();
+ actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+ } finally {
+ cleanRateLimiter();
+ cleanRewrite();
+ }
+ }
+
+ private void testRateLimiterAndJWT(final String algorithmName) throws IOException, InterruptedException {
+ try {
+ setupRateLimiter(algorithmName);
+ setupJWT();
+
+ final String key = "key00000";
+ final String token = Jwts.builder().setId("1001").signWith(SignatureAlgorithm.HS256, key.getBytes(StandardCharsets.UTF_8)).compact();
+ Map<String, Object> headers = new HashMap<>();
+ headers.put("token", token);
+
+ JsonObject request = new JsonObject();
+ request.addProperty("userId", TEST_USER_ID);
+ request.addProperty("userName", TEST_USER_NAME);
+ ModifyResponseDTO actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, headers, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+
+ AdminResponse<Object> errorRsp =
+ HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, headers, request, new TypeToken<AdminResponse<Object>>() {
+ }.getType());
+ assertThat(errorRsp.getMessage(), is("You have been restricted, please try again later!"));
+ assertThat(errorRsp.getCode(), is(429));
+
+ Thread.sleep(2000);
+
+ actualUser = HttpHelper.INSTANCE.postGateway(TEST_MODIFY_REQUEST, headers, request, ModifyResponseDTO.class);
+ assertThat(actualUser.getBody().getUserName(), is(TEST_USER_NAME));
+ assertThat(actualUser.getBody().getUserId(), is(TEST_USER_ID));
+ } finally {
+ cleanRateLimiter();
+ cleanJWT();
+ }
}
private List<ConditionData> buildSelectorConditionList() {
@@ -103,13 +473,13 @@ public final class MultiRequestPluginTest extends AbstractPluginDataInit {
return Collections.singletonList(conditionData);
}
- private RuleLocalData buildRuleLocalData(final RuleHandle handle) {
+ private RuleLocalData buildRuleLocalData(final String handleStr) {
RuleLocalData ruleLocalData = new RuleLocalData();
- Optional.ofNullable(handle).ifPresent(ruleHandle -> ruleLocalData.setRuleHandler(JsonUtils.toJson(ruleHandle)));
+ ruleLocalData.setRuleHandler(handleStr);
ConditionData conditionData = new ConditionData();
conditionData.setParamType(ParamTypeEnum.URI.getName());
conditionData.setOperator(OperatorEnum.EQ.getAlias());
- conditionData.setParamValue(TEST_PATH);
+ conditionData.setParamValue(MultiRequestPluginTest.TEST_MODIFY_REQUEST);
ruleLocalData.setConditionDataList(Collections.singletonList(conditionData));
return ruleLocalData;
}
@@ -117,14 +487,15 @@ public final class MultiRequestPluginTest extends AbstractPluginDataInit {
private List<RuleLocalData> buildRuleLocalDataList4ParamMapping() {
final List<RuleLocalData> ruleLocalDataList = new ArrayList<>();
- // prepare for addParameterKeys
final ParamMappingRuleHandle addAndRemoveHandle = new ParamMappingRuleHandle();
+ // prepare for addParameterKeys
ParamMappingRuleHandle.ParamMapInfo addInfo = new ParamMappingRuleHandle.ParamMapInfo();
addInfo.setPath("$");
addInfo.setKey("userName");
addInfo.setValue(TEST_USER_NAME);
addAndRemoveHandle.setAddParameterKeys(Collections.singletonList(addInfo));
- ruleLocalDataList.add(buildRuleLocalData(addAndRemoveHandle));
+
+ ruleLocalDataList.add(buildRuleLocalData(JsonUtils.toJson(addAndRemoveHandle)));
return ruleLocalDataList;
}
@@ -136,7 +507,66 @@ public final class MultiRequestPluginTest extends AbstractPluginDataInit {
cryptorRuleHandler.setStrategyName("rsa");
cryptorRuleHandler.setFieldNames("userName");
cryptorRuleHandler.setWay("encrypt");
- return Collections.singletonList(buildRuleLocalData(cryptorRuleHandler));
+ return Collections.singletonList(buildRuleLocalData(JsonUtils.toJson(cryptorRuleHandler)));
+ }
+
+ private List<LocalPluginController.RuleLocalData> buildRuleLocalDataList4Rewrite() {
+ final List<LocalPluginController.RuleLocalData> ruleLocalDataList = new ArrayList<>();
+ RewriteHandle rewriteHandle = new RewriteHandle();
+ rewriteHandle.setRegex(TEST_MODIFY_REQUEST);
+ rewriteHandle.setReplace(AFTER_REWRITING_PATH);
+
+ ruleLocalDataList.add(buildRuleLocalData(JsonUtils.toJson(rewriteHandle)));
+
+ return ruleLocalDataList;
+ }
+
+ private List<RuleLocalData> buildRuleLocalDataList4Redirect() {
+ final List<RuleLocalData> ruleLocalDataList = new ArrayList<>();
+ RedirectHandle redirectHandle = new RedirectHandle();
+ redirectHandle.setRedirectURI(TEST_REDIRECT_URL);
+
+ ruleLocalDataList.add(buildRuleLocalData(JsonUtils.toJson(redirectHandle)));
+
+ return ruleLocalDataList;
+ }
+
+ private List<RuleLocalData> buildRuleLocalDataList4RateLimiter(final String algorithmName) {
+ RateLimiterHandle rateLimiterHandle = new RateLimiterHandle();
+ rateLimiterHandle.setAlgorithmName(algorithmName);
+ rateLimiterHandle.setReplenishRate(0.5);
+ rateLimiterHandle.setBurstCapacity(1);
+ // see WholeKeyResolver.java
+ rateLimiterHandle.setKeyResolverName("WHOLE_KEY_RESOLVER");
+ return Collections.singletonList(buildRuleLocalData(JsonUtils.toJson(rateLimiterHandle)));
+ }
+
+ private List<RuleLocalData> buildRuleLocalDataList4Request() {
+ RequestHandle requestHandle = new RequestHandle();
+ final RequestHandle.ShenyuRequestParameter requestParameter = requestHandle.new ShenyuRequestParameter();
+ final RequestHandle.ShenyuRequestHeader requestHeader = requestHandle.new ShenyuRequestHeader();
+ final RequestHandle.ShenyuCookie cookie = requestHandle.new ShenyuCookie();
+
+ Map<String, String> paramMap = new HashMap<>();
+ paramMap.put("requestParameter", "requestParameter");
+ requestParameter.setSetParameters(new HashMap<>(paramMap));
+ requestHandle.setParameter(requestParameter);
+
+ paramMap.clear();
+ paramMap.put("requestHeader", "requestHeader");
+ requestHeader.setSetHeaders(new HashMap<>(paramMap));
+ requestHandle.setHeader(requestHeader);
+
+ paramMap.clear();
+ paramMap.put("cookie", "cookie");
+ cookie.setSetCookies(new HashMap<>(paramMap));
+ requestHandle.setCookie(cookie);
+
+ return Collections.singletonList(buildRuleLocalData(JsonUtils.toJson(requestHandle)));
+ }
+
+ private List<RuleLocalData> buildRuleLocalDataList4JWT() {
+ return Collections.singletonList(buildRuleLocalData(null));
}
private void cleanParamMapping() throws IOException {
@@ -148,4 +578,29 @@ public final class MultiRequestPluginTest extends AbstractPluginDataInit {
String res = cleanPluginData(PluginEnum.CRYPTOR_REQUEST.getName());
assertThat(res, is("success"));
}
+
+ private void cleanRewrite() throws IOException {
+ String res = cleanPluginData(PluginEnum.REWRITE.getName());
+ assertThat(res, is("success"));
+ }
+
+ private void cleanRedirect() throws IOException {
+ String res = cleanPluginData(PluginEnum.REDIRECT.getName());
+ assertThat(res, is("success"));
+ }
+
+ private void cleanRateLimiter() throws IOException {
+ String res = cleanPluginData(PluginEnum.RATE_LIMITER.getName());
+ assertThat(res, is("success"));
+ }
+
+ private void cleanRequest() throws IOException {
+ String res = cleanPluginData(PluginEnum.REQUEST.getName());
+ assertThat(res, is("success"));
+ }
+
+ private void cleanJWT() throws IOException {
+ String res = cleanPluginData(PluginEnum.JWT.getName());
+ assertThat(res, is("success"));
+ }
}
diff --git a/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/dto/ModifyResponseDTO.java b/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/dto/ModifyResponseDTO.java
new file mode 100644
index 0000000..b776636
--- /dev/null
+++ b/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/dto/ModifyResponseDTO.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shenyu.integratedtest.common.dto;
+
+public class ModifyResponseDTO {
+
+ private UserDTO body;
+
+ private String cookie;
+
+ private String header;
+
+ private String parameter;
+
+ public ModifyResponseDTO() {
+ }
+
+ public ModifyResponseDTO(final UserDTO body, final String cookie, final String header, final String parameter) {
+ this.body = body;
+ this.cookie = cookie;
+ this.header = header;
+ this.parameter = parameter;
+ }
+
+ /**
+ * get body.
+ *
+ * @return UserDTO
+ */
+ public UserDTO getBody() {
+ return body;
+ }
+
+ /**
+ * set body.
+ *
+ * @param body body
+ */
+ public void setBody(final UserDTO body) {
+ this.body = body;
+ }
+
+ /**
+ * get cookie.
+ *
+ * @return the cookie
+ */
+ public String getCookie() {
+ return cookie;
+ }
+
+ /**
+ * set cookie.
+ *
+ * @param cookie the cookie
+ */
+ public void setCookie(final String cookie) {
+ this.cookie = cookie;
+ }
+
+ /**
+ * get header.
+ *
+ * @return the header
+ */
+ public String getHeader() {
+ return header;
+ }
+
+ /**
+ * set header.
+ *
+ * @param header the header
+ */
+ public void setHeader(final String header) {
+ this.header = header;
+ }
+
+ /**
+ * get parameter.
+ *
+ * @return the parameter
+ */
+ public String getParameter() {
+ return parameter;
+ }
+
+ /**
+ * set parameter.
+ *
+ * @param parameter the parameter
+ */
+ public void setParameter(final String parameter) {
+ this.parameter = parameter;
+ }
+}
diff --git a/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/helper/HttpHelper.java b/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/helper/HttpHelper.java
index c99d7eb..009eee6 100644
--- a/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/helper/HttpHelper.java
+++ b/shenyu-integrated-test/shenyu-integrated-test-common/src/main/java/org/apache/shenyu/integratedtest/common/helper/HttpHelper.java
@@ -61,21 +61,32 @@ public class HttpHelper {
/**
* Send a post http request to shenyu gateway.
*
- * @param <S> type of response object
- * @param <Q> type of request object
- * @param path path
- * @param req request body as an object
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
+ * @param req request body as an object
* @param respType response type passed to {@link Gson#fromJson(String, Type)}
* @return response s
* @throws IOException IO exception
*/
public <S, Q> S postGateway(final String path, final Q req, final Type respType) throws IOException {
- Request request = new Request.Builder()
- .url(GATEWAY_END_POINT + path)
- .post(RequestBody.create(GSON.toJson(req), JSON))
- .build();
- Response response = client.newCall(request).execute();
- String respBody = Objects.requireNonNull(response.body()).string();
+ return postGateway(path, null, req, respType);
+ }
+
+ /**
+ * Send a post http request to shenyu gateway.
+ *
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
+ * @param headers http header
+ * @param req request body as an object
+ * @param respType response type passed to {@link Gson#fromJson(String, Type)}
+ * @return response s
+ * @throws IOException IO exception
+ */
+ public <S, Q> S postGateway(final String path, final Map<String, Object> headers, final Q req, final Type respType) throws IOException {
+ String respBody = post(path, headers, req);
LOG.info("postGateway({}) resp({})", path, respBody);
try {
return GSON.fromJson(respBody, respType);
@@ -87,9 +98,9 @@ public class HttpHelper {
/**
* Send a post http request to shenyu gateway.
*
- * @param <S> type of response object
- * @param <Q> type of request object
- * @param path path
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
* @param respType response type passed to {@link Gson#fromJson(String, Type)}
* @return response s
* @throws IOException IO exception
@@ -101,21 +112,32 @@ public class HttpHelper {
/**
* Send a post http request to shenyu gateway.
*
- * @param <S> type of response object
- * @param <Q> type of request object
- * @param path path
- * @param req request body as an object
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
+ * @param req request body as an object
* @param respType response type passed to {@link Gson#fromJson(String, Class)}
* @return response s
* @throws IOException IO exception
*/
public <S, Q> S postGateway(final String path, final Q req, final Class<S> respType) throws IOException {
- Request request = new Request.Builder()
- .post(RequestBody.create(GSON.toJson(req), JSON))
- .url(GATEWAY_END_POINT + path)
- .build();
- Response response = client.newCall(request).execute();
- String respBody = Objects.requireNonNull(response.body()).string();
+ return postGateway(path, null, req, respType);
+ }
+
+ /**
+ * Send a post http request to shenyu gateway with header.
+ *
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
+ * @param headers http header
+ * @param req request body as an object
+ * @param respType response type passed to {@link Gson#fromJson(String, Class)}
+ * @return response s
+ * @throws IOException IO exception
+ */
+ public <S, Q> S postGateway(final String path, final Map<String, Object> headers, final Q req, final Class<S> respType) throws IOException {
+ String respBody = post(path, headers, req);
LOG.info("postGateway({}) resp({})", path, respBody);
try {
return GSON.fromJson(respBody, respType);
@@ -123,23 +145,29 @@ public class HttpHelper {
return (S) respBody;
}
}
-
+
+ private <Q> String post(final String path, final Map<String, Object> headers, final Q req) throws IOException {
+ Request.Builder requestBuilder = new Request.Builder().post(RequestBody.create(GSON.toJson(req), JSON)).url(GATEWAY_END_POINT + path);
+ if (!CollectionUtils.isEmpty(headers)) {
+ headers.forEach((key, value) -> requestBuilder.addHeader(key, String.valueOf(value)));
+ }
+ Response response = client.newCall(requestBuilder.build()).execute();
+ return Objects.requireNonNull(response.body()).string();
+ }
+
/**
* Send a put http request to shenyu gateway.
*
- * @param <S> type of response object
- * @param <Q> type of request object
- * @param path path
- * @param req request body as an object
+ * @param <S> type of response object
+ * @param <Q> type of request object
+ * @param path path
+ * @param req request body as an object
* @param respType response type passed to {@link Gson#fromJson(String, Class)}
* @return response s
* @throws IOException IO exception
*/
public <S, Q> S putGateway(final String path, final Q req, final Class<S> respType) throws IOException {
- Request request = new Request.Builder()
- .put(RequestBody.create(GSON.toJson(req), JSON))
- .url(GATEWAY_END_POINT + path)
- .build();
+ Request request = new Request.Builder().put(RequestBody.create(GSON.toJson(req), JSON)).url(GATEWAY_END_POINT + path).build();
Response response = client.newCall(request).execute();
String respBody = Objects.requireNonNull(response.body()).string();
LOG.info("postGateway({}) resp({})", path, respBody);
@@ -153,7 +181,7 @@ public class HttpHelper {
/**
* Send a get http request to shenyu gateway without headers.
*
- * @param <S> response type
+ * @param <S> response type
* @param path path
* @param type type of response passed to {@link Gson#fromJson(String, Type)}
* @return response from gateway
@@ -166,10 +194,10 @@ public class HttpHelper {
/**
* Send a get http request to shenyu gateway with headers.
*
- * @param <S> response type
- * @param path path
+ * @param <S> response type
+ * @param path path
* @param headers headers
- * @param type type of response passed to {@link Gson#fromJson(String, Type)}
+ * @param type type of response passed to {@link Gson#fromJson(String, Type)}
* @return response from gateway
* @throws IOException IO exception
*/
@@ -187,7 +215,7 @@ public class HttpHelper {
/**
* Send a get http request to shenyu gateway with headers.
*
- * @param path path
+ * @param path path
* @param headers headers
* @return response from gateway
* @throws IOException IO exception
@@ -199,7 +227,7 @@ public class HttpHelper {
/**
* Send a get http request to http service with headers.
*
- * @param url url
+ * @param url url
* @param headers headers
* @return response
* @throws IOException IO exception