Author: adc Date: Wed Jan 19 21:21:50 2005 New Revision: 125716 URL: http://svn.apache.org/viewcvs?view=rev&rev=125716 Log: JACC (JSR 115) authorization from Tomcat Web Container http://issues.apache.org/jira/browse/GERONIMO-314
Checkin of Jeff Genender. Added: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/JAASTomcatPrincipal.java geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatGeronimoRealm.java geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JAASSecurityTest.java geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JACCSecurityTest.java Removed: geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/SecurityTest.java Modified: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java Added: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/JAASTomcatPrincipal.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/JAASTomcatPrincipal.java?view=auto&rev=125716 ============================================================================== --- (empty file) +++ geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/JAASTomcatPrincipal.java Wed Jan 19 21:21:50 2005 @@ -0,0 +1,47 @@ +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + + +import java.security.Principal; +import java.util.Stack; +import javax.security.auth.Subject; + + +/** + * @version $Rev: 122776 $ $Date: 2004-12-19 12:11:07 -0700 (Sun, 19 Dec 2004) $ + */ +public class JAASTomcatPrincipal implements Principal { + private final String name; + private Subject subject; + + public JAASTomcatPrincipal(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public Subject getSubject() { + return subject; + } + + public void setSubject(Subject subject) { + this.subject = subject; + } +} Added: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatGeronimoRealm.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatGeronimoRealm.java?view=auto&rev=125716 ============================================================================== --- (empty file) +++ geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatGeronimoRealm.java Wed Jan 19 21:21:50 2005 @@ -0,0 +1,619 @@ +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.io.IOException; +import java.security.AccessControlContext; +import java.security.AccessControlException; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Principal; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import javax.security.auth.Subject; +import javax.security.auth.login.AccountExpiredException; +import javax.security.auth.login.CredentialExpiredException; +import javax.security.auth.login.FailedLoginException; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; +import javax.security.jacc.PolicyConfiguration; +import javax.security.jacc.PolicyConfigurationFactory; +import javax.security.jacc.PolicyContext; +import javax.security.jacc.PolicyContextException; +import javax.security.jacc.WebResourcePermission; +import javax.security.jacc.WebRoleRefPermission; +import javax.security.jacc.WebUserDataPermission; +import javax.servlet.http.HttpServletRequest; + +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.Response; +import org.apache.catalina.deploy.LoginConfig; +import org.apache.catalina.deploy.SecurityConstraint; +import org.apache.catalina.realm.JAASCallbackHandler; +import org.apache.catalina.realm.JAASRealm; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.geronimo.common.GeronimoSecurityException; +import org.apache.geronimo.security.ContextManager; +import org.apache.geronimo.security.IdentificationPrincipal; +import org.apache.geronimo.security.PrimaryRealmPrincipal; +import org.apache.geronimo.security.RealmPrincipal; +import org.apache.geronimo.security.SubjectId; +import org.apache.geronimo.security.deploy.DefaultPrincipal; +import org.apache.geronimo.security.deploy.Realm; +import org.apache.geronimo.security.deploy.Role; +import org.apache.geronimo.security.deploy.Security; +import org.apache.geronimo.security.jacc.PolicyContextHandlerContainerSubject; +import org.apache.geronimo.security.jacc.RoleMappingConfiguration; +import org.apache.geronimo.security.util.ConfigurationUtil; + + +public class TomcatGeronimoRealm extends JAASRealm { + + private static final Log log = LogFactory.getLog(TomcatGeronimoRealm.class); + + private String policyContextID = null; + private PolicyConfigurationFactory factory = null; + private PolicyConfiguration policyConfiguration = null; + private Subject defaultSubject = null; + private PermissionCollection checked = new Permissions(); + private Map roleDesignates = new HashMap(); + private String loginDomainName = null; + + private Context context = null; + private static ThreadLocal currentRequest = new ThreadLocal(); + + /** + * Descriptive information about this <code>Realm</code> implementation. + */ + protected static final String info = "org.apache.geronimo.tomcat.TomcatGeronimoRealm/1.0"; + + /** + * Descriptive information about this <code>Realm</code> implementation. + */ + protected static final String name = "TomcatGeronimoRealm"; + + public TomcatGeronimoRealm(String policyContextID, + Security securityConfig, + String loginDomainName, + Set securityRoles, + PermissionCollection uncheckedPermissions, + PermissionCollection excludedPermissions, + Map rolePermissions) throws PolicyContextException, ClassNotFoundException { + + this.policyContextID = policyContextID; + this.defaultSubject = generateDefaultSubject(securityConfig, loginDomainName); + + /** + * Register our default subject with the ContextManager + */ + ContextManager.registerSubject(defaultSubject); + SubjectId id = ContextManager.getSubjectId(defaultSubject); + defaultSubject.getPrincipals().add(new IdentificationPrincipal(id)); + + factory = PolicyConfigurationFactory.getPolicyConfigurationFactory(); + policyConfiguration = factory.getPolicyConfiguration(policyContextID, true); + + configure(uncheckedPermissions, excludedPermissions, rolePermissions); + addRoleMappings(securityRoles, loginDomainName, securityConfig, (RoleMappingConfiguration) policyConfiguration); + policyConfiguration.commit(); + this.loginDomainName = loginDomainName; + + Set allRolePermissions = new HashSet(); + for (Iterator iterator = rolePermissions.entrySet().iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + Set permissionsForRole = (Set) entry.getValue(); + allRolePermissions.addAll(permissionsForRole); + } + for (Iterator iterator = allRolePermissions.iterator(); iterator.hasNext();) { + Permission permission = (Permission) iterator.next(); + checked.add(permission); + } + } + + protected Subject generateDefaultSubject(Security securityConfig, String loginDomainName) + throws GeronimoSecurityException { + DefaultPrincipal defaultPrincipal = securityConfig.getDefaultPrincipal(); + if (defaultPrincipal == null) { + throw new GeronimoSecurityException("Unable to generate default principal"); + } + + Subject subject = new Subject(); + + RealmPrincipal realmPrincipal = ConfigurationUtil.generateRealmPrincipal(defaultPrincipal.getPrincipal(), loginDomainName, defaultPrincipal.getRealmName()); + if (realmPrincipal == null) { + throw new GeronimoSecurityException("Unable to create realm principal"); + } + PrimaryRealmPrincipal primaryRealmPrincipal = ConfigurationUtil.generatePrimaryRealmPrincipal(defaultPrincipal.getPrincipal(), loginDomainName, defaultPrincipal.getRealmName()); + if (primaryRealmPrincipal == null) { + throw new GeronimoSecurityException("Unable to create primary realm principal"); + } + + subject.getPrincipals().add(realmPrincipal); + subject.getPrincipals().add(primaryRealmPrincipal); + + return subject; + } + + + /** + * Enforce any user data constraint required by the security constraint + * guarding this request URI. Return <code>true</code> if this constraint + * was not violated and processing should continue, or <code>false</code> + * if we have created a response already. + * + * @param request Request we are processing + * @param response Response we are creating + * @param constraints Security constraint being checked + * @throws IOException if an input/output error occurs + */ + public boolean hasUserDataPermission(Request request, + Response response, + SecurityConstraint[] constraints) + throws IOException { + + //Set the proper context + PolicyContext.setContextID(policyContextID); + + //Get an authenticated subject, if there is one + Subject subject = null; + try { + + //We will use the PolicyContextHandlerContainerSubject.HANDLER_KEY to see if a user + //has authenticated, since a request.getUserPrincipal() will not pick up the user + //unless its using a acached session. + subject = (Subject) PolicyContext.getContext(PolicyContextHandlerContainerSubject.HANDLER_KEY); + + } catch (PolicyContextException e) { + log.error(e); + } + + //If nothing has authenticated yet, do the normal + if (subject == null) + return super.hasUserDataPermission(request, response, constraints); + + ContextManager.setCurrentCaller(subject); + + try { + + AccessControlContext acc = ContextManager.getCurrentContext(); + + /** + * JACC v1.0 secion 4.1.1 + */ + acc.checkPermission(new WebUserDataPermission(request)); + + } catch (AccessControlException ace) { + response.sendError(Response.SC_FORBIDDEN); + return false; + } + + return true; + } + + /** + * Perform access control based on the specified authorization constraint. + * Return <code>true</code> if this constraint is satisfied and processing + * should continue, or <code>false</code> otherwise. + * + * @param request Request we are processing + * @param response Response we are creating + * @param constraint Security constraint we are enforcing + * @param context The Context to which client of this class is attached. + * @throws java.io.IOException if an input/output error occurs + */ + public boolean hasResourcePermission(Request request, + Response response, + SecurityConstraint[] constraint, + Context context) + throws IOException { + + //Set the current request (for hasRole) + currentRequest.set(request); + + // Specifically allow access to the form login and form error pages + // and the "j_security_check" action + LoginConfig config = context.getLoginConfig(); + if ((config != null) && + (org.apache.catalina.realm.Constants.FORM_METHOD.equals(config.getAuthMethod()))) { + String requestURI = request.getDecodedRequestURI(); + String loginPage = context.getPath() + config.getLoginPage(); + if (loginPage.equals(requestURI)) { + if (log.isDebugEnabled()) + log.debug(" Allow access to login page " + loginPage); + return (true); + } + String errorPage = context.getPath() + config.getErrorPage(); + if (errorPage.equals(requestURI)) { + if (log.isDebugEnabled()) + log.debug(" Allow access to error page " + errorPage); + return (true); + } + if (requestURI.endsWith(org.apache.catalina.realm.Constants.FORM_ACTION)) { + if (log.isDebugEnabled()) + log.debug(" Allow access to username/password submission"); + return (true); + } + } + + // Which user principal have we already authenticated? + Principal principal = request.getUserPrincipal(); + + //If we have no principal, then we should use the default. + if (principal == null) { + ContextManager.setCurrentCaller(defaultSubject); + } else { + ContextManager.setCurrentCaller(((JAASTomcatPrincipal) principal).getSubject()); + } + + try { + + AccessControlContext acc = ContextManager.getCurrentContext(); + + + /** + * JACC v1.0 secion 4.1.2 + */ + acc.checkPermission(new WebResourcePermission(request)); + + } catch (AccessControlException ace) { + response.sendError(Response.SC_FORBIDDEN); + return false; + } + + return true; + + } + + private String getServletName(Request request) { + + String contextPath = ((HttpServletRequest) request.getRequest()).getContextPath(); + String requestURI = request.getDecodedRequestURI(); + String relativeURI = requestURI.substring(contextPath.length()); + String servletPath = relativeURI; + String name = null; + + //Try exact match + if (!(relativeURI.equals("/"))) + name = context.findServletMapping(relativeURI); + + //Try prefix match (i.e. xyz/* ) + if (name == null) { + servletPath = relativeURI; + while (true) { + name = context.findServletMapping(servletPath + "/*"); + if (name != null) { + break; + } + int slash = servletPath.lastIndexOf('/'); + if (slash < 0) + break; + servletPath = servletPath.substring(0, slash); + } + } + + //Try extension match (i.e. *.do ) + if (name == null) { + int slash = relativeURI.lastIndexOf('/'); + if (slash >= 0) { + String last = relativeURI.substring(slash); + int period = last.lastIndexOf('.'); + if (period >= 0) { + String pattern = "*" + last.substring(period); + name = context.findServletMapping(pattern); + } + } + } + + //Try default match + if (name == null) { + name = context.findServletMapping("/"); + } + + /** + * JACC v1.0 secion B.19 + */ + if (name.equals("jsp")) { + name = ""; + } + + return (name == null ? "" : name); + } + + /** + * Return <code>true</code> if the specified Principal has the specified + * security role, within the context of this Realm; otherwise return + * <code>false</code>. + * + * @param principal Principal for whom the role is to be checked + * @param role Security role to be checked + */ + public boolean hasRole(Principal principal, String role) { + + if ((principal == null) || (role == null) || !(principal instanceof JAASTomcatPrincipal)) { + return false; + } + + Request request = (Request) currentRequest.get(); + if (currentRequest == null) { + log.error("No currentRequest found."); + return false; + } + + String name = getServletName(request); + + //Set the caller + ContextManager.setCurrentCaller(((JAASTomcatPrincipal) principal).getSubject()); + + AccessControlContext acc = ContextManager.getCurrentContext(); + + try { + /** + * JACC v1.0 secion 4.1.3 + */ + acc.checkPermission(new WebRoleRefPermission(name, role)); + } catch (AccessControlException e) { + return false; + } + + return true; + } + + /** + * Return the <code>Principal</code> associated with the specified + * username and credentials, if there is one; otherwise return + * <code>null</code>. + * <p/> + * If there are any errors with the JDBC connection, executing the query or + * anything we return null (don't authenticate). This event is also logged, + * and the connection will be closed so that a subsequent request will + * automatically re-open it. + * + * @param username Username of the <code>Principal</code> to look up + * @param credentials Password or other credentials to use in authenticating this + * username + */ + public Principal authenticate(String username, String credentials) { + + // Establish a LoginContext to use for authentication + try { + LoginContext loginContext = null; + if (appName == null) + appName = "Tomcat"; + + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.beginLogin", username, appName)); + + // What if the LoginModule is in the container class loader ? + ClassLoader ocl = null; + + if (isUseContextClassLoader()) { + ocl = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + } + + try { + loginContext = new LoginContext(loginDomainName, new JAASCallbackHandler(this, username, credentials)); + } catch (Throwable e) { + log.error(sm.getString("jaasRealm.unexpectedError"), e); + return (null); + } finally { + if (isUseContextClassLoader()) { + Thread.currentThread().setContextClassLoader(ocl); + } + } + + if (log.isDebugEnabled()) + log.debug("Login context created " + username); + + // Negotiate a login via this LoginContext + Subject subject = null; + try { + loginContext.login(); + Subject tempSubject = loginContext.getSubject(); + if (tempSubject == null) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } + + subject = ContextManager.getServerSideSubject(tempSubject); + if (subject == null) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } + + ContextManager.setCurrentCaller(subject); + + } catch (AccountExpiredException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.accountExpired", username)); + return (null); + } catch (CredentialExpiredException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.credentialExpired", username)); + return (null); + } catch (FailedLoginException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } catch (LoginException e) { + log.warn(sm.getString("jaasRealm.loginException", username), e); + return (null); + } catch (Throwable e) { + log.error(sm.getString("jaasRealm.unexpectedError"), e); + return (null); + } + + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.loginContextCreated", username)); + + // Return the appropriate Principal for this authenticated Subject +/* Principal principal = createPrincipal(username, subject); + if (principal == null) { + log.debug(sm.getString("jaasRealm.authenticateFailure", username)); + return (null); + } + if (log.isDebugEnabled()) { + log.debug(sm.getString("jaasRealm.authenticateSuccess", username)); + } +*/ + JAASTomcatPrincipal jaasPrincipal = new JAASTomcatPrincipal(username); + jaasPrincipal.setSubject(subject); + + return (jaasPrincipal); + + } catch (Throwable t) { + log.error("error ", t); + return null; + } + } + + + public void addRoleMappings(Set securityRoles, String loginDomainName, Security security, RoleMappingConfiguration roleMapper) throws PolicyContextException, GeronimoSecurityException { + + for (Iterator roleMappings = security.getRoleMappings().values().iterator(); roleMappings.hasNext();) { + Role role = (Role) roleMappings.next(); + String roleName = role.getRoleName(); + Set principalSet = new HashSet(); + + if (!securityRoles.contains(roleName)) { + throw new GeronimoSecurityException("Role does not exist in this configuration"); + } + + Subject roleDesignate = new Subject(); + + for (Iterator realms = role.getRealms().values().iterator(); realms.hasNext();) { + Realm realm = (Realm) realms.next(); + + for (Iterator principals = realm.getPrincipals().iterator(); principals.hasNext();) { + org.apache.geronimo.security.deploy.Principal principal = (org.apache.geronimo.security.deploy.Principal) principals.next(); + + RealmPrincipal realmPrincipal = ConfigurationUtil.generateRealmPrincipal(principal, loginDomainName, realm.getRealmName()); + if (realmPrincipal == null) { + throw new GeronimoSecurityException("Unable to create realm principal"); + } + + principalSet.add(realmPrincipal); + if (principal.isDesignatedRunAs()) { + roleDesignate.getPrincipals().add(realmPrincipal); + } + } + } + roleMapper.addRoleMapping(roleName, principalSet); + + if (roleDesignate.getPrincipals().size() > 0) { + setRoleDesignate(roleName, roleDesignate); + } + } + + /** + * Register the role designates with the context manager. + */ + for (Iterator iter = roleDesignates.keySet().iterator(); iter.hasNext();) { + String roleName = (String) iter.next(); + Subject roleDesignate = (Subject) roleDesignates.get(roleName); + + ContextManager.registerSubject(roleDesignate); + SubjectId id = ContextManager.getSubjectId(roleDesignate); + roleDesignate.getPrincipals().add(new IdentificationPrincipal(id)); + } + + } + + private void setRoleDesignate(String roleName, Subject subject) { + roleDesignates.put(roleName, subject); + } + + private void configure(PermissionCollection uncheckedPermissions, + PermissionCollection excludedPermissions, + Map rolePermissions) throws GeronimoSecurityException { + try { + policyConfiguration.addToExcludedPolicy(excludedPermissions); + policyConfiguration.addToUncheckedPolicy(uncheckedPermissions); + for (Iterator iterator = rolePermissions.entrySet().iterator(); iterator.hasNext();) { + Map.Entry entry = (Map.Entry) iterator.next(); + String roleName = (String) entry.getKey(); + Set permissions = (Set) entry.getValue(); + for (Iterator iterator1 = permissions.iterator(); iterator1.hasNext();) { + Permission permission = (Permission) iterator1.next(); + policyConfiguration.addToRole(roleName, permission); + } + } + } catch (PolicyContextException e) { + throw new GeronimoSecurityException(e); + } + } + + /** + * Prepare for active use of the public methods of this <code>Component</code>. + * + * @throws org.apache.catalina.LifecycleException + * if this component detects a fatal error + * that prevents it from being started + */ + public void start() throws LifecycleException { + + // Perform normal superclass initialization + super.start(); + + } + + + /** + * Gracefully shut down active use of the public methods of this <code>Component</code>. + * + * @throws LifecycleException if this component detects a fatal error + * that needs to be reported + */ + public void stop() throws LifecycleException { + + // Perform normal superclass finalization + super.stop(); + + for (Iterator iter = roleDesignates.keySet().iterator(); iter.hasNext();) { + String roleName = (String) iter.next(); + Subject roleDesignate = (Subject) roleDesignates.get(roleName); + + ContextManager.unregisterSubject(roleDesignate); + } + ContextManager.unregisterSubject(defaultSubject); + + try { + + if (policyConfiguration != null) + policyConfiguration.delete(); + + } catch (PolicyContextException pce) { + //Oh well, we tried + } + + } + + public void setContext(Context context) { + this.context = context; + } + +} Modified: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java?view=diff&rev=125716&p1=geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java&r1=125715&p2=geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java&r2=125716 ============================================================================== --- geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java (original) +++ geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatJAASRealm.java Wed Jan 19 21:21:50 2005 @@ -1,157 +1,164 @@ -/** - * - * Copyright 2003-2004 The Apache Software Foundation - * - * Licensed 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.apache.geronimo.tomcat; - -import java.security.Principal; - -import javax.security.auth.Subject; -import javax.security.auth.login.AccountExpiredException; -import javax.security.auth.login.CredentialExpiredException; -import javax.security.auth.login.FailedLoginException; -import javax.security.auth.login.LoginContext; -import javax.security.auth.login.LoginException; - -import org.apache.catalina.realm.JAASCallbackHandler; -import org.apache.catalina.realm.JAASRealm; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.geronimo.security.ContextManager; - -/** - * @version $Rev: 106522 $ $Date: 2004-11-25 01:28:57 +0100 (Thu, 25 Nov 2004) $ - */ -public class TomcatJAASRealm extends JAASRealm { - private static final Log log = LogFactory.getLog(TomcatJAASRealm.class); - - /** - * Descriptive information about this <code>Realm</code> implementation. - */ - protected static final String info = "org.apache.geronimo.tomcat.TomcatJAASRealm/1.0"; - - /** - * Descriptive information about this <code>Realm</code> implementation. - */ - protected static final String name = "TomcatJAASRealm"; - - /** - * Return the <code>Principal</code> associated with the specified - * username and credentials, if there is one; otherwise return - * <code>null</code>. - * - * If there are any errors with the JDBC connection, executing the query or - * anything we return null (don't authenticate). This event is also logged, - * and the connection will be closed so that a subsequent request will - * automatically re-open it. - * - * @param username - * Username of the <code>Principal</code> to look up - * @param credentials - * Password or other credentials to use in authenticating this - * username - */ - public Principal authenticate(String username, String credentials) { - - // Establish a LoginContext to use for authentication - try { - LoginContext loginContext = null; - if (appName == null) - appName = "Tomcat"; - - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.beginLogin", username, appName)); - - // What if the LoginModule is in the container class loader ? - ClassLoader ocl = null; - - if (isUseContextClassLoader()) { - ocl = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); - } - - try { - loginContext = new LoginContext(appName, new JAASCallbackHandler(this, username, credentials)); - } catch (Throwable e) { - log.error(sm.getString("jaasRealm.unexpectedError"), e); - return (null); - } finally { - if (isUseContextClassLoader()) { - Thread.currentThread().setContextClassLoader(ocl); - } - } - - if (log.isDebugEnabled()) - log.debug("Login context created " + username); - - // Negotiate a login via this LoginContext - Subject subject = null; - try { - loginContext.login(); - Subject tempSubject = loginContext.getSubject(); - if (tempSubject == null) { - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.failedLogin", username)); - return (null); - } - - subject = ContextManager.getServerSideSubject(tempSubject); - if (subject == null) { - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.failedLogin", username)); - return (null); - } - - } catch (AccountExpiredException e) { - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.accountExpired", username)); - return (null); - } catch (CredentialExpiredException e) { - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.credentialExpired", username)); - return (null); - } catch (FailedLoginException e) { - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.failedLogin", username)); - return (null); - } catch (LoginException e) { - log.warn(sm.getString("jaasRealm.loginException", username), e); - return (null); - } catch (Throwable e) { - log.error(sm.getString("jaasRealm.unexpectedError"), e); - return (null); - } - - if (log.isDebugEnabled()) - log.debug(sm.getString("jaasRealm.loginContextCreated", username)); - - // Return the appropriate Principal for this authenticated Subject - Principal principal = createPrincipal(username, subject); - if (principal == null) { - log.debug(sm.getString("jaasRealm.authenticateFailure", username)); - return (null); - } - if (log.isDebugEnabled()) { - log.debug(sm.getString("jaasRealm.authenticateSuccess", username)); - } - - return (principal); - } catch (Throwable t) { - log.error("error ", t); - return null; - } - } - -} +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.security.Principal; +import javax.security.auth.Subject; +import javax.security.auth.login.AccountExpiredException; +import javax.security.auth.login.CredentialExpiredException; +import javax.security.auth.login.FailedLoginException; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + +import org.apache.catalina.realm.JAASCallbackHandler; +import org.apache.catalina.realm.JAASRealm; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.geronimo.security.ContextManager; + + +/** + * @version $Rev: 106522 $ $Date: 2004-11-25 01:28:57 +0100 (Thu, 25 Nov 2004) $ + */ +public class TomcatJAASRealm extends JAASRealm { + private static final Log log = LogFactory.getLog(TomcatJAASRealm.class); + + /** + * Descriptive information about this <code>Realm</code> implementation. + */ + protected static final String info = "org.apache.geronimo.tomcat.TomcatJAASRealm/1.0"; + + /** + * Descriptive information about this <code>Realm</code> implementation. + */ + protected static final String name = "TomcatJAASRealm"; + private String loginDomainName = null; + + public TomcatJAASRealm(String loginDomainName) { + super(); + + this.loginDomainName = loginDomainName; + + } + + /** + * Return the <code>Principal</code> associated with the specified + * username and credentials, if there is one; otherwise return + * <code>null</code>. + * <p/> + * If there are any errors with the JDBC connection, executing the query or + * anything we return null (don't authenticate). This event is also logged, + * and the connection will be closed so that a subsequent request will + * automatically re-open it. + * + * @param username Username of the <code>Principal</code> to look up + * @param credentials Password or other credentials to use in authenticating this + * username + */ + public Principal authenticate(String username, String credentials) { + + // Establish a LoginContext to use for authentication + try { + LoginContext loginContext = null; + if (appName == null) + appName = "Tomcat"; + + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.beginLogin", username, appName)); + + // What if the LoginModule is in the container class loader ? + ClassLoader ocl = null; + + if (isUseContextClassLoader()) { + ocl = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + } + + try { + loginContext = new LoginContext(loginDomainName, new JAASCallbackHandler(this, username, credentials)); + } catch (Throwable e) { + log.error(sm.getString("jaasRealm.unexpectedError"), e); + return (null); + } finally { + if (isUseContextClassLoader()) { + Thread.currentThread().setContextClassLoader(ocl); + } + } + + if (log.isDebugEnabled()) + log.debug("Login context created " + username); + + // Negotiate a login via this LoginContext + Subject subject = null; + try { + loginContext.login(); + Subject tempSubject = loginContext.getSubject(); + if (tempSubject == null) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } + + subject = ContextManager.getServerSideSubject(tempSubject); + if (subject == null) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } + + } catch (AccountExpiredException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.accountExpired", username)); + return (null); + } catch (CredentialExpiredException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.credentialExpired", username)); + return (null); + } catch (FailedLoginException e) { + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.failedLogin", username)); + return (null); + } catch (LoginException e) { + log.warn(sm.getString("jaasRealm.loginException", username), e); + return (null); + } catch (Throwable e) { + log.error(sm.getString("jaasRealm.unexpectedError"), e); + return (null); + } + + if (log.isDebugEnabled()) + log.debug(sm.getString("jaasRealm.loginContextCreated", username)); + + // Return the appropriate Principal for this authenticated Subject + Principal principal = createPrincipal(username, subject); + if (principal == null) { + log.debug(sm.getString("jaasRealm.authenticateFailure", username)); + return (null); + } + if (log.isDebugEnabled()) { + log.debug(sm.getString("jaasRealm.authenticateSuccess", username)); + } + + return (principal); + } catch (Throwable t) { + log.error("error ", t); + return null; + } + } + +} Modified: geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java?view=diff&rev=125716&p1=geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java&r1=125715&p2=geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java&r2=125716 ============================================================================== --- geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java (original) +++ geronimo/trunk/modules/tomcat/src/java/org/apache/geronimo/tomcat/TomcatWebAppContext.java Wed Jan 19 21:21:50 2005 @@ -1,197 +1,221 @@ -/** - * - * Copyright 2003-2004 The Apache Software Foundation - * - * Licensed 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.apache.geronimo.tomcat; - -import java.net.URI; -import java.net.URL; - -import org.apache.catalina.Context; -import org.apache.catalina.Realm; -import org.apache.catalina.deploy.SecurityConstraint; -import org.apache.catalina.deploy.LoginConfig; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.apache.geronimo.gbean.GBeanInfo; -import org.apache.geronimo.gbean.GBeanInfoBuilder; -import org.apache.geronimo.gbean.GBeanLifecycle; -import org.apache.geronimo.gbean.WaitingException; - - -/** - * Wrapper for a WebApplicationContext that sets up its J2EE environment. - * - * @version $Rev: 56022 $ $Date: 2004-10-30 07:16:18 +0200 (Sat, 30 Oct 2004) $ - */ -public class TomcatWebAppContext implements GBeanLifecycle, TomcatContext { - - private static Log log = LogFactory.getLog(TomcatWebAppContext.class); - - protected final TomcatContainer container; - - protected Context context = null; - - private final URI webAppRoot; - - private String path = null; - - private String docBase = null; - - private final LoginConfig loginConfig; - - private final Realm tomcatRealm; - - private final SecurityConstraint[] securityConstraints; - - private final String[] securityRoles; - - - public TomcatWebAppContext(URI webAppRoot, URI[] webClassPath, URL configurationBaseUrl, String authMethod, - String realmName, String loginPage, String errorPage, Realm tomcatRealm, - SecurityConstraint[] securityConstraints, String[] securityRoles, - TomcatContainer container) { - assert webAppRoot != null; - assert webClassPath != null; - assert configurationBaseUrl != null; - assert container != null; - - this.webAppRoot = webAppRoot; - this.container = container; - - this.setDocBase(this.webAppRoot.getPath()); - this.tomcatRealm = tomcatRealm; - this.securityConstraints = securityConstraints; - this.securityRoles = securityRoles; - - if (authMethod != null){ - loginConfig = new LoginConfig(); - loginConfig.setAuthMethod(authMethod); - loginConfig.setRealmName(realmName); - loginConfig.setLoginPage(loginPage); - loginConfig.setErrorPage(errorPage); - } else { - loginConfig = null; - } - } - - public String getDocBase() { - return docBase; - } - - public void setDocBase(String docBase) { - this.docBase = docBase; - } - - public void setContextProperties() { - context.setDocBase(webAppRoot.getPath()); - context.setPath(path); - - //Security - if (tomcatRealm != null) - context.setRealm(tomcatRealm); - - if (loginConfig != null) - context.setLoginConfig(loginConfig); - - // Add the security constraints - if (securityConstraints != null) { - for (int i = 0; i < securityConstraints.length; i++) { - SecurityConstraint sc = securityConstraints[i]; - context.addConstraint(sc); - } - } - - // Add the security roles - if (securityRoles != null) { - for (int i = 0; i < securityRoles.length; i++) { - context.addSecurityRole(securityRoles[i]); - } - } - } - - public Context getContext() { - return context; - } - - public void setContext(Context context) { - this.context = context; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public void doStart() throws WaitingException, Exception { - - // See the note of TomcatContainer::addContext - container.addContext(this); - // Is it necessary - doesn't Tomcat Embedded take care of it? - // super.start(); - - log.info("TomcatWebAppContext started"); - } - - public void doStop() throws Exception { - container.removeContext(this); - - log.info("TomcatWebAppContext stopped"); - } - - public void doFail() { - container.removeContext(this); - - log.info("TomcatWebAppContext failed"); - } - - public static final GBeanInfo GBEAN_INFO; - - static { - GBeanInfoBuilder infoFactory = new GBeanInfoBuilder("Tomcat WebApplication Context", TomcatWebAppContext.class); - - infoFactory.addAttribute("webAppRoot", URI.class, true); - infoFactory.addAttribute("webClassPath", URI[].class, true); - infoFactory.addAttribute("configurationBaseUrl", URL.class, true); - - infoFactory.addAttribute("path", String.class, true); - - infoFactory.addAttribute("authMethod", String.class, true); - infoFactory.addAttribute("realmName", String.class, true); - infoFactory.addAttribute("loginPage", String.class, true); - infoFactory.addAttribute("errorPage", String.class, true); - - infoFactory.addAttribute("tomcatRealm", Realm.class, true); - infoFactory.addAttribute("securityConstraints", SecurityConstraint[].class, true); - infoFactory.addAttribute("securityRoles", String[].class, true); - - infoFactory.addReference("Container", TomcatContainer.class); - - infoFactory.setConstructor(new String[]{"webAppRoot", "webClassPath", "configurationBaseUrl", "authMethod", - "realmName", "loginPage", "errorPage", "tomcatRealm", - "securityConstraints", "securityRoles", "Container"}); - - GBEAN_INFO = infoFactory.getBeanInfo(); - } - - public static GBeanInfo getGBeanInfo() { - return GBEAN_INFO; - } -} +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.net.URI; +import java.net.URL; +import java.security.PermissionCollection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.apache.catalina.Context; +import org.apache.catalina.Realm; +import org.apache.catalina.deploy.LoginConfig; +import org.apache.catalina.deploy.SecurityConstraint; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.geronimo.gbean.GBeanInfo; +import org.apache.geronimo.gbean.GBeanInfoBuilder; +import org.apache.geronimo.gbean.GBeanLifecycle; +import org.apache.geronimo.gbean.WaitingException; +import org.apache.geronimo.security.deploy.Security; + + +/** + * Wrapper for a WebApplicationContext that sets up its J2EE environment. + * + * @version $Rev: 56022 $ $Date: 2004-10-30 07:16:18 +0200 (Sat, 30 Oct 2004) $ + */ +public class TomcatWebAppContext implements GBeanLifecycle, TomcatContext { + + private static Log log = LogFactory.getLog(TomcatWebAppContext.class); + + protected final TomcatContainer container; + + protected Context context = null; + private final URI webAppRoot; + private String path = null; + private String docBase = null; + private final LoginConfig loginConfig; + private final Realm tomcatRealm; + private final Set securityConstraints; + private final Set securityRoles; + + public TomcatWebAppContext(URI webAppRoot, + URI[] webClassPath, + URL configurationBaseUrl, + LoginConfig loginConfig, + Realm tomcatRealm, + Set securityConstraints, + + String policyContextID, + String loginDomainName, + Security securityConfig, + Set securityRoles, + PermissionCollection uncheckedPermissions, + PermissionCollection excludedPermissions, + Map rolePermissions, + + TomcatContainer container) { + + assert webAppRoot != null; + assert webClassPath != null; + assert configurationBaseUrl != null; + assert container != null; + + this.webAppRoot = webAppRoot; + this.container = container; + + this.setDocBase(this.webAppRoot.getPath()); + this.tomcatRealm = tomcatRealm; + this.securityConstraints = securityConstraints; + this.securityRoles = securityRoles; + this.loginConfig = loginConfig; + } + + public String getDocBase() { + return docBase; + } + + public void setDocBase(String docBase) { + this.docBase = docBase; + } + + public void setContextProperties() { + context.setDocBase(webAppRoot.getPath()); + context.setPath(path); + + //Security + if (tomcatRealm != null) { + if (tomcatRealm instanceof TomcatGeronimoRealm) { + ((TomcatGeronimoRealm) tomcatRealm).setContext(context); + } + + context.setRealm(tomcatRealm); + } + + if (loginConfig != null) + context.setLoginConfig(loginConfig); + + // Add the security constraints + if (securityConstraints != null) { + Iterator conIterator = securityConstraints.iterator(); + while (conIterator.hasNext()) { + context.addConstraint((SecurityConstraint) conIterator.next()); + } + } + + // Add the security roles + if (securityRoles != null) { + Iterator secIterator = securityRoles.iterator(); + while (secIterator.hasNext()) { + context.addSecurityRole((String) secIterator.next()); + } + } + } + + public Context getContext() { + return context; + } + + public void setContext(Context context) { + this.context = context; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public void doStart() throws WaitingException, Exception { + + // See the note of TomcatContainer::addContext + container.addContext(this); + // Is it necessary - doesn't Tomcat Embedded take care of it? + // super.start(); + + log.info("TomcatWebAppContext started"); + } + + public void doStop() throws Exception { + container.removeContext(this); + + log.info("TomcatWebAppContext stopped"); + } + + public void doFail() { + container.removeContext(this); + + log.info("TomcatWebAppContext failed"); + } + + public static final GBeanInfo GBEAN_INFO; + + static { + GBeanInfoBuilder infoFactory = new GBeanInfoBuilder("Tomcat WebApplication Context", TomcatWebAppContext.class); + + infoFactory.addAttribute("webAppRoot", URI.class, true); + infoFactory.addAttribute("webClassPath", URI[].class, true); + infoFactory.addAttribute("configurationBaseUrl", URL.class, true); + + infoFactory.addAttribute("path", String.class, true); + + infoFactory.addAttribute("loginConfig", LoginConfig.class, true); + + infoFactory.addAttribute("tomcatRealm", Realm.class, true); + infoFactory.addAttribute("securityConstraints", Set.class, true); + + infoFactory.addAttribute("policyContextID", String.class, true); + infoFactory.addAttribute("loginDomainName", String.class, true); + infoFactory.addAttribute("securityConfig", Security.class, true); + infoFactory.addAttribute("securityRoles", Set.class, true); + infoFactory.addAttribute("uncheckedPermissions", PermissionCollection.class, true); + infoFactory.addAttribute("excludedPermissions", PermissionCollection.class, true); + infoFactory.addAttribute("rolePermissions", Map.class, true); + + infoFactory.addReference("Container", TomcatContainer.class); + + infoFactory.setConstructor(new String[]{ + "webAppRoot", + "webClassPath", + "configurationBaseUrl", + "loginConfig", + "tomcatRealm", + "securityConstraints", + "policyContextID", + "loginDomainName", + "securityConfig", + "securityRoles", + "uncheckedPermissions", + "excludedPermissions", + "rolePermissions", + "Container" + }); + + GBEAN_INFO = infoFactory.getBeanInfo(); + } + + public static GBeanInfo getGBeanInfo() { + return GBEAN_INFO; + } +} Modified: geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java?view=diff&rev=125716&p1=geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java&r1=125715&p2=geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java&r2=125716 ============================================================================== --- geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java (original) +++ geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/AbstractWebModuleTest.java Wed Jan 19 21:21:50 2005 @@ -1,272 +1,292 @@ -/** - * - * Copyright 2003-2004 The Apache Software Foundation - * - * Licensed 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.apache.geronimo.tomcat; - -import java.io.File; -import java.net.URI; -import java.util.Collections; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import javax.management.ObjectName; - -import junit.framework.TestCase; - -import org.apache.catalina.deploy.SecurityConstraint; -import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTrackingCoordinator; -import org.apache.geronimo.gbean.GBeanData; -import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContext; -import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContextImpl; -import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; -import org.apache.geronimo.kernel.Kernel; -import org.apache.geronimo.kernel.management.State; -import org.apache.geronimo.security.SecurityServiceImpl; -import org.apache.geronimo.security.deploy.MapOfSets; -import org.apache.geronimo.security.deploy.Principal; -import org.apache.geronimo.security.jaas.JaasLoginService; -import org.apache.geronimo.security.jaas.LoginModuleGBean; -import org.apache.geronimo.security.realm.GenericSecurityRealm; -import org.apache.geronimo.system.serverinfo.ServerInfo; -import org.apache.geronimo.tomcat.connector.HTTPConnector; -import org.apache.geronimo.transaction.context.TransactionContextManager; -import org.apache.geronimo.transaction.manager.TransactionManagerImpl; - -/** - * @version $Rev: 111239 $ $Date: 2004-12-08 02:29:11 -0700 (Wed, 08 Dec 2004) $ - */ -public class AbstractWebModuleTest extends TestCase { - - protected static final String securityRealmName = "demo-properties-realm"; - - protected Kernel kernel; - - private GBeanData container; - - private ObjectName containerName; - - private ObjectName connectorName; - - private GBeanData connector; - - private ObjectName webModuleName; - - private ObjectName tmName; - - private ObjectName ctcName; - - private GBeanData tm; - - private GBeanData ctc; - - private ObjectName tcmName; - - private GBeanData tcm; - - private ClassLoader cl; - - private J2eeContext moduleContext = new J2eeContextImpl("tomcat.test", "test", "null", "tomcatTest", null, null); - - private GBeanData securityServiceGBean; - - protected ObjectName securityServiceName; - - private ObjectName loginServiceName; - - private GBeanData loginServiceGBean; - - protected GBeanData propertiesLMGBean; - - protected ObjectName propertiesLMName; - - private ObjectName propertiesRealmName; - - private GBeanData propertiesRealmGBean; - - private ObjectName serverInfoName; - - private GBeanData serverInfoGBean; - - public void testDummy() throws Exception { - } - - protected void setUpInsecureAppContext() throws Exception { - - GBeanData app = new GBeanData(webModuleName, TomcatWebAppContext.GBEAN_INFO); - // GBeanData app = new GBeanData(webModuleName, - // TomcatWebAppContext.GBEAN_INFO); - app.setAttribute("webAppRoot", new File("target/var/catalina/webapps/war1/").toURI()); - // app.setAttribute("componentContext", null); - // OnlineUserTransaction userTransaction = new OnlineUserTransaction(); - // app.setAttribute("userTransaction", userTransaction); - // we have no classes or libs. - app.setAttribute("webClassPath", new URI[] {}); - // app.setAttribute("contextPriorityClassLoader", Boolean.FALSE); - app.setAttribute("configurationBaseUrl", new File("target/var/catalina/webapps/war1/WEB-INF/web.xml").toURL()); - // app.setReferencePattern("TransactionContextManager", tcmName); - // app.setReferencePattern("TrackedConnectionAssociator", ctcName); - app.setReferencePattern("Container", containerName); - - // app.setAttribute("contextPath", "/test"); - app.setAttribute("path", "/test"); - - start(app); - } - - // protected void setUpSecureAppContext(Security securityConfig, Set - // uncheckedPermissions, Set excludedPermissions, Map rolePermissions, Set - // securityRoles, Map legacySecurityConstraintMap) throws Exception { - protected ObjectName setUpSecureAppContext(SecurityConstraint[] securityConstraints, String[] securityRoles) - throws Exception { - GBeanData app = new GBeanData(webModuleName, TomcatWebAppContext.GBEAN_INFO); - app.setAttribute("webAppRoot", new File("target/var/catalina/webapps/war3/").toURI()); - app.setAttribute("webClassPath", new URI[] {}); - app.setAttribute("configurationBaseUrl", new File("target/var/catalina/webapps/war3/WEB-INF/web.xml").toURL()); - app.setAttribute("path", "/securetest"); - app.setAttribute("authMethod", "FORM"); - app.setAttribute("realmName", "Test JAAS Realm"); - app.setAttribute("loginPage", "/auth/logon.html?param=test"); - app.setAttribute("errorPage", "/auth/logonError.html?param=test"); - - app.setAttribute("securityConstraints", securityConstraints); - app.setAttribute("securityRoles", securityRoles); - - TomcatJAASRealm realm = new TomcatJAASRealm(); - realm.setUserClassNames("org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); - realm.setRoleClassNames("org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"); - app.setAttribute("tomcatRealm", realm); - - app.setReferencePattern("Container", containerName); - start(app); - - return webModuleName; - } - - protected void setUpSecurity() throws Exception { - securityServiceName = new ObjectName("geronimo.security:type=SecurityService"); - securityServiceGBean = new GBeanData(securityServiceName, SecurityServiceImpl.GBEAN_INFO); - securityServiceGBean.setAttribute("policyConfigurationFactory", "org.apache.geronimo.security.jacc.GeronimoPolicyConfigurationFactory"); - - loginServiceName = JaasLoginService.OBJECT_NAME; - loginServiceGBean = new GBeanData(loginServiceName, JaasLoginService.GBEAN_INFO); - loginServiceGBean.setReferencePatterns("Realms", Collections.singleton(new ObjectName("geronimo.security:type=SecurityRealm,*"))); - // loginServiceGBean.setAttribute("reclaimPeriod", new Long(1000 * - // 1000)); - loginServiceGBean.setAttribute("algorithm", "HmacSHA1"); - loginServiceGBean.setAttribute("password", "secret"); - - propertiesLMName = new ObjectName("geronimo.security:type=LoginModule,name=demo-properties-login"); - propertiesLMGBean = new GBeanData(propertiesLMName, LoginModuleGBean.GBEAN_INFO); - propertiesLMGBean.setAttribute("loginModuleClass", "org.apache.geronimo.security.realm.providers.PropertiesFileLoginModule"); - propertiesLMGBean.setAttribute("serverSide", Boolean.TRUE); - Properties options = new Properties(); - options.setProperty("usersURI", "src/test-resources/data/users.properties"); - options.setProperty("groupsURI", "src/test-resources/data/groups.properties"); - propertiesLMGBean.setAttribute("options", options); - propertiesLMGBean.setAttribute("loginDomainName", securityRealmName); - - propertiesRealmName = new ObjectName("geronimo.security:type=SecurityRealm,realm=demo-properties-realm"); - propertiesRealmGBean = new GBeanData(propertiesRealmName, GenericSecurityRealm.GBEAN_INFO); - propertiesRealmGBean.setReferencePatterns("ServerInfo", Collections.singleton(serverInfoName)); - propertiesRealmGBean.setAttribute("realmName", securityRealmName); - Properties config = new Properties(); - config.setProperty("LoginModule.1.REQUIRED", propertiesLMName.getCanonicalName()); - propertiesRealmGBean.setAttribute("loginModuleConfiguration", config); - Principal.PrincipalEditor principalEditor = new Principal.PrincipalEditor(); - principalEditor.setAsText("metro=org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); - propertiesRealmGBean.setAttribute("defaultPrincipal", principalEditor.getValue()); - - start(securityServiceGBean); - start(loginServiceGBean); - start(propertiesLMGBean); - start(propertiesRealmGBean); - - } - - protected void tearDownSecurity() throws Exception { - stop(propertiesRealmName); - stop(propertiesLMName); - stop(serverInfoName); - stop(loginServiceName); - stop(securityServiceName); - } - - private void start(GBeanData gbeanData) throws Exception { - kernel.loadGBean(gbeanData, cl); - kernel.startGBean(gbeanData.getName()); - if (((Integer) kernel.getAttribute(gbeanData.getName(), "state")).intValue() != State.RUNNING_INDEX) { - fail("gbean not started: " + gbeanData.getName()); - } - } - - protected void stop(ObjectName name) throws Exception { - kernel.stopGBean(name); - kernel.unloadGBean(name); - } - - protected void setUp() throws Exception { - cl = this.getClass().getClassLoader(); - containerName = NameFactory.getWebComponentName(null, null, null, null, "tomcatContainer", "WebResource", moduleContext); - connectorName = NameFactory.getWebComponentName(null, null, null, null, "tomcatConnector", "WebResource", moduleContext); - webModuleName = NameFactory.getWebComponentName(null, null, null, null, NameFactory.WEB_MODULE, "WebResource", moduleContext); - - tmName = NameFactory.getComponentName(null, null, null, null, "TransactionManager", NameFactory.JTA_RESOURCE, moduleContext); - tcmName = NameFactory.getComponentName(null, null, null, null, "TransactionContextManager", NameFactory.JTA_RESOURCE, moduleContext); - ctcName = new ObjectName("geronimo.test:role=ConnectionTrackingCoordinator"); - - kernel = new Kernel("test.kernel"); - kernel.boot(); - - serverInfoName = new ObjectName("geronimo.system:role=ServerInfo"); - serverInfoGBean = new GBeanData(serverInfoName, ServerInfo.GBEAN_INFO); - serverInfoGBean.setAttribute("baseDirectory", "."); - - start(serverInfoGBean); - - // Need to override the constructor for unit tests - container = new GBeanData(containerName, TomcatContainer.GBEAN_INFO); - container.setAttribute("catalinaHome", "target/var/catalina"); - container.setAttribute("endorsedDirs", "target/endorsed"); - container.setReferencePattern("ServerInfo", serverInfoName); - - connector = new GBeanData(connectorName, HTTPConnector.GBEAN_INFO); - connector.setAttribute("port", new Integer(8080)); - connector.setReferencePattern("TomcatContainer", containerName); - - start(container); - start(connector); - - tm = new GBeanData(tmName, TransactionManagerImpl.GBEAN_INFO); - Set patterns = new HashSet(); - patterns.add(ObjectName.getInstance("geronimo.server:j2eeType=JCAManagedConnectionFactory,*")); - tm.setAttribute("defaultTransactionTimeoutSeconds", new Integer(10)); - tm.setReferencePatterns("ResourceManagers", patterns); - start(tm); - tcm = new GBeanData(tcmName, TransactionContextManager.GBEAN_INFO); - tcm.setReferencePattern("TransactionManager", tmName); - start(tcm); - ctc = new GBeanData(ctcName, ConnectionTrackingCoordinator.GBEAN_INFO); - start(ctc); - } - - protected void tearDown() throws Exception { - stop(ctcName); - stop(tmName); - stop(containerName); - kernel.shutdown(); - } -} +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.io.File; +import java.net.URI; +import java.security.PermissionCollection; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import javax.management.ObjectName; + +import junit.framework.TestCase; +import org.apache.catalina.authenticator.Constants; +import org.apache.catalina.deploy.LoginConfig; + +import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTrackingCoordinator; +import org.apache.geronimo.gbean.GBeanData; +import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContext; +import org.apache.geronimo.j2ee.j2eeobjectnames.J2eeContextImpl; +import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; +import org.apache.geronimo.kernel.Kernel; +import org.apache.geronimo.kernel.management.State; +import org.apache.geronimo.security.SecurityServiceImpl; +import org.apache.geronimo.security.deploy.Principal; +import org.apache.geronimo.security.deploy.Security; +import org.apache.geronimo.security.jaas.GeronimoLoginConfiguration; +import org.apache.geronimo.security.jaas.JaasLoginService; +import org.apache.geronimo.security.jaas.LoginModuleGBean; +import org.apache.geronimo.security.realm.GenericSecurityRealm; +import org.apache.geronimo.system.serverinfo.ServerInfo; +import org.apache.geronimo.tomcat.connector.HTTPConnector; +import org.apache.geronimo.transaction.context.TransactionContextManager; +import org.apache.geronimo.transaction.manager.TransactionManagerImpl; + + +/** + * @version $Rev: 111239 $ $Date: 2004-12-08 02:29:11 -0700 (Wed, 08 Dec 2004) $ + */ +public class AbstractWebModuleTest extends TestCase { + + protected static final String securityRealmName = "demo-properties-realm"; + protected Kernel kernel; + private GBeanData container; + private ObjectName containerName; + private ObjectName connectorName; + private GBeanData connector; + private ObjectName webModuleName; + private ObjectName tmName; + private ObjectName ctcName; + private GBeanData tm; + private GBeanData ctc; + private ObjectName tcmName; + private GBeanData tcm; + private ClassLoader cl; + private J2eeContext moduleContext = new J2eeContextImpl("tomcat.test", "test", "null", "tomcatTest", null, null); + private GBeanData securityServiceGBean; + protected ObjectName securityServiceName; + private ObjectName loginServiceName; + private GBeanData loginServiceGBean; + private GBeanData loginConfigurationGBean; + protected ObjectName loginConfigurationName; + protected GBeanData propertiesLMGBean; + protected ObjectName propertiesLMName; + protected ObjectName propertiesRealmName; + private GBeanData propertiesRealmGBean; + private ObjectName serverInfoName; + private GBeanData serverInfoGBean; + + public void testDummy() throws Exception { + } + + protected void setUpInsecureAppContext() throws Exception { + + GBeanData app = new GBeanData(webModuleName, TomcatWebAppContext.GBEAN_INFO); + app.setAttribute("webAppRoot", new File("target/var/catalina/webapps/war1/").toURI()); + app.setAttribute("webClassPath", new URI[]{}); + app.setAttribute("configurationBaseUrl", new File("target/var/catalina/webapps/war1/WEB-INF/web.xml").toURL()); + app.setReferencePattern("Container", containerName); + app.setAttribute("path", "/test"); + + start(app); + } + + protected ObjectName setUpJAASSecureAppContext(Set securityConstraints, Set securityRoles) throws Exception { + GBeanData app = new GBeanData(webModuleName, TomcatWebAppContext.GBEAN_INFO); + app.setAttribute("webAppRoot", new File("target/var/catalina/webapps/war3/").toURI()); + app.setAttribute("webClassPath", new URI[]{}); + app.setAttribute("configurationBaseUrl", new File("target/var/catalina/webapps/war3/WEB-INF/web.xml").toURL()); + app.setAttribute("path", "/securetest"); + + LoginConfig loginConfig = new LoginConfig(); + loginConfig.setAuthMethod(Constants.FORM_METHOD); + loginConfig.setRealmName("Test JAAS Realm"); + loginConfig.setLoginPage("/auth/logon.html?param=test"); + loginConfig.setErrorPage("/auth/logonError.html?param=test"); + app.setAttribute("loginConfig", loginConfig); + app.setAttribute("loginConfig", loginConfig); + + app.setAttribute("securityConstraints", securityConstraints); + app.setAttribute("securityRoles", securityRoles); + + TomcatJAASRealm realm = new TomcatJAASRealm("demo-properties-realm"); + realm.setUserClassNames("org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); + realm.setRoleClassNames("org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"); + app.setAttribute("tomcatRealm", realm); + + app.setReferencePattern("Container", containerName); + start(app); + + return webModuleName; + } + + protected ObjectName setUpSecureAppContext(Security securityConfig, + Set securityConstraints, + PermissionCollection uncheckedPermissions, + PermissionCollection excludedPermissions, + Map rolePermissions, + Set securityRoles) + throws Exception { + + GBeanData app = new GBeanData(webModuleName, TomcatWebAppContext.GBEAN_INFO); + app.setAttribute("webAppRoot", new File("target/var/catalina/webapps/war3/").toURI()); + app.setAttribute("webClassPath", new URI[]{}); + app.setAttribute("configurationBaseUrl", new File("target/var/catalina/webapps/war3/WEB-INF/web.xml").toURL()); + app.setAttribute("path", "/securetest"); + + LoginConfig loginConfig = new LoginConfig(); + loginConfig.setAuthMethod(Constants.FORM_METHOD); + loginConfig.setRealmName("Test JACC Realm"); + loginConfig.setLoginPage("/auth/logon.html?param=test"); + loginConfig.setErrorPage("/auth/logonError.html?param=test"); + app.setAttribute("loginConfig", loginConfig); + + app.setAttribute("securityConstraints", securityConstraints); + app.setAttribute("securityRoles", securityRoles); + + TomcatGeronimoRealm realm = new TomcatGeronimoRealm("securetest", + securityConfig, + "demo-properties-realm", + securityRoles, + uncheckedPermissions, + excludedPermissions, + rolePermissions); + realm.setUserClassNames("org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); + realm.setRoleClassNames("org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"); + app.setAttribute("tomcatRealm", realm); + + app.setReferencePattern("Container", containerName); + start(app); + + return webModuleName; + } + + protected void setUpSecurity() throws Exception { + + loginConfigurationName = new ObjectName("geronimo.security:type=LoginConfiguration"); + loginConfigurationGBean = new GBeanData(loginConfigurationName, GeronimoLoginConfiguration.getGBeanInfo()); + Set configurations = new HashSet(); + configurations.add(new ObjectName("geronimo.server:j2eeType=SecurityRealm,*")); + configurations.add(new ObjectName("geronimo.server:j2eeType=ConfigurationEntry,*")); + loginConfigurationGBean.setReferencePatterns("Configurations", configurations); + + securityServiceName = new ObjectName("geronimo.server:j2eeType=SecurityService"); + securityServiceGBean = new GBeanData(securityServiceName, SecurityServiceImpl.GBEAN_INFO); + securityServiceGBean.setAttribute("policyConfigurationFactory", "org.apache.geronimo.security.jacc.GeronimoPolicyConfigurationFactory"); + + loginServiceName = JaasLoginService.OBJECT_NAME; + loginServiceGBean = new GBeanData(loginServiceName, JaasLoginService.GBEAN_INFO); + loginServiceGBean.setReferencePattern("Realms", new ObjectName("geronimo.server:j2eeType=SecurityRealm,*")); + loginServiceGBean.setAttribute("algorithm", "HmacSHA1"); + loginServiceGBean.setAttribute("password", "secret"); + + propertiesLMName = new ObjectName("geronimo.security:type=LoginModule,name=demo-properties-login"); + propertiesLMGBean = new GBeanData(propertiesLMName, LoginModuleGBean.GBEAN_INFO); + propertiesLMGBean.setAttribute("loginModuleClass", "org.apache.geronimo.security.realm.providers.PropertiesFileLoginModule"); + propertiesLMGBean.setAttribute("serverSide", Boolean.TRUE); + Properties options = new Properties(); + options.setProperty("usersURI", "src/test-resources/data/users.properties"); + options.setProperty("groupsURI", "src/test-resources/data/groups.properties"); + propertiesLMGBean.setAttribute("options", options); + propertiesLMGBean.setAttribute("loginDomainName", "demo-properties-realm"); + + propertiesRealmName = new ObjectName("geronimo.server:j2eeType=SecurityRealm,name=demo-properties-realm"); + propertiesRealmGBean = new GBeanData(propertiesRealmName, GenericSecurityRealm.GBEAN_INFO); + propertiesRealmGBean.setReferencePattern("ServerInfo", serverInfoName); + propertiesRealmGBean.setAttribute("realmName", "demo-properties-realm"); + Properties config = new Properties(); + config.setProperty("LoginModule.1.REQUIRED", propertiesLMName.getCanonicalName()); + propertiesRealmGBean.setAttribute("loginModuleConfiguration", config); + Principal.PrincipalEditor principalEditor = new Principal.PrincipalEditor(); + principalEditor.setAsText("metro=org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); + propertiesRealmGBean.setAttribute("defaultPrincipal", principalEditor.getValue()); + + start(loginConfigurationGBean); + start(securityServiceGBean); + start(loginServiceGBean); + start(propertiesLMGBean); + start(propertiesRealmGBean); + + } + + protected void tearDownSecurity() throws Exception { + stop(propertiesRealmName); + stop(propertiesLMName); + stop(loginServiceName); + stop(securityServiceName); + stop(loginConfigurationName); + } + + private void start(GBeanData gbeanData) throws Exception { + kernel.loadGBean(gbeanData, cl); + kernel.startGBean(gbeanData.getName()); + if (((Integer) kernel.getAttribute(gbeanData.getName(), "state")).intValue() != State.RUNNING_INDEX) { + fail("gbean not started: " + gbeanData.getName()); + } + } + + protected void stop(ObjectName name) throws Exception { + kernel.stopGBean(name); + kernel.unloadGBean(name); + } + + protected void setUp() throws Exception { + cl = this.getClass().getClassLoader(); + containerName = NameFactory.getWebComponentName(null, null, null, null, "tomcatContainer", "WebResource", moduleContext); + connectorName = NameFactory.getWebComponentName(null, null, null, null, "tomcatConnector", "WebResource", moduleContext); + webModuleName = NameFactory.getWebComponentName(null, null, null, null, NameFactory.WEB_MODULE, "WebResource", moduleContext); + + tmName = NameFactory.getComponentName(null, null, null, null, "TransactionManager", NameFactory.JTA_RESOURCE, moduleContext); + tcmName = NameFactory.getComponentName(null, null, null, null, "TransactionContextManager", NameFactory.JTA_RESOURCE, moduleContext); + + ctcName = new ObjectName("geronimo.test:role=ConnectionTrackingCoordinator"); + + kernel = new Kernel("test.kernel"); + kernel.boot(); + + serverInfoName = new ObjectName("geronimo.system:role=ServerInfo"); + serverInfoGBean = new GBeanData(serverInfoName, ServerInfo.GBEAN_INFO); + serverInfoGBean.setAttribute("baseDirectory", "."); + + start(serverInfoGBean); + + // Need to override the constructor for unit tests + container = new GBeanData(containerName, TomcatContainer.GBEAN_INFO); + container.setAttribute("catalinaHome", "target/var/catalina"); + container.setAttribute("endorsedDirs", "target/endorsed"); + container.setReferencePattern("ServerInfo", serverInfoName); + + connector = new GBeanData(connectorName, HTTPConnector.GBEAN_INFO); + connector.setAttribute("port", new Integer(8080)); + connector.setReferencePattern("TomcatContainer", containerName); + + start(container); + start(connector); + + tm = new GBeanData(tmName, TransactionManagerImpl.GBEAN_INFO); + Set patterns = new HashSet(); + patterns.add(ObjectName.getInstance("geronimo.server:j2eeType=JCAManagedConnectionFactory,*")); + tm.setAttribute("defaultTransactionTimeoutSeconds", new Integer(10)); + tm.setReferencePatterns("ResourceManagers", patterns); + start(tm); + tcm = new GBeanData(tcmName, TransactionContextManager.GBEAN_INFO); + tcm.setReferencePattern("TransactionManager", tmName); + start(tcm); + ctc = new GBeanData(ctcName, ConnectionTrackingCoordinator.GBEAN_INFO); + start(ctc); + } + + protected void tearDown() throws Exception { + stop(ctcName); + stop(tmName); + stop(containerName); + stop(serverInfoName); + kernel.shutdown(); + } +} Modified: geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java?view=diff&rev=125716&p1=geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java&r1=125715&p2=geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java&r2=125716 ============================================================================== --- geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java (original) +++ geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/ApplicationTest.java Wed Jan 19 21:21:50 2005 @@ -1,40 +1,41 @@ -/** - * - * Copyright 2003-2004 The Apache Software Foundation - * - * Licensed 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.apache.geronimo.tomcat; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; - -/** - * @version $Rev: 111239 $ $Date: 2004-12-08 02:29:11 -0700 (Wed, 08 Dec 2004) $ - */ -public class ApplicationTest extends AbstractWebModuleTest { - - public void testApplication() throws Exception { - setUpInsecureAppContext(); - - HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/test/hello.txt") - .openConnection(); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); - assertEquals("Hello World", reader.readLine()); - connection.disconnect(); - } - -} +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + + +/** + * @version $Rev: 111239 $ $Date: 2004-12-08 02:29:11 -0700 (Wed, 08 Dec 2004) $ + */ +public class ApplicationTest extends AbstractWebModuleTest { + + public void testApplication() throws Exception { + setUpInsecureAppContext(); + + HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/test/hello.txt") + .openConnection(); + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + assertEquals("Hello World", reader.readLine()); + connection.disconnect(); + } + +} Added: geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JAASSecurityTest.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JAASSecurityTest.java?view=auto&rev=125716 ============================================================================== --- (empty file) +++ geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JAASSecurityTest.java Wed Jan 19 21:21:50 2005 @@ -0,0 +1,228 @@ +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; +import javax.management.ObjectName; + +import org.apache.catalina.deploy.SecurityCollection; +import org.apache.catalina.deploy.SecurityConstraint; + + +/** + * Tests the JAAS security for Tomcat + * + * @version $Revision$ $Date$ + */ +public class JAASSecurityTest extends AbstractWebModuleTest { + + ObjectName appName = null; + + public void testNotAuthorized() throws Exception { + + Set constraints = new HashSet(); + + SecurityConstraint sc = new SecurityConstraint(); + sc.setAuthConstraint(true); + sc.addAuthRole("content-administrator"); + sc.addAuthRole("auto-administrator"); + SecurityCollection coll = new SecurityCollection("Admin Role"); + coll.addPattern("/protected/*"); + sc.addCollection(coll); + constraints.add(sc); + + sc = new SecurityConstraint(); + sc.setAuthConstraint(false); + coll = new SecurityCollection("NO ACCESS"); + coll.addPattern("/auth/logon.html"); + sc.addCollection(coll); + constraints.add(sc); + + Set securityRoles = new HashSet(); + securityRoles.add("content-administrator"); + securityRoles.add("auto-administrator"); + + startWebApp(constraints, securityRoles); + + //Begin the test + HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + //Be sure we have been given the login page + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals("<!-- Login Page -->", reader.readLine()); + reader.close(); + + String cookie = connection.getHeaderField("Set-Cookie"); + cookie = cookie.substring(0, cookie.lastIndexOf(';')); + String location = "http://localhost:8080/securetest/protected/j_security_check?j_username=alan&j_password=starcraft"; + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); + + location = connection.getHeaderField("Location"); + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(true); + assertEquals(HttpURLConnection.HTTP_FORBIDDEN, connection.getResponseCode()); + connection.disconnect(); + + stopWebApp(); + } + + public void testBadAuthentication() throws Exception { + + Set constraints = new HashSet(); + + SecurityConstraint sc = new SecurityConstraint(); + sc.setAuthConstraint(true); + sc.addAuthRole("content-administrator"); + sc.addAuthRole("auto-administrator"); + SecurityCollection coll = new SecurityCollection("Admin Role"); + coll.addPattern("/protected/*"); + sc.addCollection(coll); + constraints.add(sc); + + sc = new SecurityConstraint(); + sc.setAuthConstraint(false); + coll = new SecurityCollection("NO ACCESS"); + coll.addPattern("/auth/logon.html"); + sc.addCollection(coll); + constraints.add(sc); + + Set securityRoles = new HashSet(); + securityRoles.add("content-administrator"); + securityRoles.add("auto-administrator"); + + startWebApp(constraints, securityRoles); + + //Begin the test + HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + + //Be sure we have been given the login page + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals("<!-- Login Page -->", reader.readLine()); + reader.close(); + + String cookie = connection.getHeaderField("Set-Cookie"); + cookie = cookie.substring(0, cookie.lastIndexOf(';')); + String location = "http://localhost:8080/securetest/protected/j_security_check?j_username=alan&j_password=basspassword"; + + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(true); + + //Be sure we have been given the login error page + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + + location = connection.getHeaderField("Location"); + assertEquals("<!-- Not Authorized -->", reader.readLine()); + reader.close(); + + connection.disconnect(); + + stopWebApp(); + } + + public void testGoodAuthentication() throws Exception { + + Set constraints = new HashSet(); + + SecurityConstraint sc = new SecurityConstraint(); + sc.setAuthConstraint(true); + sc.addAuthRole("content-administrator"); + sc.addAuthRole("auto-administrator"); + SecurityCollection coll = new SecurityCollection("Admin Role"); + coll.addPattern("/protected/*"); + sc.addCollection(coll); + constraints.add(sc); + + sc = new SecurityConstraint(); + sc.setAuthConstraint(false); + coll = new SecurityCollection("NO ACCESS"); + coll.addPattern("/auth/logon.html"); + sc.addCollection(coll); + constraints.add(sc); + + Set securityRoles = new HashSet(); + securityRoles.add("content-administrator"); + securityRoles.add("auto-administrator"); + + startWebApp(constraints, securityRoles); + + //Begin the test + HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + + //Be sure we have been given the login page + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals("<!-- Login Page -->", reader.readLine()); + reader.close(); + + String cookie = connection.getHeaderField("Set-Cookie"); + cookie = cookie.substring(0, cookie.lastIndexOf(';')); + String location = "http://localhost:8080/securetest/protected/j_security_check?j_username=izumi&j_password=violin"; + + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); + + connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + assertEquals("Hello World", reader.readLine()); + connection.disconnect(); + + stopWebApp(); + } + + protected void startWebApp(Set securityConstraints, Set securityRoles) throws Exception { + appName = setUpJAASSecureAppContext(securityConstraints, securityRoles); + } + + protected void stopWebApp() throws Exception { + stop(appName); + } + + protected void setUp() throws Exception { + super.setUp(); + setUpSecurity(); + } + + protected void tearDown() throws Exception { + tearDownSecurity(); + super.tearDown(); + } + +} Added: geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JACCSecurityTest.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JACCSecurityTest.java?view=auto&rev=125716 ============================================================================== --- (empty file) +++ geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/JACCSecurityTest.java Wed Jan 19 21:21:50 2005 @@ -0,0 +1,215 @@ +/** + * + * Copyright 2003-2004 The Apache Software Foundation + * + * Licensed 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.apache.geronimo.tomcat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.management.ObjectName; +import javax.security.jacc.WebResourcePermission; +import javax.security.jacc.WebUserDataPermission; + +import org.apache.catalina.deploy.SecurityCollection; +import org.apache.catalina.deploy.SecurityConstraint; + +import org.apache.geronimo.security.deploy.DefaultPrincipal; +import org.apache.geronimo.security.deploy.Principal; +import org.apache.geronimo.security.deploy.Realm; +import org.apache.geronimo.security.deploy.Role; +import org.apache.geronimo.security.deploy.Security; + + +/** + * Tests the JACC security for Tomcat + * + * @version $Revision$ $Date$ + */ +public class JACCSecurityTest extends AbstractWebModuleTest { + + ObjectName appName = null; + + /** + * Test the explicit map feature. Only Alan should be able to log in. + * + * @throws Exception thrown if an error in the test occurs + */ + public void testExplicitMapping() throws Exception { + + Set constraints = new HashSet(); + + SecurityConstraint sc = new SecurityConstraint(); + sc.setAuthConstraint(true); + sc.addAuthRole("content-administrator"); + sc.addAuthRole("auto-administrator"); + SecurityCollection coll = new SecurityCollection("Admin Role"); + coll.addPattern("/protected/*"); + sc.addCollection(coll); + constraints.add(sc); + + sc = new SecurityConstraint(); + sc.setAuthConstraint(false); + coll = new SecurityCollection("NO ACCESS"); + coll.addPattern("/auth/logon.html"); + sc.addCollection(coll); + constraints.add(sc); + + Security securityConfig = new Security(); + securityConfig.setUseContextHandler(false); + + DefaultPrincipal defaultPrincipal = new DefaultPrincipal(); + defaultPrincipal.setRealmName("demo-properties-realm"); + Principal principal = new Principal(); + principal.setClassName("org.apache.geronimo.security.realm.providers.GeronimoUserPrincipal"); + principal.setPrincipalName("izumi"); + defaultPrincipal.setPrincipal(principal); + + securityConfig.setDefaultPrincipal(defaultPrincipal); + + Role role = new Role(); + role.setRoleName("content-administrator"); + principal = new Principal(); + principal.setClassName("org.apache.geronimo.security.realm.providers.GeronimoGroupPrincipal"); + principal.setPrincipalName("it"); + Realm realm = new Realm(); + realm.setRealmName("demo-properties-realm"); + realm.getPrincipals().add(principal); + role.getRealms().put(realm.getRealmName(), realm); + + securityConfig.getRoleMappings().put(role.getRoleName(), role); + + PermissionCollection uncheckedPermissions = new Permissions(); + + PermissionCollection excludedPermissions = new Permissions(); + excludedPermissions.add(new WebResourcePermission("/auth/login.html", "")); + excludedPermissions.add(new WebUserDataPermission("/auth/login.html", "")); + + Map rolePermissions = new HashMap(); + Set permissions = new HashSet(); + permissions.add(new WebUserDataPermission("/protected/*", "")); + permissions.add(new WebResourcePermission("/protected/*", "")); + rolePermissions.put("content-administrator", permissions); + rolePermissions.put("auto-administrator", permissions); + + Set securityRoles = new HashSet(); + securityRoles.add("content-administrator"); + securityRoles.add("auto-administrator"); + + startWebApp(securityConfig, constraints, uncheckedPermissions, excludedPermissions, rolePermissions, securityRoles); + + //Begin the test + HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + + //Be sure we have been given the login page + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals("<!-- Login Page -->", reader.readLine()); + reader.close(); + + String cookie = connection.getHeaderField("Set-Cookie"); + cookie = cookie.substring(0, cookie.lastIndexOf(';')); + String location = "http://localhost:8080/securetest/protected/j_security_check?j_username=alan&j_password=starcraft"; + + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); + + connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + assertEquals("Hello World", reader.readLine()); + connection.disconnect(); + + //Now lets try it with izumi + connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode()); + + cookie = connection.getHeaderField("Set-Cookie"); + cookie = cookie.substring(0, cookie.lastIndexOf(';')); + + //Be sure we have been given the login page + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + assertEquals("<!-- Login Page -->", reader.readLine()); + reader.close(); + + location = "http://localhost:8080/securetest/protected/j_security_check?j_username=izumi&j_password=violin"; + + connection = (HttpURLConnection) new URL(location).openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, connection.getResponseCode()); + + try { + connection = (HttpURLConnection) new URL("http://localhost:8080/securetest/protected/hello.txt").openConnection(); + connection.setRequestProperty("Cookie", cookie); + connection.setInstanceFollowRedirects(false); + reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + fail("Should throw an IOException for HTTP 403 response"); + } catch (IOException e) { + } + + assertEquals(HttpURLConnection.HTTP_FORBIDDEN, connection.getResponseCode()); + connection.disconnect(); + + + stopWebApp(); + } + + protected void startWebApp(Security securityConfig, + Set securityConstraints, + PermissionCollection uncheckedPermissions, + PermissionCollection excludedPermissions, + Map rolePermissions, + Set securityRoles) throws Exception { + + appName = setUpSecureAppContext(securityConfig, securityConstraints, uncheckedPermissions, + excludedPermissions, rolePermissions, securityRoles); + + + } + + protected void stopWebApp() throws Exception { + stop(appName); + } + + protected void setUp() throws Exception { + super.setUp(); + setUpSecurity(); + } + + protected void tearDown() throws Exception { + tearDownSecurity(); + super.tearDown(); + } + +} Deleted: /geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/SecurityTest.java Url: http://svn.apache.org/viewcvs/geronimo/trunk/modules/tomcat/src/test/org/apache/geronimo/tomcat/SecurityTest.java?view=auto&rev=125715 ==============================================================================