Skip to content

Commit

Permalink
Merge pull request #61 from ruks/master
Browse files Browse the repository at this point in the history
Added throttling and jwt test cases
  • Loading branch information
harsha89 authored Jun 15, 2018
2 parents b32028e + e21bc9b commit 002c633
Show file tree
Hide file tree
Showing 16 changed files with 738 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import wso2/gateway;
future ftr = start initThrottlePolicies();

function initThrottlePolicies() {
runtime:sleep(100);
while (true) {
if(gateway:isStreamsInitialized == true) {
log:printDebug("Throttle streams initialized.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,25 @@
*/
package org.wso2.micro.gateway.tests.common;

import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.micro.gateway.tests.common.model.API;
import org.wso2.micro.gateway.tests.common.model.ApplicationDTO;
import org.wso2.micro.gateway.tests.common.model.SubscribedApiDTO;
import org.wso2.micro.gateway.tests.context.ServerInstance;
import org.wso2.micro.gateway.tests.util.TestConstant;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;

/**
* Base test class for CLI based tests
Expand Down Expand Up @@ -50,5 +65,73 @@ public void init(String label) throws Exception {
public void finalize() throws Exception {
mockHttpServer.stopIt();
microGWServer.stopServer(false);
MockAPIPublisher.getInstance().clear();
}

protected String getJWT(API api, ApplicationDTO applicationDTO, String tier) throws Exception {
return getJWT(api.getName(), "/" + api.getContext() + "/" + api.getVersion(), api.getVersion(), tier,
applicationDTO.getName(), applicationDTO.getTier());
}

protected String getJWT(String apiName, String context, String version, String subTier, String appName,
String appTier) throws Exception {
ApplicationDTO applicationDTO = new ApplicationDTO();
applicationDTO.setId(10);
applicationDTO.setName(appName);
applicationDTO.setTier(appTier);

SubscribedApiDTO subscribedApiDTO = new SubscribedApiDTO();
subscribedApiDTO.setContext(context);
subscribedApiDTO.setName(apiName);
subscribedApiDTO.setVersion(version);
subscribedApiDTO.setPublisher("admin");
subscribedApiDTO.setSubscriptionTier(subTier);
subscribedApiDTO.setSubscriberTenantDomain("carbon.super");

JSONObject jwtTokenInfo = new JSONObject();
jwtTokenInfo.put("aud", "http://org.wso2.apimgt/gateway");
jwtTokenInfo.put("sub", "admin");
jwtTokenInfo.put("application", new JSONObject(applicationDTO));
jwtTokenInfo.put("scope", "am_application_scope default");
jwtTokenInfo.put("iss", "https://localhost:8244/token");
jwtTokenInfo.put("keytype", "PRODUCTION");
jwtTokenInfo.put("subscribedAPIs", new JSONArray(Arrays.asList(subscribedApiDTO)));
jwtTokenInfo.put("exp", System.currentTimeMillis() + 3600 * 1000);
jwtTokenInfo.put("iat", System.currentTimeMillis());
jwtTokenInfo.put("jti", UUID.randomUUID());

String payload = jwtTokenInfo.toString();

JSONObject head = new JSONObject();
head.put("typ", "JWT");
head.put("alg", "RS256");
head.put("x5t", "UB_BQy2HFV3EMTgq64Q-1VitYbE");
String header = head.toString();

String base64UrlEncodedHeader = Base64.getUrlEncoder()
.encodeToString(header.getBytes(Charset.defaultCharset()));
String base64UrlEncodedBody = Base64.getUrlEncoder().encodeToString(payload.getBytes(Charset.defaultCharset()));

Signature signature = Signature.getInstance("SHA256withRSA");
String jksPath = getClass().getClassLoader().getResource("wso2carbon.jks").getPath();
FileInputStream is = new FileInputStream(jksPath);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "wso2carbon".toCharArray());
String alias = "wso2carbon";
Key key = keystore.getKey(alias, "wso2carbon".toCharArray());
Key privateKey = null;
if (key instanceof PrivateKey) {
privateKey = key;
}
signature.initSign((PrivateKey) privateKey);
String assertion = base64UrlEncodedHeader + "." + base64UrlEncodedBody;
byte[] dataInBytes = assertion.getBytes(StandardCharsets.UTF_8);
signature.update(dataInBytes);
//sign the assertion and return the signature
byte[] signedAssertion = signature.sign();
String base64UrlEncodedAssertion = Base64.getUrlEncoder().encodeToString(signedAssertion);
String jwt = base64UrlEncodedHeader + '.' + base64UrlEncodedBody + '.' + base64UrlEncodedAssertion;

return jwt;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.apimgt.gateway.cli.constants.GatewayCliConstants;
import org.wso2.micro.gateway.tests.context.Constants;

import java.io.File;
import java.nio.file.Files;
Expand All @@ -41,15 +42,17 @@ public class CLIExecutor {
public void generate(String label) throws Exception {
org.wso2.apimgt.gateway.cli.cmd.Main main = new org.wso2.apimgt.gateway.cli.cmd.Main();

Path path = Files.createTempDirectory("userProject", new FileAttribute[0]);
String baseDir = (System.getProperty(Constants.SYSTEM_PROP_BASE_DIR, ".")) + File.separator + "target";
Path path = Files.createTempDirectory(new File(baseDir).toPath(), "userProject", new FileAttribute[0]);
log.info("CLI Project Home: " + path.toString());

System.setProperty(GatewayCliConstants.CLI_HOME, this.cliHome);
log.info("CLI Home: " + this.cliHome);

File asd = new File(path.toString() + File.separator + GatewayCliConstants.MAIN_DIRECTORY_NAME + File.separator
+ GatewayCliConstants.GW_DIST_CONF);
asd.mkdirs();
File gwConfDir = new File(
path.toString() + File.separator + GatewayCliConstants.MAIN_DIRECTORY_NAME + File.separator
+ GatewayCliConstants.GW_DIST_CONF);
gwConfDir.mkdirs();
Files.copy(new File(
getClass().getClassLoader().getResource("confs" + File.separator + "default-cli-test-config.toml")
.getPath()).toPath(), new File(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.micro.gateway.tests.common.model.API;
import org.wso2.micro.gateway.tests.common.model.ApplicationPolicy;
import org.wso2.micro.gateway.tests.common.model.SubscriptionPolicy;

import java.io.FileInputStream;
import java.io.IOException;
Expand All @@ -41,6 +43,8 @@ public class MockAPIPublisher {
private Map<String, List<API>> apis;
private Map<String, KeyValidationInfo> tokenInfo;
private static MockAPIPublisher instance;
private static List<SubscriptionPolicy> subscriptionPolicies;
private static List<ApplicationPolicy> applicationPolicies;

public static MockAPIPublisher getInstance() {
if (instance == null) {
Expand All @@ -52,6 +56,8 @@ public static MockAPIPublisher getInstance() {
public MockAPIPublisher() {
apis = new HashMap<>();
tokenInfo = new HashMap<>();
subscriptionPolicies = new ArrayList<>();
applicationPolicies = new ArrayList<>();
}

public void addApi(String label, API api) {
Expand Down Expand Up @@ -127,10 +133,34 @@ public String getKeyValidationResponseForToken(String token) {
try {
String xmlResponse = IOUtils.toString(new FileInputStream(
getClass().getClassLoader().getResource("key-validation-response.xml").getPath()));
xmlResponse = xmlResponse.replace("$APINAME", info.getApiName());
return xmlResponse;
} catch (IOException e) {
log.error("Error occurred when generating response", e);
throw new RuntimeException(e.getMessage(), e);
}
}

public void clear() {
tokenInfo.clear();
apis.clear();
subscriptionPolicies.clear();
applicationPolicies.clear();
}

public void addSubscriptionPolicy(SubscriptionPolicy subscriptionPolicy) {
subscriptionPolicies.add(subscriptionPolicy);
}

public static List<SubscriptionPolicy> getSubscriptionPolicies() {
return subscriptionPolicies;
}

public void addApplicationPolicy(ApplicationPolicy applicationPolicy) {
applicationPolicies.add(applicationPolicy);
}

public static List<ApplicationPolicy> getApplicationPolicies() {
return applicationPolicies;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,20 @@
*/
package org.wso2.micro.gateway.tests.common;

import com.google.gson.Gson;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.wso2.apimgt.gateway.cli.constants.GatewayCliConstants;
import org.wso2.micro.gateway.tests.common.model.ApplicationPolicy;
import org.wso2.micro.gateway.tests.common.model.SubscriptionPolicy;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
Expand Down Expand Up @@ -117,7 +121,7 @@ public void handle(HttpExchange exchange) throws IOException {
String label = null;
for (String para : paras) {
String[] searchQuery = para.split(":");
if("label".equalsIgnoreCase(searchQuery[0])){
if ("label".equalsIgnoreCase(searchQuery[0])) {
label = searchQuery[1];
}
}
Expand Down Expand Up @@ -167,18 +171,27 @@ public void handle(HttpExchange exchange) throws IOException {
});
httpServer.createContext(AdminRestAPIBasePath + "/throttling/policies/application", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
byte[] response = IOUtils.toString(new FileInputStream(
getClass().getClassLoader().getResource("application-policies.json").getPath())).getBytes();
String defaultPolicies = IOUtils.toString(new FileInputStream(
getClass().getClassLoader().getResource("application-policies.json").getPath()));
JSONObject policies = new JSONObject(defaultPolicies);
for (ApplicationPolicy policy : MockAPIPublisher.getInstance().getApplicationPolicies()) {
policies.getJSONArray("list").put(new JSONObject(new Gson().toJson(policy)));
}
byte[] response = policies.toString().getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
});
httpServer.createContext(AdminRestAPIBasePath + "/throttling/policies/subscription", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
byte[] response = IOUtils.toString(new FileInputStream(
getClass().getClassLoader().getResource("subscription-policies.json").getPath()))
.getBytes();
String defaultPolicies = IOUtils.toString(new FileInputStream(
getClass().getClassLoader().getResource("subscription-policies.json").getPath()));
JSONObject policies = new JSONObject(defaultPolicies);
for (SubscriptionPolicy policy : MockAPIPublisher.getInstance().getSubscriptionPolicies()) {
policies.getJSONArray("list").put(new JSONObject(new Gson().toJson(policy)));
}
byte[] response = policies.toString().getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.micro.gateway.tests.common.model;

import java.io.Serializable;

/**
* Application model
*/
public class ApplicationDTO implements Serializable {

private int id;
private String name;
private String tier;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getTier() {
return tier;
}

public void setTier(String tier) {
this.tier = tier;
}
}
Loading

0 comments on commit 002c633

Please sign in to comment.