From 80c1a8c8caf351f40d870bafbd5bf8895629bdc6 Mon Sep 17 00:00:00 2001 From: megala21 Date: Mon, 16 Oct 2017 17:08:42 +0530 Subject: [PATCH 1/3] Adding some more test cases --- .../framework/AuthenticationException.java | 41 ----- .../AuthenticationFrameworkUtil.java | 11 +- .../AuthenticatorFrameworkException.java | 45 ------ .../framework/WebappAuthenticationValve.java | 8 +- .../framework/WebappAuthenticatorFactory.java | 9 +- .../oauth/OAuthTokenValidationException.java | 17 +- .../PermissionAuthorizationValve.java | 75 --------- .../authorizer/PermissionAuthorizer.java | 48 ------ .../authorizer/WebappTenantAuthorizer.java | 6 +- .../config/WebappAuthenticatorConfig.java | 11 -- .../impl/AuthenticatorConfigServiceImpl.java | 6 +- .../WebappAuthenticationValveTest.java | 149 ++++++++++++++++++ .../WebappAuthenticatorConfigTest.java | 28 +++- .../framework/util/TestRequest.java | 44 ++++++ .../src/test/resources/testng.xml | 1 + 15 files changed, 234 insertions(+), 265 deletions(-) delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java index dba70afda4..d4d50f7bf1 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationException.java @@ -22,53 +22,12 @@ public class AuthenticationException extends Exception { private static final long serialVersionUID = -3151279311929070297L; - private String errorMessage; - private int errorCode; - - public AuthenticationException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public AuthenticationException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public AuthenticationException(String msg, Exception nestedEx) { super(msg, nestedEx); - setErrorMessage(msg); - } - - public AuthenticationException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); } public AuthenticationException(String msg) { super(msg); - setErrorMessage(msg); - } - - public AuthenticationException() { - super(); } - public AuthenticationException(Throwable cause) { - super(cause); - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index 3d768ecff4..73e809fdd3 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java @@ -21,10 +21,8 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.owasp.encoder.Encode; import org.w3c.dom.Document; -import javax.servlet.http.HttpServletResponse; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -35,14 +33,7 @@ public class AuthenticationFrameworkUtil { private static final Log log = LogFactory.getLog(AuthenticationFrameworkUtil.class); - public static void handleNoMatchAuthScheme(Request request, Response response, String httpVerb, String version, - String context) { - String msg = "Resource is not matched for HTTP Verb: '" + httpVerb + "', API context: '" + context + - "', Version: '" + version + "' and RequestURI: '" + Encode.forHtml(request.getRequestURI()) + "'"; - handleResponse(request, response, HttpServletResponse.SC_FORBIDDEN, msg); - } - - public static void handleResponse(Request request, Response response, int statusCode, String payload) { + static void handleResponse(Request request, Response response, int statusCode, String payload) { response.setStatus(statusCode); String targetResponseContentType = request.getHeader(Constants.HTTPHeaders.HEADER_HTTP_ACCEPT); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java index 61d08dc1db..a62fe4d4e7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkException.java @@ -22,53 +22,8 @@ public class AuthenticatorFrameworkException extends Exception { private static final long serialVersionUID = -3151279311229070297L; - private String errorMessage; - private int errorCode; - - public AuthenticatorFrameworkException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public AuthenticatorFrameworkException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - public AuthenticatorFrameworkException(String msg, Exception nestedEx) { super(msg, nestedEx); - setErrorMessage(msg); - } - - public AuthenticatorFrameworkException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public AuthenticatorFrameworkException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public AuthenticatorFrameworkException() { - super(); - } - - public AuthenticatorFrameworkException(Throwable cause) { - super(cause); } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 5a357a3ab5..3dd4331ef5 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.webapp.authenticator.framework; +import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; @@ -85,7 +86,8 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { } private boolean isContextSkipped(Request request) { - String ctx = request.getContext().getPath(); + Context context = request.getContext(); + String ctx = context == null ? null :context.getPath(); if (ctx == null || "".equals(ctx)) { ctx = request.getContextPath(); if (ctx == null || "".equals(ctx)) { @@ -105,6 +107,9 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { private boolean isNonSecuredEndPoint(Request request) { String uri = request.getRequestURI(); + if (uri == null) { + uri = ""; + } if(!uri.endsWith("/")) { uri = uri + "/"; } @@ -147,6 +152,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { log.debug(msg + " , API : " + Encode.forUriComponent(request.getRequestURI())); } AuthenticationFrameworkUtil. + handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); break; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java index 4222b1a629..46e0e77b31 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -24,14 +24,9 @@ import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFram import java.util.Map; -public class WebappAuthenticatorFactory { +class WebappAuthenticatorFactory { - public static WebappAuthenticator getAuthenticator(String authScheme) { - return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository(). - getAuthenticator(authScheme); - } - - public static WebappAuthenticator getAuthenticator(Request request) { + static WebappAuthenticator getAuthenticator(Request request) { Map authenticators = AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); for (WebappAuthenticator authenticator : authenticators.values()) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java index 42dbfe417c..9976c5b6c2 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java @@ -29,19 +29,4 @@ public class OAuthTokenValidationException extends Exception { super(msg, nestedEx); } - public OAuthTokenValidationException(String message, Throwable cause) { - super(message, cause); - } - - public OAuthTokenValidationException(String msg) { - super(msg); - } - - public OAuthTokenValidationException() { - super(); - } - - public OAuthTokenValidationException(Throwable cause) { - super(cause); - } -} +} \ No newline at end of file diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java deleted file mode 100644 index c8abdab444..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2015, 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.authorizer; - -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; -import org.wso2.carbon.tomcat.ext.valves.CompositeValve; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; - -import javax.servlet.http.HttpServletResponse; - -public class PermissionAuthorizationValve extends CarbonTomcatValve { - - private static final Log log = LogFactory.getLog(PermissionAuthorizationValve.class); - private static final String AUTHORIZATION_ENABLED = "authorization-enabled"; - - - @Override - public void invoke(Request request, Response response, CompositeValve compositeValve) { - - String permissionStatus = request.getContext().findParameter(AUTHORIZATION_ENABLED); - if (permissionStatus == null || permissionStatus.isEmpty()) { - this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); - return; - } - // check whether the permission checking function is enabled in web.xml - boolean isEnabled = Boolean.valueOf(permissionStatus); - if (!isEnabled) { - this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); - return; - } - - if (log.isDebugEnabled()) { - log.debug("Checking permission of request: " + request.getRequestURI()); - } - PermissionAuthorizer permissionAuthorizer = new PermissionAuthorizer(); - WebappAuthenticator.Status status = permissionAuthorizer.authorize(request, response); - this.processResponse(request, response, compositeValve, status); - } - - private void processResponse(Request request, Response response, CompositeValve compositeValve, - WebappAuthenticator.Status status) { - switch (status) { - case SUCCESS: - case CONTINUE: - this.getNext().invoke(request, response, compositeValve); - break; - case FAILURE: - String msg = "Failed to authorize incoming request"; - log.error(msg); - AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - break; - } - } -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java deleted file mode 100644 index c17d6fcc6a..0000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2015, 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.authorizer; - -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.owasp.encoder.Encode; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; -import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; -import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.webapp.authenticator.framework.Constants; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; - -import java.util.Properties; - -/** - * This class represents the methods that are used to authorize requests. - */ -public class PermissionAuthorizer { - - private static final Log log = LogFactory.getLog(PermissionAuthorizer.class); - - public WebappAuthenticator.Status authorize(Request request, Response response) { - - return WebappAuthenticator.Status.SUCCESS; - } - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java index 26d8ff995d..1b6aef18ae 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/WebappTenantAuthorizer.java @@ -43,10 +43,10 @@ public class WebappTenantAuthorizer { } private static boolean isProviderTenant(Request request, String requestTenantDomain) { - Object tenantDoamin = request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); + Object tenantDomain = request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); String param = null; - if (tenantDoamin != null) { - param = (String)request.getServletContext().getAttribute(PROVIDER_TENANT_DOMAIN_PARAM_NAME); + if (tenantDomain != null) { + param = (String)tenantDomain; } return (param == null || requestTenantDomain.equals(param)); } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java index 007eef108d..67ab3ef49a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/WebappAuthenticatorConfig.java @@ -88,15 +88,4 @@ public class WebappAuthenticatorConfig { } } - private static Schema getSchema() throws AuthenticatorFrameworkException { - try { - File deviceManagementSchemaConfig = new File(WebappAuthenticatorConfig.AUTHENTICATOR_CONFIG_SCHEMA_PATH); - SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - return factory.newSchema(deviceManagementSchemaConfig); - } catch (SAXException e) { - throw new AuthenticatorFrameworkException("Error occurred while initializing the schema of " + - "webapp-authenticator-config.xml", e); - } - } - } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java index 702a5cbc9e..0cc7017557 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/config/impl/AuthenticatorConfigServiceImpl.java @@ -34,7 +34,7 @@ public class AuthenticatorConfigServiceImpl implements AuthenticatorConfigServic public AuthenticatorConfig getAuthenticatorConfig(String authenticatorName) throws InvalidConfigurationStateException { List configs = WebappAuthenticatorConfig.getInstance().getAuthenticators(); - int index = 0; + int index; if (authenticatorName == null || authenticatorName.isEmpty()) { return null; } @@ -42,9 +42,9 @@ public class AuthenticatorConfigServiceImpl implements AuthenticatorConfigServic AuthenticatorConfig authenticatorConfig = configs.get(i); if (authenticatorName.equals(authenticatorConfig.getName())) { index = i; - break; + return configs.get(index); } } - return configs.get(index); + return null; } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java new file mode 100644 index 0000000000..1340993c9b --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java @@ -0,0 +1,149 @@ +/* + * 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; + +import org.apache.catalina.Context; +import org.apache.catalina.connector.Connector; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.catalina.core.StandardContext; +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.tomcat.ext.valves.CompositeValve; +import org.wso2.carbon.webapp.authenticator.framework.util.TestRequest; + +import javax.servlet.http.HttpServletResponse; +import java.lang.reflect.Field; +import java.util.Base64; + +import static org.wso2.carbon.security.SecurityConstants.ADMIN_USER; + +/** + * This is a test class for {@link WebappAuthenticationValve}. + */ +public class WebappAuthenticationValveTest { + private WebappAuthenticationValve webappAuthenticationValve; + private CompositeValve compositeValve; + + @BeforeClass() + public void setup() { + webappAuthenticationValve = new WebappAuthenticationValve(); + compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + } + + @Test(description = "This method tests the invoke method of the WebAppAuthenticationValve with the context path " + + "starting with carbon") + public void testInvokeWithContextSkippedScenario1() { + Request request = new Request(); + Context context = new StandardContext(); + context.setPath("carbon"); + CompositeValve compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + + request = new TestRequest("", "test"); + context = new StandardContext(); + compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + } + + @Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when " + + "un-secured endpoints are invoked.") + public void testInvokeUnSecuredEndpoints() { + Request request = new TestRequest("", "test"); + Context context = new StandardContext(); + context.setPath("carbon1"); + context.addParameter("doAuthentication", String.valueOf(true)); + context.addParameter("nonSecuredEndPoints", "test, test1"); + CompositeValve compositeValve = Mockito.mock(CompositeValve.class); + Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); + request.setContext(context); + webappAuthenticationValve.invoke(request, null, compositeValve); + } + + @Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when " + + "secured endpoints are invoked.") + public void testInvokeSecuredEndpoints() throws NoSuchFieldException, IllegalAccessException { + String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes())); + Request request = createRequest("basic " + encodedString); + webappAuthenticationValve.invoke(request, null, compositeValve); + + encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER + "test").getBytes())); + request = createRequest("basic " + encodedString); + Response response = new Response(); + org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response(); + Connector connector = new Connector(); + response.setConnector(connector); + response.setCoyoteResponse(coyoteResponse); + webappAuthenticationValve.invoke(request, response, compositeValve); + Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED, + "Response of un-authorized request is not updated"); + } + + @Test(description = "This method tests the behaviour of invoke method when the request does not satisfy any " + + "authenticator requirements") + public void testInvokeWithoutProperAuthenticator() throws NoSuchFieldException, IllegalAccessException { + Request request = createRequest("basic"); + Response response = new Response(); + org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response(); + Connector connector = new Connector(); + response.setConnector(connector); + response.setCoyoteResponse(coyoteResponse); + webappAuthenticationValve.invoke(request, response, compositeValve); + Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED, + "Response of un-authorized request is not updated"); + } + + /** + * To create a request with the given authorization header + * + * @param authorizationHeader Authorization header + * @return the relevant request. + * @throws IllegalAccessException Illegal Access Exception. + * @throws NoSuchFieldException No Such Field Exception. + */ + private Request createRequest(String authorizationHeader) throws IllegalAccessException, NoSuchFieldException { + Request request = new TestRequest("", ""); + Context context = new StandardContext(); + context.addParameter("basicAuth", "true"); + context.addParameter("managed-api-enabled", "true"); + context.setPath("carbon1"); + context.addParameter("doAuthentication", String.valueOf(true)); + request.setContext(context); + + MimeHeaders mimeHeaders = new MimeHeaders(); + MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER); + bytes.setString(authorizationHeader); + Field headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); + headersField.setAccessible(true); + org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request(); + 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/WebappAuthenticatorConfigTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java index 637a46598a..57cb61101c 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorConfigTest.java @@ -18,16 +18,15 @@ */ package org.wso2.carbon.webapp.authenticator.framework; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.utils.ServerConstants; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkException; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; +import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfigService; import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig; +import org.wso2.carbon.webapp.authenticator.framework.config.impl.AuthenticatorConfigServiceImpl; import java.util.List; @@ -42,10 +41,8 @@ public class WebappAuthenticatorConfigTest { public void testConfigInitialization() { try { WebappAuthenticatorConfig.init(); - WebappAuthenticatorConfig config = WebappAuthenticatorConfig.getInstance(); Assert.assertNotNull(config); - List authConfigs = config.getAuthenticators(); Assert.assertNotNull(authConfigs); } catch (AuthenticatorFrameworkException e) { @@ -56,6 +53,27 @@ public class WebappAuthenticatorConfigTest { } } + + @Test(description = "This method tests getAuthenticatorConfig method of AuthenticatorConfigService", + dependsOnMethods = {"testConfigInitialization"}) + public void getAuthenticatorConfigTest() { + AuthenticatorConfigService authenticatorConfigService = new AuthenticatorConfigServiceImpl(); + AuthenticatorConfig authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig("BasicAuth"); + Assert.assertNotNull(authenticatorConfig, + "Added authenticator config for the BasicAuth authenticator cannot be retrieved successfully"); + Assert.assertEquals(authenticatorConfig.getClassName(), + "org.wso2.carbon.webapp.authenticator.framework" + ".authenticator.BasicAuthAuthenticator", + "Class name related with Basic Auth does not match with " + + "the class name specified in the configuration"); + authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig(null); + Assert.assertNull(authenticatorConfig, + "Authenticator is retrieved even when the authenticator name is given as null"); + authenticatorConfig = authenticatorConfigService.getAuthenticatorConfig("non-existing"); + Assert.assertNull(authenticatorConfig, + "Authenticator is retrieved for a non-existing authenticator"); + + } + @AfterClass public void cleanup() { System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, ""); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java new file mode 100644 index 0000000000..6b5b8cb85b --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/util/TestRequest.java @@ -0,0 +1,44 @@ +/* + * 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.Request; + +/** + * This is a test class implementation of {@link Request} + */ +public class TestRequest extends Request { + private String contextPath; + private String requestURI; + + public TestRequest(String contextPath, String requestURI) { + this.contextPath = contextPath; + this.requestURI = requestURI; + } + + @Override + public String getContextPath() { + return contextPath; + } + + @Override + public String getRequestURI() { + return requestURI; + } +} 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 c9f3f8ad68..bb43e50bdc 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 @@ -34,6 +34,7 @@ + From 75bb02ac4a40ca7ffd22c4b128636809d2e5b0d4 Mon Sep 17 00:00:00 2001 From: megala21 Date: Mon, 16 Oct 2017 17:13:43 +0530 Subject: [PATCH 2/3] Refactoring --- .../authenticator/oauth/OAuthTokenValidationException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java index 9976c5b6c2..96de132910 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/oauth/OAuthTokenValidationException.java @@ -29,4 +29,4 @@ public class OAuthTokenValidationException extends Exception { super(msg, nestedEx); } -} \ No newline at end of file +} From ab54dda56c7b2d765d864b7042e8cf2b37606a93 Mon Sep 17 00:00:00 2001 From: megala21 Date: Tue, 17 Oct 2017 09:36:59 +0530 Subject: [PATCH 3/3] Refactoring --- .../framework/WebappAuthenticationValve.java | 36 +++++++++---------- .../WebappAuthenticationValveTest.java | 3 -- 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 3dd4331ef5..c1cf0897dc 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -110,7 +110,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { if (uri == null) { uri = ""; } - if(!uri.endsWith("/")) { + if (!uri.endsWith("/")) { uri = uri + "/"; } String contextPath = request.getContextPath(); @@ -125,7 +125,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { while (tokenizer.hasMoreTokens()) { skippedEndPoint = tokenizer.nextToken(); skippedEndPoint = skippedEndPoint.replace("\n", "").replace("\r", "").trim(); - if(!skippedEndPoint.endsWith("/")) { + if (!skippedEndPoint.endsWith("/")) { skippedEndPoint = skippedEndPoint + "/"; } nonSecuredEndpoints.put(skippedEndPoint, "true"); @@ -138,23 +138,21 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { private void processRequest(Request request, Response response, CompositeValve compositeValve, AuthenticationInfo authenticationInfo) { switch (authenticationInfo.getStatus()) { - case SUCCESS: - case CONTINUE: - this.getNext().invoke(request, response, compositeValve); - break; - case FAILURE: - String msg = "Failed to authorize incoming request"; - if (authenticationInfo.getMessage() != null && !authenticationInfo.getMessage().isEmpty()) { - msg = authenticationInfo.getMessage(); - response.setHeader("WWW-Authenticate", msg); - } - if (log.isDebugEnabled()) { - log.debug(msg + " , API : " + Encode.forUriComponent(request.getRequestURI())); - } - AuthenticationFrameworkUtil. - - handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - break; + case SUCCESS: + case CONTINUE: + this.getNext().invoke(request, response, compositeValve); + break; + case FAILURE: + String msg = "Failed to authorize incoming request"; + if (authenticationInfo.getMessage() != null && !authenticationInfo.getMessage().isEmpty()) { + msg = authenticationInfo.getMessage(); + response.setHeader("WWW-Authenticate", msg); + } + if (log.isDebugEnabled()) { + log.debug(msg + " , API : " + Encode.forUriComponent(request.getRequestURI())); + } + AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); + break; } } } \ No newline at end of file diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java index 1340993c9b..69cbac221a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/test/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValveTest.java @@ -63,7 +63,6 @@ public class WebappAuthenticationValveTest { Mockito.doNothing().when(compositeValve).continueInvocation(Mockito.any(), Mockito.any()); request.setContext(context); webappAuthenticationValve.invoke(request, null, compositeValve); - request = new TestRequest("", "test"); context = new StandardContext(); compositeValve = Mockito.mock(CompositeValve.class); @@ -92,7 +91,6 @@ public class WebappAuthenticationValveTest { String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes())); Request request = createRequest("basic " + encodedString); webappAuthenticationValve.invoke(request, null, compositeValve); - encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER + "test").getBytes())); request = createRequest("basic " + encodedString); Response response = new Response(); @@ -135,7 +133,6 @@ public class WebappAuthenticationValveTest { context.setPath("carbon1"); context.addParameter("doAuthentication", String.valueOf(true)); request.setContext(context); - MimeHeaders mimeHeaders = new MimeHeaders(); MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER); bytes.setString(authorizationHeader);