diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java index 06c0a3a0fb..0d177c6c26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerNegativeTest.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.h2.jdbcx.JdbcDataSource; import org.mockito.Mockito; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.common.Device; @@ -69,7 +69,7 @@ public class DeviceTypeManagerNegativeTest { private PropertyBasedPluginDAOImpl propertyBasedPluginDAO; private Device sampleDevice; - @BeforeTest + @BeforeClass public void setup() throws SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java index f90d33bd34..b512a2965d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerServiceTest.java @@ -21,14 +21,16 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.mockito.Mockito; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; import org.wso2.carbon.device.mgt.common.InitialOperationConfig; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.license.mgt.License; @@ -75,7 +77,7 @@ public class DeviceTypeManagerServiceTest { private Method setPolicyMonitoringManager; private Method setPullNotificationSubscriber; - @BeforeTest + @BeforeClass public void setup() throws NoSuchMethodException, SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException, DeviceManagementException, RegistryException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java index d6f732cf13..49a6a7c9ff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/DeviceTypeManagerTest.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.mockito.Mockito; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -73,7 +73,7 @@ public class DeviceTypeManagerTest { private String[] customDeviceTypeProperties = {"custom_property", "custom_property2"}; private final String SQL_FOLDER = "sql-files" + File.separator; - @BeforeTest(description = "Mocking the classes for testing") + @BeforeClass(description = "Mocking the classes for testing") public void setup() throws NoSuchFieldException, IllegalAccessException, IOException, SQLException, SAXException, ParserConfigurationException, DeviceTypeConfigurationException, JAXBException { ClassLoader classLoader = getClass().getClassLoader(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java index b6beda3c2c..09435166dc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/device/type/template/HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest.java @@ -19,7 +19,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -60,7 +60,7 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest { private String androidSenseDeviceType = "androidsense"; private DeviceManagementService generatedDeviceManagementService; - @BeforeTest + @BeforeClass public void setup() throws RegistryException, IOException, SAXException, ParserConfigurationException, DeviceTypeConfigurationException, JAXBException { createSampleDeviceTypeMetaDefinition(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java index 96f4c28694..feb549a22f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/test/java/org/wso2/carbon/device/mgt/extensions/utils/UtilsTest.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.utils; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -51,7 +51,7 @@ import java.util.List; public class UtilsTest { private FileSystemBasedLicenseManager fileSystemBasedLicenseManager; - @BeforeTest + @BeforeClass public void setup() { fileSystemBasedLicenseManager = new FileSystemBasedLicenseManager(); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml index 624cc1fe0d..1339cc580e 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/pom.xml @@ -248,6 +248,11 @@ h2-database-engine test + + org.powermock + powermock-api-mockito + test + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java index 95fbc86a44..5d22e52056 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/OAuthTokenValidationStubFactory.java @@ -97,44 +97,6 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory { return connectionManager; } - /** - * Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs - * - * @param properties Properties to configure PoolingHttpClientConnectionManager - * @return An instance of properly configured PoolingHttpClientConnectionManager - */ - private HttpClientConnectionManager createClientConnectionManager(Properties properties) { - PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); - if (properties != null) { - String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost"); - if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " + - "which is 2, will be used"); - } - } else { - connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam)); - } - - String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections"); - if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " + - "which is 10, will be used"); - } - } else { - connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam)); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the " + - "HttpClient used in OAuth token validation service stub instances are not provided. " + - "Therefore, the defaults, 2/10 respectively, will be used"); - } - } - return connectionManager; - } - @Override public Object makeObject() throws Exception { return this.createStub(); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java index db3b71ba7c..52510d5b67 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java @@ -134,10 +134,10 @@ public class Utils { authenticationInfo.setUsername(username); authenticationInfo.setTenantDomain(tenantDomain); authenticationInfo.setTenantId(getTenantIdOFUser(username + "@" + tenantDomain)); - if (oAuthValidationResponse.isValid()) - authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE); + authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE); } else { authenticationInfo.setMessage(oAuthValidationResponse.getErrorMsg()); + authenticationInfo.setStatus(WebappAuthenticator.Status.FAILURE); } return authenticationInfo; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 3339ad8ceb..99fd36d534 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -18,7 +18,6 @@ package org.wso2.carbon.webapp.authenticator.framework.authenticator; -import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.SignedJWT; @@ -46,6 +45,7 @@ import java.security.interfaces.RSAPublicKey; import java.text.ParseException; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Properties; import java.util.StringTokenizer; @@ -164,8 +164,6 @@ public class JWTAuthenticator implements WebappAuthenticator { log.error("Error occurred while obtaining the user.", e); } catch (ParseException e) { log.error("Error occurred while parsing the JWT header.", e); - } catch (JOSEException e) { - log.error("Error occurred while verifying the JWT header.", e); } catch (Exception e) { log.error("Error occurred while verifying the JWT header.", e); } finally { @@ -203,12 +201,12 @@ public class JWTAuthenticator implements WebappAuthenticator { private String tenantDomain; private final String DEFAULT_ISSUER = "default"; - public IssuerAlias(String tenantDomain) { + IssuerAlias(String tenantDomain) { this.issuer = DEFAULT_ISSUER; this.tenantDomain = tenantDomain; } - public IssuerAlias(String issuer, String tenantDomain) { + IssuerAlias(String issuer, String tenantDomain) { this.issuer = issuer; this.tenantDomain = tenantDomain; } @@ -223,7 +221,7 @@ public class JWTAuthenticator implements WebappAuthenticator { @Override public boolean equals(Object obj) { return (obj instanceof IssuerAlias) && issuer.equals( - ((IssuerAlias) obj).issuer) && tenantDomain == ((IssuerAlias) obj).tenantDomain; + ((IssuerAlias) obj).issuer) && Objects.equals(tenantDomain, ((IssuerAlias) obj).tenantDomain); } } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java index 6a0422903b..cbd53b1b83 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/LocalOAuthValidator.java @@ -68,11 +68,11 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { tenantDomain = MultitenantUtils.getTenantDomain(userName); } + return new OAuthValidationResponse(userName, tenantDomain, true); } else { OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse(); oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg()); return oAuthValidationResponse; } - return new OAuthValidationResponse(userName,tenantDomain,isValid); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java index 7700941382..44488fd3f8 100755 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/impl/RemoteOAuthValidator.java @@ -55,42 +55,41 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator { try { OAuth2TokenValidationRequestDTO validationRequest = createValidationRequest(accessToken, resource); stub = (OAuth2TokenValidationServiceStub) this.stubs.borrowObject(); - validationResponse = - stub.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + validationResponse = stub.findOAuthConsumerIfTokenIsValid(validationRequest) + .getAccessTokenValidationResponse(); } catch (RemoteException e) { - throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " + - "IS server for OAuth2 token validation.", e); + throw new OAuthTokenValidationException( + "Remote Exception occurred while invoking the Remote " + "IS server for OAuth2 token validation.", + e); } catch (Exception e) { - throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " + - "service stub from the pool", e); + throw new OAuthTokenValidationException( + "Error occurred while borrowing an oauth token validation " + "service stub from the pool", e); } finally { try { this.stubs.returnObject(stub); } catch (Exception e) { - log.warn("Error occurred while returning the object back to the oauth token validation service " + - "stub pool", e); + log.warn("Error occurred while returning the object back to the oauth token validation service " + + "stub pool", e); } } - if (validationResponse == null) { if (log.isDebugEnabled()) { log.debug("Response returned by the OAuth token validation service is null"); } return null; } - boolean isValid = validationResponse.getValid(); String tenantDomain; String username; if (isValid) { username = MultitenantUtils.getTenantAwareUsername(validationResponse.getAuthorizedUser()); tenantDomain = MultitenantUtils.getTenantDomain(validationResponse.getAuthorizedUser()); + return new OAuthValidationResponse(username, tenantDomain, true); } else { OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse(); oAuthValidationResponse.setErrorMsg(validationResponse.getErrorMsg()); return oAuthValidationResponse; } - return new OAuthValidationResponse(username, tenantDomain, isValid); } private OAuth2TokenValidationRequestDTO createValidationRequest(String accessToken, String resource) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java index 9eeaca651f..66ab2e2871 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BSTAuthenticatorTest.java @@ -19,12 +19,29 @@ package org.wso2.carbon.webapp.authenticator.framework.authenticator; +import org.apache.catalina.Context; +import org.apache.catalina.connector.Request; +import org.apache.catalina.core.StandardContext; +import org.apache.commons.io.FileUtils; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.mockito.Mockito; import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; +import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; +import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.webapp.authenticator.framework.util.TestInputBuffer; +import java.io.File; +import java.io.IOException; import java.lang.reflect.Field; +import java.net.URL; import java.util.Properties; /** @@ -33,11 +50,29 @@ import java.util.Properties; public class BSTAuthenticatorTest { private BSTAuthenticator bstAuthenticator; private Properties properties; + private Field headersField; + private OAuth2TokenValidationService oAuth2TokenValidationService; + private OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO; - @BeforeTest - public void init() { + @BeforeClass + public void init() throws NoSuchFieldException { bstAuthenticator = new BSTAuthenticator(); properties = new Properties(); + headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + oAuth2TokenValidationService = Mockito + .mock(OAuth2TokenValidationService.class, Mockito.CALLS_REAL_METHODS); + oAuth2ClientApplicationDTO = Mockito + .mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS); + + OAuth2TokenValidationResponseDTO authorizedValidationResponse = new OAuth2TokenValidationResponseDTO(); + authorizedValidationResponse.setValid(true); + authorizedValidationResponse.setAuthorizedUser("admin@" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + + Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService) + .findOAuthConsumerIfTokenIsValid(Mockito.any()); + oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(authorizedValidationResponse); + AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService); } @Test(description = "This test case is used to test the behaviour of BST Authenticator when the properties are " @@ -89,4 +124,125 @@ public class BSTAuthenticatorTest { Assert.assertNotNull(oAuth2TokenValidator, "Token validation creation failed even with the required " + "parameters."); } + + @Test(description = "This method tests the get methods of the BST Authenticator", + dependsOnMethods = {"testInitWithRemote"}) + public void testGetterMethods() { + Assert.assertNotNull(bstAuthenticator.getProperties(), "Retrieval of properties from BSTAuthenticator failed"); + Assert.assertNotNull(bstAuthenticator.getProperty("Password"), + "Retrieval of added property failed in " + "BSTAuthenticator"); + Assert.assertNull(bstAuthenticator.getProperty("test"), + "Retrieval of property test is successful, which is " + "never added"); + Assert.assertEquals(bstAuthenticator.getName(), "BSTAuthenticator", + "Name returned by BSTAuthenticator does" + " not match."); + } + + @Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions") + public void testCanHandleWithFalseConditions() throws IllegalAccessException { + Request request = new Request(); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + request.setCoyoteRequest(coyoteRequest); + Assert.assertFalse(bstAuthenticator.canHandle(request), + "BST Authenticator can handle a request without content type"); + + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue("content-type"); + bytes.setString("test"); + headersField.set(coyoteRequest, mimeHeaders); + request.setCoyoteRequest(coyoteRequest); + Assert.assertFalse(bstAuthenticator.canHandle(request), + "BST Authenticator can handle a request with content type test"); + } + + + @Test(description = "This test case tests the canHandle method of the BSTAuthenticator under valid conditions") + public void testCanHandleWithValidRequest() throws IOException, IllegalAccessException { + Request request = createSoapRequest("CorrectBST.xml"); + Assert.assertTrue(bstAuthenticator.canHandle(request), "BST Authenticator cannot handle a valid " + + "authentication request"); + } + + @Test(description = "This test case tests the canHandle method of the BSTAuthenticator under missing soap headers") + public void testCanHandleWithMissingHeaders() throws IOException, IllegalAccessException { + Request request = createSoapRequest("WrongBST1.xml"); + Assert.assertFalse(bstAuthenticator.canHandle(request), + "BST Authenticator can handle a request with missing headers "); + request = createSoapRequest("WrongBST2.xml"); + Assert.assertFalse(bstAuthenticator.canHandle(request), + "BST Authenticator can handle a request with missing headers "); + } + + @Test(description = "This method tests the authenticate method of BST Authenticator when only minimal information" + + " is provided") + public void testAuthenticateWithMinimalConditions() throws NoSuchFieldException, IllegalAccessException { + Request request = new Request(); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + request.setCoyoteRequest(coyoteRequest); + AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE, + "Authentication status of authentication info is wrong"); + } + + @Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant " + + "details", dependsOnMethods = "testInitWithRemote") + public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException { + Request request = createSoapRequest("CorrectBST.xml"); + org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest(); + Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB"); + uriMB.setAccessible(true); + MessageBytes bytes = MessageBytes.newInstance(); + bytes.setString("test"); + uriMB.set(coyoteRequest, bytes); + request.setCoyoteRequest(coyoteRequest); + bstAuthenticator.canHandle(request); + AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE, + "Authentication status of authentication info is wrong"); + Assert.assertEquals(authenticationInfo.getUsername(), "admin", + "User name in the authentication info is different than original user"); + OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO(); + unAuthorizedValidationRespose.setValid(false); + unAuthorizedValidationRespose.setErrorMsg("User is not authorized"); + Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService) + .findOAuthConsumerIfTokenIsValid(Mockito.any()); + oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose); + AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService); + authenticationInfo = bstAuthenticator.authenticate(request, null); + Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE, + "Un-authorized user got authenticated with BST"); + } + + /** + * To create a soap request by reading the request from given file. + * + * @param fileName Name of the file that has the soap request content. + * @return Request created with soap content. + * @throws IllegalAccessException Illegal Access Exception. + * @throws IOException IO Exception. + */ + private Request createSoapRequest(String fileName) throws IllegalAccessException, IOException { + Request request = new Request(); + ClassLoader classLoader = getClass().getClassLoader(); + URL resourceUrl = classLoader + .getResource("requests" + File.separator + "BST" + File.separator + fileName); + String bstRequestContent = null; + if (resourceUrl != null) { + File bst = new File(resourceUrl.getFile()); + bstRequestContent = FileUtils.readFileToString(bst); + } + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue("content-type"); + bytes.setString("application/xml"); + bytes = mimeHeaders.addValue("custom"); + bytes.setString(bstRequestContent); + headersField.set(coyoteRequest, mimeHeaders); + TestInputBuffer inputBuffer = new TestInputBuffer(); + coyoteRequest.setInputBuffer(inputBuffer); + Context context = new StandardContext(); + request.setContext(context); + request.setCoyoteRequest(coyoteRequest); + return request; + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java index 2553f04423..91ac4abab9 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticatorTest.java @@ -26,6 +26,7 @@ import org.apache.commons.codec.EncoderException; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.testng.Assert; +import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; @@ -51,7 +52,7 @@ public class BasicAuthAuthenticatorTest { private MessageBytes bytes; private final String BASIC_HEADER = "basic "; - @BeforeTest + @BeforeClass public void init() throws NoSuchFieldException { basicAuthAuthenticator = new BasicAuthAuthenticator(); headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java new file mode 100644 index 0000000000..24deab4123 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OauthAuthenticatorTest.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2017, 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.carbon.webapp.authenticator.framework.authenticator; + +import org.apache.catalina.connector.Request; +import org.apache.commons.pool.impl.GenericObjectPool; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.carbon.core.security.AuthenticatorsConfiguration; +import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import org.wso2.carbon.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest; +import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Properties; + +/** + * This is a test case for {@link OAuthAuthenticator} + */ +public class OauthAuthenticatorTest { + private OAuthAuthenticator oAuthAuthenticator; + private final String BEARER_HEADER = "bearer "; + private Field headersField; + private Properties properties; + + @BeforeClass + public void setup() + throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + oAuthAuthenticator = new OAuthAuthenticator(); + headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + } + + @Test(description = "This method tests the successful execution of init method") + public void testInit() throws NoSuchFieldException, IllegalAccessException { + properties = new Properties(); + properties.setProperty("TokenValidationEndpointUrl", "test"); + properties.setProperty("Username", "admin"); + properties.setProperty("Password", "admin"); + properties.setProperty("IsRemote", "true"); + properties.setProperty("MaxConnectionsPerHost", "100"); + properties.setProperty("MaxTotalConnections", "1000"); + Assert.assertNull(oAuthAuthenticator.getProperty("test"), + "OAuth authenticator is returning the properties that were never set"); + oAuthAuthenticator.setProperties(properties); + oAuthAuthenticator.init(); + Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator"); + tokenValidator.setAccessible(true); + Assert.assertNotNull(tokenValidator.get(oAuthAuthenticator), "OauthAuthenticator initialization failed"); + Assert.assertEquals(oAuthAuthenticator.getName(), "OAuth", "Name of the OauthAuthenticator does not match"); + } + + @Test(description = "This method tests the canHandle method of OAuthAuthenticator") + public void testCanHandle() throws IllegalAccessException { + Request request = createOauthRequest(BEARER_HEADER); + Assert.assertTrue(oAuthAuthenticator.canHandle(request), + "The request with the bearer authorization header cannot be handled by OauthAuthenticator"); + + request = createOauthRequest("test"); + Assert.assertFalse(oAuthAuthenticator.canHandle(request), + "The request without bearer authorization header can be handled by OauthAuthenticator"); + } + + @Test(description = "This method tests the authenticate under different parameters", + dependsOnMethods = {"testInit"}) + public void testAuthenticate() throws Exception { + Request request = createOauthRequest(BEARER_HEADER); + Assert.assertEquals(oAuthAuthenticator.authenticate(request, null).getStatus(), + WebappAuthenticator.Status.CONTINUE, "Authentication status mismatched"); + request = createOauthRequest(BEARER_HEADER + "abc"); + org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest(); + Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB"); + uriMB.setAccessible(true); + MessageBytes bytes = MessageBytes.newInstance(); + bytes.setString("test"); + uriMB.set(coyoteRequest, bytes); + request.setCoyoteRequest(coyoteRequest); + Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator"); + tokenValidator.setAccessible(true); + + GenericObjectPool genericObjectPool = Mockito.mock(GenericObjectPool.class, Mockito.CALLS_REAL_METHODS); + RemoteOAuthValidator remoteOAuthValidator = Mockito + .mock(RemoteOAuthValidator.class, Mockito.CALLS_REAL_METHODS); + tokenValidator.set(oAuthAuthenticator, remoteOAuthValidator); + Field stubs = RemoteOAuthValidator.class.getDeclaredField("stubs"); + stubs.setAccessible(true); + stubs.set(remoteOAuthValidator, genericObjectPool); + OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO(); + oAuth2TokenValidationResponseDTO.setValid(true); + oAuth2TokenValidationResponseDTO.setAuthorizedUser("admin@carbon.super"); + OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO = Mockito + .mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(oAuth2TokenValidationResponseDTO).when(oAuth2ClientApplicationDTO) + .getAccessTokenValidationResponse(); + OAuth2TokenValidationServiceStub oAuth2TokenValidationServiceStub = Mockito + .mock(OAuth2TokenValidationServiceStub.class, Mockito.CALLS_REAL_METHODS); + Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationServiceStub) + .findOAuthConsumerIfTokenIsValid(Mockito.any()); + Mockito.doReturn(oAuth2TokenValidationServiceStub).when(genericObjectPool).borrowObject(); + oAuthAuthenticator.canHandle(request); + AuthenticationInfo authenticationInfo = oAuthAuthenticator.authenticate(request, null); + Assert.assertEquals(authenticationInfo.getUsername(), "admin"); + + } + + @Test(description = "This method is used to test getProperty method of the OAuthAuthenticator", + dependsOnMethods = {"testInit"}) + public void testGetProperty() { + Assert.assertEquals(oAuthAuthenticator.getProperty("Username"), "admin", + "Username property of " + "OauthAuthenticator is not matching with the assigned one."); + Assert.assertEquals(oAuthAuthenticator.getProperties().size(), properties.size(), + "Property list assigned " + "does not match with retrieved list"); + } + + /** + * This will create an OAuth request. + * + * @param authorizationHeader Authorization Header + */ + private Request createOauthRequest(String authorizationHeader) throws IllegalAccessException { + Request request = new Request(); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER); + bytes.setString(authorizationHeader); + headersField.set(coyoteRequest, mimeHeaders); + request.setCoyoteRequest(coyoteRequest); + return request; + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestInputBuffer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestInputBuffer.java new file mode 100644 index 0000000000..7ded99b18a --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestInputBuffer.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017, 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.carbon.webapp.authenticator.framework.util; + +import org.apache.catalina.connector.InputBuffer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.coyote.Request; +import org.apache.tomcat.util.buf.ByteChunk; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.MimeHeaders; + +import java.io.IOException; +import java.lang.reflect.Field; + +/** + * This is a dummy implementation of {@link InputBuffer} for the test cases. + */ +public class TestInputBuffer implements org.apache.coyote.InputBuffer { + private Log log = LogFactory.getLog(TestInputBuffer.class); + + @Override + public int doRead(ByteChunk byteChunk, Request request) throws IOException { + String string = request.getHeader("custom"); + MimeHeaders mimeHeaders = new MimeHeaders(); + Field byteC = null; + try { + byteC = MessageBytes.class.getDeclaredField("byteC"); + byteC.setAccessible(true); + } catch (NoSuchFieldException e) { + log.error("Cannot get the byteC field", e); + } + MessageBytes bytes = mimeHeaders.addValue("content-type"); + try { + if (byteC != null) { + byteC.set(bytes, byteChunk); + } + } catch (IllegalAccessException e) { + log.error("Cannot set byteC field", e); + } + bytes.setString(string); + bytes.toBytes(); + return byteChunk.getLength(); + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/CorrectBST.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/CorrectBST.xml new file mode 100644 index 0000000000..9be7210ec6 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/CorrectBST.xml @@ -0,0 +1,25 @@ + + + + + test + + + + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST1.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST1.xml new file mode 100644 index 0000000000..b83635c6d1 --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST1.xml @@ -0,0 +1,25 @@ + + + + + + + + + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST2.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST2.xml new file mode 100644 index 0000000000..671d1e770e --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/requests/BST/WrongBST2.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml index 4ce2c1153a..d166d4b15e 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/resources/testng.xml @@ -30,6 +30,7 @@ +