Merge pull request #1049 from sinthuja/origin-wso2-master

Adding more tests to APIM handler
revert-70aa11f8
Megala Uthayakumar 7 years ago committed by GitHub
commit 40dd5bee18

@ -55,6 +55,11 @@
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -97,6 +102,15 @@
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin> <plugin>
<groupId>org.jacoco</groupId> <groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId> <artifactId>jacoco-maven-plugin</artifactId>

@ -52,7 +52,7 @@ public class AuthenticationHandler extends AbstractHandler {
private static final Log log = LogFactory.getLog(AuthenticationHandler.class); private static final Log log = LogFactory.getLog(AuthenticationHandler.class);
private RESTInvoker restInvoker; private RESTInvoker restInvoker;
private static final String X_JWT_ASSERTION = "X-JWT-Assertion"; private static final String X_JWT_ASSERTION = "X-JWT-Assertion";
private static final String JWTTOKEN = "JWTToken"; private static final String JWTTOKEN = "JWTToken";
private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Bearer "; private static final String BEARER = "Bearer ";
@ -72,8 +72,8 @@ public class AuthenticationHandler extends AbstractHandler {
/** /**
* Handling the message and checking the security. * Handling the message and checking the security.
* *
* @param messageContext * @param messageContext Request message context.
* @return * @return Boolean value of the result of the processing the request.
*/ */
@Override @Override
public boolean handleRequest(org.apache.synapse.MessageContext messageContext) { public boolean handleRequest(org.apache.synapse.MessageContext messageContext) {
@ -87,7 +87,7 @@ public class AuthenticationHandler extends AbstractHandler {
Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS); Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS);
try { try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
RESTResponse response; RESTResponse response = null;
if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) { if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) {
String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE); String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE);
@ -95,7 +95,7 @@ public class AuthenticationHandler extends AbstractHandler {
log.debug("Verify Cert:\n" + mdmSignature); log.debug("Verify Cert:\n" + mdmSignature);
} }
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
if (deviceType == null){ if (deviceType == null) {
return false; return false;
} }
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
@ -108,8 +108,7 @@ public class AuthenticationHandler extends AbstractHandler {
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
String str = response.getContent(); String str = response.getContent();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -140,8 +139,7 @@ public class AuthenticationHandler extends AbstractHandler {
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent()); log.debug("Verify response:" + response.getContent());
} }
@ -155,8 +153,6 @@ public class AuthenticationHandler extends AbstractHandler {
if (x509 != null) { if (x509 != null) {
headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509)); headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509));
return true; return true;
} else {
response = null;
} }
} else if (headers.containsKey(AuthConstants.ENCODED_PEM)) { } else if (headers.containsKey(AuthConstants.ENCODED_PEM)) {
String encodedPem = headers.get(AuthConstants.ENCODED_PEM); String encodedPem = headers.get(AuthConstants.ENCODED_PEM);
@ -173,8 +169,7 @@ public class AuthenticationHandler extends AbstractHandler {
certificate.setSerial(""); certificate.setSerial("");
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent()); log.debug("Verify response:" + response.getContent());
} }

@ -17,11 +17,9 @@
*/ */
package org.wso2.carbon.apimgt.handlers.invoker; package org.wso2.carbon.apimgt.handlers.invoker;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
@ -32,7 +30,6 @@ import org.apache.http.util.EntityUtils;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -63,7 +60,7 @@ public class RESTInvoker {
.setConnectionManager(connectionManager) .setConnectionManager(connectionManager)
.setDefaultRequestConfig(defaultRequestConfig) .setDefaultRequestConfig(defaultRequestConfig)
.build(); .build();
if(log.isDebugEnabled()){ if (log.isDebugEnabled()) {
log.debug("REST client initialized with " + log.debug("REST client initialized with " +
"maxTotalConnection = " + maxTotalConnections + "maxTotalConnection = " + maxTotalConnections +
"maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute + "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute +
@ -72,14 +69,11 @@ public class RESTInvoker {
} }
public RESTResponse invokePOST(URI uri, Map<String, String> requestHeaders, String username, public RESTResponse invokePOST(URI uri, Map<String, String> requestHeaders, String payload) throws IOException {
String password, String payload) throws IOException {
HttpPost httpPost = null; HttpPost httpPost = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
Header[] headers;
int httpStatus; int httpStatus;
String contentType;
String output; String output;
try { try {
httpPost = new HttpPost(uri); httpPost = new HttpPost(uri);
@ -90,11 +84,9 @@ public class RESTInvoker {
httpPost.setHeader(header, requestHeaders.get(header)); httpPost.setHeader(header, requestHeaders.get(header));
} }
} }
response = sendReceiveRequest(httpPost, username, password); response = sendReceiveRequest(httpPost);
output = IOUtils.toString(response.getEntity().getContent()); output = IOUtils.toString(response.getEntity().getContent());
headers = response.getAllHeaders();
httpStatus = response.getStatusLine().getStatusCode(); httpStatus = response.getStatusLine().getStatusCode();
contentType = response.getEntity().getContentType().getValue();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoked POST " + uri.toString() + log.debug("Invoked POST " + uri.toString() +
" - Input payload: " + payload + " - Response message: " + output); " - Input payload: " + payload + " - Response message: " + output);
@ -108,21 +100,11 @@ public class RESTInvoker {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
return new RESTResponse(contentType, output, headers, httpStatus); return new RESTResponse(output, httpStatus);
} }
private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase, String username, String password) private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase)
throws IOException { throws IOException {
CloseableHttpResponse response; return client.execute(requestBase);
if (username != null && !username.equals("") && password != null) {
String combinedCredentials = username + ":" + password;
byte[] encodedCredentials = Base64.encodeBase64(combinedCredentials.getBytes(StandardCharsets.UTF_8));
requestBase.addHeader("Authorization", "Basic " + new String(encodedCredentials));
response = client.execute(requestBase);
} else {
response = client.execute(requestBase);
}
return response;
} }
} }

@ -17,40 +17,25 @@
*/ */
package org.wso2.carbon.apimgt.handlers.invoker; package org.wso2.carbon.apimgt.handlers.invoker;
import org.apache.http.Header;
/** /**
* RESTResponse class holds the data retrieved from the HTTP invoke response. * RESTResponse class holds the data retrieved from the HTTP invoke response.
*/ */
public class RESTResponse { public class RESTResponse {
private String contentType;
private String content; private String content;
private Header[] headers;
private int httpStatus; private int httpStatus;
/** /**
* Constructor * Constructor
* *
* @param contentType from the REST invoke response
* @param content from the REST invoke response * @param content from the REST invoke response
* @param headers from the REST invoke response
* @param httpStatus from the REST invoke response * @param httpStatus from the REST invoke response
*/ */
RESTResponse(String contentType, String content, Header[] headers, int httpStatus) { RESTResponse(String content, int httpStatus) {
this.contentType = contentType;
this.content = content; this.content = content;
this.headers = headers;
this.httpStatus = httpStatus; this.httpStatus = httpStatus;
} }
/**
* Get the content type of the EST invoke response
*
* @return String content type of the response
*/
public String getContentType() {
return contentType;
}
/** /**
* Get contents of the REST invoke response * Get contents of the REST invoke response
@ -61,15 +46,6 @@ public class RESTResponse {
return content; return content;
} }
/**
* Get headers of the REST invoke response
*
* @return headers of the REST invoke response
*/
public Header[] getHeaders() {
return headers;
}
/** /**
* Get the HTTP Status code from REST invoke response * Get the HTTP Status code from REST invoke response
* *

@ -59,6 +59,7 @@ public class Utils {
/** /**
* This method initializes the iot-api-config.xml file. * This method initializes the iot-api-config.xml file.
*
* @return IoTServerConfiguration Object based on the configuration file. * @return IoTServerConfiguration Object based on the configuration file.
*/ */
public static IOTServerConfiguration initConfig() { public static IOTServerConfiguration initConfig() {
@ -67,10 +68,11 @@ public class Utils {
/** /**
* This methods initialized the iot-api-config.xml from provided path. * This methods initialized the iot-api-config.xml from provided path.
*
* @param path The actual file path of iot-api-config.xml * @param path The actual file path of iot-api-config.xml
* @return The instance of the IOTServerConfiguration based on the configuration. * @return The instance of the IOTServerConfiguration based on the configuration.
*/ */
public static IOTServerConfiguration initConfig(String path){ public static IOTServerConfiguration initConfig(String path) {
try { try {
File file = new File(path); File file = new File(path);
Document doc = Utils.convertToDocument(file); Document doc = Utils.convertToDocument(file);
@ -145,15 +147,15 @@ public class Utils {
getClientSecretes(iotServerConfiguration, restInvoker); getClientSecretes(iotServerConfiguration, restInvoker);
} }
URI tokenUrl = new URI(iotServerConfiguration.getOauthTokenEndpoint()); URI tokenUrl = new URI(iotServerConfiguration.getOauthTokenEndpoint());
String tokenContent = "grant_type=password&username=" + iotServerConfiguration.getUsername()+ "&password=" + String tokenContent = "grant_type=password&username=" + iotServerConfiguration.getUsername() + "&password=" +
iotServerConfiguration.getPassword() + "&scope=activity-view"; iotServerConfiguration.getPassword() + "&scope=activity-view";
String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes()); String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes());
Map<String, String> tokenHeaders = new HashMap<>(); Map<String, String> tokenHeaders = new HashMap<>();
tokenHeaders.put("Authorization", tokenBasicAuth); tokenHeaders.put("Authorization", tokenBasicAuth);
tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded"); tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded");
RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, null, null, tokenContent); RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, tokenContent);
if(log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Token response:" + response.getContent()); log.debug("Token response:" + response.getContent());
} }
JSONObject jsonResponse = new JSONObject(response.getContent()); JSONObject jsonResponse = new JSONObject(response.getContent());
@ -168,6 +170,7 @@ public class Utils {
/** /**
* This method register an application to get the client key and secret. * This method register an application to get the client key and secret.
*
* @param iotServerConfiguration Instance of the IoTServerConfiguration. * @param iotServerConfiguration Instance of the IoTServerConfiguration.
* @throws APIMCertificateMGTException * @throws APIMCertificateMGTException
*/ */
@ -189,7 +192,7 @@ public class Utils {
dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE); dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE);
dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth); dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth);
URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint()); URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint());
RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, null, null, dcrContent); RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, dcrContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DCR response :" + response.getContent()); log.debug("DCR response :" + response.getContent());
} }

@ -78,7 +78,7 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
@Test(description = "Handle request with without device type", @Test(description = "Handle request with without device type",
dependsOnMethods = "testHandleRequestWithEmptyTransportHeader") dependsOnMethods = "testHandleRequestWithEmptyTransportHeader")
public void testHandleRequestWithURISyntaxError() throws Exception { public void testHandleRequestWithoutDeviceType() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration, boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
@ -87,7 +87,7 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
} }
@Test(description = "Handle request with device type URI with MDM ceritificate", @Test(description = "Handle request with device type URI with MDM ceritificate",
dependsOnMethods = "testHandleRequestWithURISyntaxError") dependsOnMethods = "testHandleRequestWithoutDeviceType")
public void testHandleSuccessfulRequestMDMCertificate() throws Exception { public void testHandleSuccessfulRequestMDMCertificate() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>(); HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert"); transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
@ -150,6 +150,70 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
this.mockClient.reset(); this.mockClient.reset();
} }
@Test(description = "Handle request with device type URI with Encoded Pem with invalid response",
dependsOnMethods = "testHandleSuccessRequestEncodedPem")
public void testHandleSuccessRequestEncodedPemInvalidResponse() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getInvalidResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/api/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with cert management exception ",
dependsOnMethods = "testHandleSuccessRequestEncodedPem")
public void testHandleRequestWithCertMgmtException() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/api/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with IO exception",
dependsOnMethods = "testHandleRequestWithCertMgmtException")
public void testHandleRequestWithIOException() throws Exception {
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/api/testdevice");
boolean response = this.handler.handleRequest(messageContext);
Assert.assertFalse(response);
this.mockClient.reset();
}
@Test(description = "Handle request with URI exception",
dependsOnMethods = "testHandleRequestWithIOException")
public void testHandleRequestWithURIException() throws Exception {
TestUtils.resetSystemProperties();
HashMap<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
AuthenticationHandler handler = new AuthenticationHandler();
boolean response = handler.handleRequest(createSynapseMessageContext("<empty/>", this.synapseConfiguration,
transportHeaders, "https://test.com/testservice/api/testdevice"));
Assert.assertFalse(response);
TestUtils.setSystemProperties();
}
@Test(description = "Handle response")
public void testHandleResponse() throws Exception {
boolean response = this.handler.handleResponse(null);
Assert.assertTrue(response);
}
private static MessageContext createSynapseMessageContext( private static MessageContext createSynapseMessageContext(
String payload, SynapseConfiguration config, HashMap<String, String> transportHeaders, String payload, SynapseConfiguration config, HashMap<String, String> transportHeaders,
String address) throws Exception { String address) throws Exception {
@ -228,6 +292,16 @@ public class AuthenticationHandlerTest extends BaseAPIHandlerTest {
return mockDCRResponse; return mockDCRResponse;
} }
private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException {
CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
BasicHttpEntity responseEntity = new BasicHttpEntity();
responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name())));
responseEntity.setContentType(TestUtils.CONTENT_TYPE);
mockDCRResponse.setEntity(responseEntity);
mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request"));
return mockDCRResponse;
}
private String getContent(String filePath) throws IOException { private String getContent(String filePath) throws IOException {
FileReader fileReader = new FileReader(filePath); FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader); BufferedReader bufferedReader = new BufferedReader(fileReader);

@ -41,7 +41,11 @@ public class MockClient extends CloseableHttpClient {
throws IOException { throws IOException {
if (this.responseCount < this.responses.size()) { if (this.responseCount < this.responses.size()) {
this.responseCount++; this.responseCount++;
return this.responses.get(this.responseCount - 1); CloseableHttpResponse response = this.responses.get(this.responseCount - 1);
if (response == null) {
throw new IOException("test exception");
}
return response;
} else { } else {
return new MockHttpResponse(); return new MockHttpResponse();
} }

Loading…
Cancel
Save