Adding some more test cases

revert-70aa11f8
megala21 7 years ago
parent 48bc9b661d
commit 80c1a8c8ca

@ -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);
}
}

@ -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);

@ -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);
}
}

@ -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;
}

@ -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<String, WebappAuthenticator> authenticators =
AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators();
for (WebappAuthenticator authenticator : authenticators.values()) {

@ -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);
}
}
}

@ -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;
}
}
}

@ -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;
}
}

@ -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));
}

@ -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);
}
}
}

@ -34,7 +34,7 @@ public class AuthenticatorConfigServiceImpl implements AuthenticatorConfigServic
public AuthenticatorConfig getAuthenticatorConfig(String authenticatorName) throws
InvalidConfigurationStateException {
List<AuthenticatorConfig> 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;
}
}

@ -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;
}
}

@ -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<AuthenticatorConfig> 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, "");

@ -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;
}
}

@ -34,6 +34,7 @@
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticatorTest" />
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.CertificateAuthenticatorTest" />
<class name="org.wso2.carbon.webapp.authenticator.framework.internal.WebappAuthenticatorFrameworkServiceComponentTest"/>
<class name="org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationValveTest"/>
</classes>
</test>

Loading…
Cancel
Save