1
0
mirror of synced 2026-07-16 16:15:12 +00:00

Compare commits

..

2 Commits

Author SHA1 Message Date
Luke Taylor 45253ca148 Updated sandbox pom versions to match release 2008-06-04 09:56:08 +00:00
Luke Taylor 807ae835b8 [maven-release-plugin] copy for tag spring-security-parent-2.0.2 2008-06-03 16:06:44 +00:00
1011 changed files with 37274 additions and 33724 deletions
+7
View File
@@ -0,0 +1,7 @@
dist
target
build.properties
*.log
.clover
*.keystore
server-work
+205
View File
@@ -0,0 +1,205 @@
<?xml version="1.0"?>
<!--
/*
* Copyright 2001-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.
*/
-->
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.2//EN"
"http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<!--
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.sf.net (or in your downloaded distribution).
Most Checks are configurable, be sure to consult the documentation.
To completely disable a check, just comment it out or delete it from the file.
Finally, it is worth reading the documentation.
-->
<module name="Checker">
<!-- Checks that a package.html file exists for each package. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html#PackageHtml -->
<!-- module name="PackageHtml"/ -->
<!-- Checks whether files end with a new line. -->
<!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
<module name="NewlineAtEndOfFile"/>
<!-- Checks that property files contain the same keys. -->
<!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
<module name="Translation"/>
<module name="TreeWalker">
<property name="cacheFile" value="${checkstyle.cache.file}"/>
<!-- Checks for Javadoc comments. -->
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
<!--
<module name="JavadocMethod"/>
<module name="JavadocType"/>
<module name="JavadocVariable"/>
<module name="JavadocStyle"/>
-->
<!-- Checks for Naming Conventions. -->
<!-- See http://checkstyle.sf.net/config_naming.html -->
<module name="ConstantName">
<!-- logger variables break normal constant syntax. We need to allow lower case too -->
<property name="format" value="^[a-zA-Z][a-zA-Z0-9]*(_[A-Z0-9]+)*$"/>
</module>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<!-- Checks for Headers -->
<!-- See http://checkstyle.sf.net/config_header.html -->
<!-- <module name="Header"> -->
<!-- The follow property value demonstrates the ability -->
<!-- to have access to ANT properties. In this case it uses -->
<!-- the ${basedir} property to allow Checkstyle to be run -->
<!-- from any directory within a project. See property -->
<!-- expansion, -->
<!-- http://checkstyle.sf.net/config.html#properties -->
<!-- <property -->
<!-- name="headerFile" -->
<!-- value="${basedir}/java.header"/> -->
<!-- </module> -->
<!-- Following interprets the header file as regular expressions. -->
<!-- <module name="RegexpHeader"/> -->
<!-- Checks for imports -->
<!-- See http://checkstyle.sf.net/config_imports.html -->
<module name="AvoidStarImport">
<property name="excludes" value="javax.servlet,java.util"/>
</module>
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
<module name="RedundantImport"/>
<!--module name="UnusedImports"/ -->
<!-- Checks for Size Violations. -->
<!-- See http://checkstyle.sf.net/config_sizes.html -->
<module name="FileLength"/>
<module name="LineLength">
<property name="max" value="125"/>
</module>
<module name="MethodLength"/>
<module name="ParameterNumber"/>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="EmptyForIteratorPad"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="TabCharacter"/>
<module name="WhitespaceAfter"/>
<!--
<module name="WhitespaceAround">
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyConstructors" value="true"/>
</module>
-->
<!-- Modifier Checks -->
<!-- See http://checkstyle.sf.net/config_modifiers.html -->
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<!-- Checks for blocks. You know, those {}'s -->
<!-- See http://checkstyle.sf.net/config_blocks.html -->
<module name="AvoidNestedBlocks"/>
<!-- module name="EmptyBlock"/ -->
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>
<!-- Checks for common coding problems -->
<!-- See http://checkstyle.sf.net/config_coding.html -->
<!-- module name="AvoidInlineConditionals"/ -->
<module name="DoubleCheckedLocking"/> <!-- MY FAVOURITE -->
<module name="EmptyStatement"/>
<!-- module name="EqualsHashCode"/ -->
<!--
<module name="HiddenField">
<property name="ignoreConstructorParameter" value="true"/>
<property name="ignoreSetter" value="true"/>
</module>
-->
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<!-- module name="MagicNumber"/ -->
<module name="MissingSwitchDefault"/>
<!--
<module name="RedundantThrows">
<property name="allowUnchecked" value="true"/>
</module>
-->
<!--
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
-->
<!-- Checks for class design -->
<!-- See http://checkstyle.sf.net/config_design.html -->
<!-- module name="DesignForExtension"/ -->
<module name="FinalClass"/>
<module name="HideUtilityClassConstructor"/>
<module name="InterfaceIsType"/>
<module name="VisibilityModifier">
<!-- logger variables are often protected -->
<property name="protectedAllowed" value="true"/>
</module>
<!-- Miscellaneous other checks. -->
<!-- See http://checkstyle.sf.net/config_misc.html -->
<module name="ArrayTypeStyle"/>
<!-- module name="FinalParameters"/ -->
<!--
<module name="GenericIllegalRegexp">
<property name="format" value="\s+$"/>
<property name="message" value="Line has trailing spaces."/>
</module>
-->
<!-- module name="TrailingComment"/ -->
<!-- module name="TodoComment"/ -->
<module name="UpperEll"/>
</module>
</module>
+30 -22
View File
@@ -3,13 +3,14 @@
<parent>
<artifactId>spring-security-parent</artifactId>
<groupId>org.springframework.security</groupId>
<version>2.5.0.M1</version>
<version>2.0.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-acl</artifactId>
<name>Spring Security - ACL module</name>
<packaging>jar</packaging>
<version>2.0.2</version>
<packaging>bundle</packaging>
<dependencies>
<dependency>
@@ -17,15 +18,6 @@
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<!--
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
@@ -35,15 +27,11 @@
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.context.support</artifactId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.test</artifactId>
<artifactId>spring-mock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -56,10 +44,30 @@
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmock</groupId>
<artifactId>jmock-junit4</artifactId>
</dependency>
</dependencies>
<properties>
<spring.osgi.export>
org.springframework.security.*;version=${pom.version.osgi}
</spring.osgi.export>
<spring.osgi.import>
net.sf.ehcache.*;version="[1.4.1, 2.0.0)";resolution:=optional,
org.springframework.security.*;version="[${pom.version.osgi},${pom.version.osgi}]",
org.springframework.context.*;version="${spring.version.osgi}",
org.springframework.dao.*;version="${spring.version.osgi}";resolution:=optional,
org.springframework.jdbc.*;version="${spring.version.osgi}";resolution:=optional,
org.springframework.transaction.support.*;version="${spring.version.osgi}";resolution:=optional,
org.springframework.util.*;version="${spring.version.osgi}",
org.apache.commons.logging.*;version="[1.1.1, 2.0.0)",
javax.sql.*
</spring.osgi.import>
</project>
<spring.osgi.private.pkg>
!org.springframework.security.*
</spring.osgi.private.pkg>
<spring.osgi.symbolic.name>org.springframework.security.acls</spring.osgi.symbolic.name>
</properties>
</project>
@@ -18,7 +18,6 @@ import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.Sid;
import java.io.Serializable;
import java.util.List;
/**
@@ -45,7 +44,7 @@ import java.util.List;
*/
public interface Acl extends Serializable {
/**
/**
* Returns all of the entries represented by the present <tt>Acl</tt>. Entries associated with
* the <tt>Acl</tt> parents are not returned.
*
@@ -56,7 +55,7 @@ public interface Acl extends Serializable {
* part of advanced permission checking.</p>
*
* <p>Do <em>NOT</em> use this method for making authorization decisions. Instead use {@link
* #isGranted(List, List, boolean)}.</p>
* #isGranted(Permission[], Sid[], boolean)}.</p>
*
* <p>This method must operate correctly even if the <tt>Acl</tt> only represents a subset of
* <tt>Sid</tt>s. The caller is responsible for correctly handling the result if only a subset of
@@ -65,7 +64,7 @@ public interface Acl extends Serializable {
* @return the list of entries represented by the <tt>Acl</tt>, or <tt>null</tt> if there are
* no entries presently associated with this <tt>Acl</tt>.
*/
List<AccessControlEntry> getEntries();
AccessControlEntry[] getEntries();
/**
* Obtains the domain object this <tt>Acl</tt> provides entries for. This is immutable once an
@@ -147,7 +146,7 @@ public interface Acl extends Serializable {
* @throws UnloadedSidException thrown if the <tt>Acl</tt> does not have details for one or more of the
* <tt>Sid</tt>s passed as arguments
*/
boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode)
boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException;
/**
@@ -167,5 +166,5 @@ public interface Acl extends Serializable {
*
* @return <tt>true</tt> if every passed <tt>Sid</tt> is represented by this <tt>Acl</tt> instance
*/
boolean isSidLoaded(List<Sid> sids);
boolean isSidLoaded(Sid[] sids);
}
@@ -1,137 +0,0 @@
package org.springframework.security.acls;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.Authentication;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.objectidentity.ObjectIdentityGenerator;
import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalStrategy;
import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalStrategyImpl;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategyImpl;
import org.springframework.security.expression.PermissionEvaluator;
/**
* Used by Spring Security's expression-based access control implementation to evaluate permissions for a particular
* object using the ACL module. Similar in behaviour to
* {@link org.springframework.security.vote.AclEntryVoter AclEntryVoter}.
*
* @author Luke Taylor
* @version $Id$
* @since 2.5
*/
public class AclPermissionEvaluator implements PermissionEvaluator {
private final Log logger = LogFactory.getLog(getClass());
private AclService aclService;
private ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
private ObjectIdentityGenerator objectIdentityGenerator = new ObjectIdentityRetrievalStrategyImpl();
private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
public AclPermissionEvaluator(AclService aclService) {
this.aclService = aclService;
}
/**
* Determines whether the user has the given permission(s) on the domain object using the ACL
* configuration. If the domain object is null, returns false (this can always be overridden using a null
* check in the expression itself).
*/
public boolean hasPermission(Authentication authentication, Object domainObject, Object permission) {
if (domainObject == null) {
return false;
}
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
return checkPermission(authentication, objectIdentity, permission);
}
public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
ObjectIdentity objectIdentity = objectIdentityGenerator.createObjectIdentity(targetId, targetType);
return checkPermission(authentication, objectIdentity, permission);
}
private boolean checkPermission(Authentication authentication, ObjectIdentity oid, Object permission) {
// Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication);
List<Permission> requiredPermission = resolvePermission(permission);
try {
// Lookup only ACLs for SIDs we're interested in
Acl acl = aclService.readAclById(oid, sids);
if (acl.isGranted(requiredPermission, sids, false)) {
if (logger.isDebugEnabled()) {
logger.debug("Access is granted");
}
return true;
}
if (logger.isDebugEnabled()) {
logger.debug("Returning false - ACLs returned, but insufficient permissions for this principal");
}
} catch (NotFoundException nfe) {
if (logger.isDebugEnabled()) {
logger.debug("Returning false - no ACLs apply for this principal");
}
}
return false;
}
// TODO: Add permission resolver/PermissionFactory rewrite
List<Permission> resolvePermission(Object permission) {
if (permission instanceof Integer) {
return Arrays.asList(BasePermission.buildFromMask(((Integer)permission).intValue()));
}
if (permission instanceof Permission) {
return Arrays.asList((Permission)permission);
}
if (permission instanceof Permission[]) {
return Arrays.asList((Permission[])permission);
}
if (permission instanceof String) {
String permString = (String)permission;
Permission p = null;
try {
p = BasePermission.buildFromName(permString);
} catch(IllegalArgumentException notfound) {
p = BasePermission.buildFromName(permString.toUpperCase());
}
if (p != null) {
return Arrays.asList(p);
}
}
throw new IllegalArgumentException("unsupported permission: " + permission);
}
public void setObjectIdentityRetrievalStrategy(ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy) {
this.objectIdentityRetrievalStrategy = objectIdentityRetrievalStrategy;
}
public void setObjectIdentityGenerator(ObjectIdentityGenerator objectIdentityGenerator) {
this.objectIdentityGenerator = objectIdentityGenerator;
}
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) {
this.sidRetrievalStrategy = sidRetrievalStrategy;
}
}
@@ -17,7 +17,6 @@ package org.springframework.security.acls;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.Sid;
import java.util.List;
import java.util.Map;
@@ -37,13 +36,12 @@ public interface AclService {
*
* @return the children (or <tt>null</tt> if none were found)
*/
List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity);
ObjectIdentity[] findChildren(ObjectIdentity parentIdentity);
/**
* Same as {@link #readAclsById(Java.util.List<ObjectIdentity>)} except it returns only a single Acl.
* <p>
* This method should not be called as it does not leverage the underlying implementation's potential ability to
* filter <tt>Acl</tt> entries based on a {@link Sid} parameter.</p>
* Same as {@link #readAclsById(ObjectIdentity[])} except it returns only a single Acl.<p>This method
* should not be called as it does not leverage the underlaying implementation's potential ability to filter
* <tt>Acl</tt> entries based on a {@link Sid} parameter.</p>
*
* @param object to locate an {@link Acl} for
*
@@ -54,17 +52,18 @@ public interface AclService {
Acl readAclById(ObjectIdentity object) throws NotFoundException;
/**
* Same as {@link #readAclsById(List, List)} except it returns only a single Acl.
* Same as {@link #readAclsById(ObjectIdentity[], Sid[])} except it returns only a single Acl.
*
* @param object to locate an {@link Acl} for
* @param sids the security identities for which {@link Acl} information is required
* @param sids the security identities for which {@link Acl} information is required
* (may be <tt>null</tt> to denote all entries)
*
* @return the {@link Acl} for the requested {@link ObjectIdentity} (never <tt>null</tt>)
*
* @throws NotFoundException if an {@link Acl} was not found for the requested {@link ObjectIdentity}
*/
Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException;
Acl readAclById(ObjectIdentity object, Sid[] sids)
throws NotFoundException;
/**
* Obtains all the <tt>Acl</tt>s that apply for the passed <tt>Object</tt>s.<p>The returned map is
@@ -77,7 +76,7 @@ public interface AclService {
*
* @throws NotFoundException if an {@link Acl} was not found for each requested {@link ObjectIdentity}
*/
Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException;
Map readAclsById(ObjectIdentity[] objects) throws NotFoundException;
/**
* Obtains all the <tt>Acl</tt>s that apply for the passed <tt>Object</tt>s, but only for the
@@ -90,12 +89,13 @@ public interface AclService {
* not have a map key.</p>
*
* @param objects the objects to find {@link Acl} information for
* @param sids the security identities for which {@link Acl} information is required
* @param sids the security identities for which {@link Acl} information is required
* (may be <tt>null</tt> to denote all entries)
*
* @return a map with exactly one element for each {@link ObjectIdentity} passed as an argument (never <tt>null</tt>)
*
* @throws NotFoundException if an {@link Acl} was not found for each requested {@link ObjectIdentity}
*/
Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException;
Map readAclsById(ObjectIdentity[] objects, Sid[] sids)
throws NotFoundException;
}
@@ -26,7 +26,7 @@ import org.springframework.security.SpringSecurityException;
public class AlreadyExistsException extends SpringSecurityException {
//~ Constructors ===================================================================================================
/**
/**
* Constructs an <code>AlreadyExistsException</code> with the specified message.
*
* @param msg the detail message
@@ -35,7 +35,7 @@ public class AlreadyExistsException extends SpringSecurityException {
super(msg);
}
/**
/**
* Constructs an <code>AlreadyExistsException</code> with the specified message
* and root cause.
*
@@ -14,6 +14,8 @@
*/
package org.springframework.security.acls;
/**
* A mutable ACL that provides audit capabilities.
*
@@ -26,7 +26,7 @@ import org.springframework.security.SpringSecurityException;
public class ChildrenExistException extends SpringSecurityException {
//~ Constructors ===================================================================================================
/**
/**
* Constructs an <code>ChildrenExistException</code> with the specified
* message.
*
@@ -36,7 +36,7 @@ public class ChildrenExistException extends SpringSecurityException {
super(msg);
}
/**
/**
* Constructs an <code>ChildrenExistException</code> with the specified
* message and root cause.
*
@@ -26,7 +26,7 @@ import org.springframework.security.SpringSecurityException;
public class IdentityUnavailableException extends SpringSecurityException {
//~ Constructors ===================================================================================================
/**
/**
* Constructs an <code>IdentityUnavailableException</code> with the specified message.
*
* @param msg the detail message
@@ -35,7 +35,7 @@ public class IdentityUnavailableException extends SpringSecurityException {
super(msg);
}
/**
/**
* Constructs an <code>IdentityUnavailableException</code> with the specified message
* and root cause.
*
@@ -21,9 +21,11 @@ import org.springframework.security.acls.sid.Sid;
/**
* A mutable <tt>Acl</tt>.
*
* <p>
* A mutable ACL must ensure that appropriate security checks are performed
* before allowing access to its methods.
* </p>
*
* @author Ben Alex
* @version $Id$
@@ -45,7 +47,7 @@ public interface MutableAcl extends Acl {
/**
* Changes the present owner to a different owner.
*
*
* @param newOwner the new owner (mandatory; cannot be null)
*/
void setOwner(Sid newOwner);
@@ -55,6 +55,8 @@ public interface MutableAclService extends AclService {
*
* @param acl to modify
*
* @return DOCUMENT ME!
*
* @throws NotFoundException if the relevant record could not be found (did you remember to use {@link
* #createAcl(ObjectIdentity)} to create the object, rather than creating it with the <code>new</code>
* keyword?)
@@ -26,7 +26,7 @@ import org.springframework.security.SpringSecurityException;
public class NotFoundException extends SpringSecurityException {
//~ Constructors ===================================================================================================
/**
/**
* Constructs an <code>NotFoundException</code> with the specified message.
*
* @param msg the detail message
@@ -35,7 +35,7 @@ public class NotFoundException extends SpringSecurityException {
super(msg);
}
/**
/**
* Constructs an <code>NotFoundException</code> with the specified message
* and root cause.
*
@@ -23,6 +23,7 @@ import org.springframework.security.acls.sid.Sid;
* <p>
* Generally the owner of an ACL is able to call any ACL mutator method, as
* well as assign a new owner.
* </p>
*
* @author Ben Alex
* @version $Id$
@@ -27,7 +27,7 @@ import org.springframework.security.SpringSecurityException;
public class UnloadedSidException extends SpringSecurityException {
//~ Constructors ===================================================================================================
/**
/**
* Constructs an <code>NotFoundException</code> with the specified message.
*
* @param msg the detail message
@@ -36,7 +36,7 @@ public class UnloadedSidException extends SpringSecurityException {
super(msg);
}
/**
/**
* Constructs an <code>NotFoundException</code> with the specified message
* and root cause.
*
@@ -1,59 +0,0 @@
package org.springframework.security.acls.domain;
import org.springframework.security.acls.AclFormattingUtils;
import org.springframework.security.acls.Permission;
/**
* Provides an abstract superclass for {@link Permission} implementations.
*
* @author Ben Alex
* @since 2.0.3
* @see AbstractRegisteredPermission
*
*/
public abstract class AbstractPermission implements Permission {
//~ Instance fields ================================================================================================
protected char code;
protected int mask;
//~ Constructors ===================================================================================================
protected AbstractPermission(int mask, char code) {
this.mask = mask;
this.code = code;
}
//~ Methods ========================================================================================================
public final boolean equals(Object arg0) {
if (arg0 == null) {
return false;
}
if (!(arg0 instanceof Permission)) {
return false;
}
Permission rhs = (Permission) arg0;
return (this.mask == rhs.getMask());
}
public final int getMask() {
return mask;
}
public String getPattern() {
return AclFormattingUtils.printBinary(mask, code);
}
public final String toString() {
return this.getClass().getSimpleName() + "[" + getPattern() + "=" + mask + "]";
}
public final int hashCode() {
return this.mask;
}
}
@@ -68,45 +68,45 @@ public class AccessControlEntryImpl implements AccessControlEntry, AuditableAcce
AccessControlEntryImpl rhs = (AccessControlEntryImpl) arg0;
if (this.acl == null) {
if (rhs.getAcl() != null) {
return false;
}
// Both this.acl and rhs.acl are null and thus equal
if (rhs.getAcl() != null) {
return false;
}
// Both this.acl and rhs.acl are null and thus equal
} else {
// this.acl is non-null
if (rhs.getAcl() == null) {
return false;
}
// Both this.acl and rhs.acl are non-null, so do a comparison
if (this.acl.getObjectIdentity() == null) {
if (rhs.acl.getObjectIdentity() != null) {
return false;
}
// Both this.acl and rhs.acl are null and thus equal
} else {
// Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null
if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) {
return false;
}
}
// this.acl is non-null
if (rhs.getAcl() == null) {
return false;
}
// Both this.acl and rhs.acl are non-null, so do a comparison
if (this.acl.getObjectIdentity() == null) {
if (rhs.acl.getObjectIdentity() != null) {
return false;
}
// Both this.acl and rhs.acl are null and thus equal
} else {
// Both this.acl.objectIdentity and rhs.acl.objectIdentity are non-null
if (!this.acl.getObjectIdentity().equals(rhs.getAcl().getObjectIdentity())) {
return false;
}
}
}
if (this.id == null) {
if (rhs.id != null) {
return false;
}
// Both this.id and rhs.id are null and thus equal
if (rhs.id != null) {
return false;
}
// Both this.id and rhs.id are null and thus equal
} else {
// this.id is non-null
if (rhs.id == null) {
return false;
}
// this.id is non-null
if (rhs.id == null) {
return false;
}
// Both this.id and rhs.id are non-null
if (!this.id.equals(rhs.id)) {
return false;
}
// Both this.id and rhs.id are non-null
if (!this.id.equals(rhs.id)) {
return false;
}
}
if ((this.auditFailure != rhs.isAuditFailure()) || (this.auditSuccess != rhs.isAuditSuccess())
@@ -15,28 +15,27 @@
package org.springframework.security.acls.domain;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategyImpl;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.util.Assert;
/**
* Default implementation of {@link AclAuthorizationStrategy}.
* <p>
* Permission will be granted provided the current principal is either the owner (as defined by the ACL), has
* {@link BasePermission#ADMINISTRATION} (as defined by the ACL and via a {@link Sid} retrieved for the current
* principal via {@link #sidRetrievalStrategy}), or if the current principal holds the relevant system-wide
* {@link GrantedAuthority} and injected into the constructor.
* Default implementation of {@link AclAuthorizationStrategy}.<p>Permission will be granted provided the current
* principal is either the owner (as defined by the ACL), has {@link BasePermission#ADMINISTRATION} (as defined by the
* ACL and via a {@link Sid} retrieved for the current principal via {@link #sidRetrievalStrategy}), or if the current
* principal holds the relevant system-wide {@link GrantedAuthority} and injected into the constructor.</p>
*
* @author Ben Alex
* @version $Id$
@@ -51,7 +50,7 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
//~ Constructors ===================================================================================================
/**
/**
* Constructor. The only mandatory parameter relates to the system-wide {@link GrantedAuthority} instances that
* can be held to always permit ACL changes.
*
@@ -61,7 +60,8 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
* index 2 is the authority needed to change other ACL and ACE details) (required)
*/
public AclAuthorizationStrategyImpl(GrantedAuthority[] auths) {
Assert.isTrue(auths != null && auths.length == 3, "GrantedAuthority[] with three elements required");
Assert.notEmpty(auths, "GrantedAuthority[] with three elements required");
Assert.isTrue(auths.length == 3, "GrantedAuthority[] with three elements required");
this.gaTakeOwnership = auths[0];
this.gaModifyAuditing = auths[1];
this.gaGeneralChanges = auths[2];
@@ -100,23 +100,23 @@ public class AclAuthorizationStrategyImpl implements AclAuthorizationStrategy {
}
// Iterate this principal's authorities to determine right
List<GrantedAuthority> auths = authentication.getAuthorities();
GrantedAuthority[] auths = authentication.getAuthorities();
for (int i = 0; i < auths.size(); i++) {
if (requiredAuthority.equals(auths.get(i))) {
for (int i = 0; i < auths.length; i++) {
if (requiredAuthority.equals(auths[i])) {
return;
}
}
// Try to get permission via ACEs within the ACL
List<Sid> sids = sidRetrievalStrategy.getSids(authentication);
Sid[] sids = sidRetrievalStrategy.getSids(authentication);
if (acl.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), sids, false)) {
if (acl.isGranted(new Permission[] {BasePermission.ADMINISTRATION}, sids, false)) {
return;
}
throw new AccessDeniedException(
"Principal does not have required ACL permissions to perform requested operation");
"Principal does not have required ACL permissions to perform requested operation");
}
public void setSidRetrievalStrategy(SidRetrievalStrategy sidRetrievalStrategy) {
@@ -15,8 +15,9 @@
package org.springframework.security.acls.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
@@ -35,24 +36,24 @@ import org.springframework.util.Assert;
* Base implementation of <code>Acl</code>.
*
* @author Ben Alex
* @version $Id$
* @version $Id
*/
public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
//~ Instance fields ================================================================================================
private Acl parentAcl;
private transient AclAuthorizationStrategy aclAuthorizationStrategy;
private transient AuditLogger auditLogger;
private List<AccessControlEntry> aces = new ArrayList<AccessControlEntry>();
private List aces = new Vector();
private ObjectIdentity objectIdentity;
private Serializable id;
private Sid owner; // OwnershipAcl
private List<Sid> loadedSids = null; // includes all SIDs the WHERE clause covered, even if there was no ACE for a SID
private Sid[] loadedSids = null; // includes all SIDs the WHERE clause covered, even if there was no ACE for a SID
private boolean entriesInheriting = true;
//~ Constructors ===================================================================================================
/**
/**
* Minimal constructor, which should be used {@link
* org.springframework.security.acls.MutableAclService#createAcl(ObjectIdentity)}.
*
@@ -62,7 +63,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
* @param auditLogger audit logger (required)
*/
public AclImpl(ObjectIdentity objectIdentity, Serializable id, AclAuthorizationStrategy aclAuthorizationStrategy,
AuditLogger auditLogger) {
AuditLogger auditLogger) {
Assert.notNull(objectIdentity, "Object Identity required");
Assert.notNull(id, "Id required");
Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required");
@@ -73,7 +74,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
this.auditLogger = auditLogger;
}
/**
/**
* Full constructor, which should be used by persistence tools that do not
* provide field-level access features.
*
@@ -89,7 +90,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
* @param owner the owner (required)
*/
public AclImpl(ObjectIdentity objectIdentity, Serializable id, AclAuthorizationStrategy aclAuthorizationStrategy,
AuditLogger auditLogger, Acl parentAcl, List<Sid> loadedSids, boolean entriesInheriting, Sid owner) {
AuditLogger auditLogger, Acl parentAcl, Sid[] loadedSids, boolean entriesInheriting, Sid owner) {
Assert.notNull(objectIdentity, "Object Identity required");
Assert.notNull(id, "Id required");
Assert.notNull(aclAuthorizationStrategy, "AclAuthorizationStrategy required");
@@ -105,54 +106,35 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
this.owner = owner;
}
/**
/**
* Private no-argument constructor for use by reflection-based persistence
* tools along with field-level access.
*/
@SuppressWarnings("unused")
private AclImpl() {}
//~ Methods ========================================================================================================
private void verifyAceIndexExists(int aceIndex) {
if (aceIndex < 0) {
throw new NotFoundException("aceIndex must be greater than or equal to zero");
}
if (aceIndex > this.aces.size()) {
throw new NotFoundException("aceIndex must correctly refer to an index of the AccessControlEntry collection");
}
}
public void deleteAce(int aceIndex) throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
verifyAceIndexExists(aceIndex);
synchronized (aces) {
this.aces.remove(aceIndex);
}
}
private void verifyAceIndexExists(int aceIndex) {
if (aceIndex < 0) {
throw new NotFoundException("aceIndex must be greater than or equal to zero");
}
if (aceIndex > this.aces.size()) {
throw new NotFoundException("aceIndex must correctly refer to an index of the AccessControlEntry collection");
}
}
public void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting) throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.notNull(permission, "Permission required");
Assert.notNull(sid, "Sid required");
if (atIndexLocation < 0) {
throw new NotFoundException("atIndexLocation must be greater than or equal to zero");
}
if (atIndexLocation > this.aces.size()) {
throw new NotFoundException("atIndexLocation must be less than or equal to the size of the AccessControlEntry collection");
}
AccessControlEntryImpl ace = new AccessControlEntryImpl(null, this, sid, permission, granting, false, false);
synchronized (aces) {
this.aces.add(atIndexLocation, ace);
}
}
public List<AccessControlEntry> getEntries() {
public AccessControlEntry[] getEntries() {
// Can safely return AccessControlEntry directly, as they're immutable outside the ACL package
return new ArrayList<AccessControlEntry>(aces);
return (AccessControlEntry[]) aces.toArray(new AccessControlEntry[] {});
}
public Serializable getId() {
@@ -163,6 +145,33 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
return objectIdentity;
}
public Sid getOwner() {
return this.owner;
}
public Acl getParentAcl() {
return parentAcl;
}
public void insertAce(int atIndexLocation, Permission permission, Sid sid, boolean granting)
throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.notNull(permission, "Permission required");
Assert.notNull(sid, "Sid required");
if (atIndexLocation < 0) {
throw new NotFoundException("atIndexLocation must be greater than or equal to zero");
}
if (atIndexLocation > this.aces.size()) {
throw new NotFoundException("atIndexLocation must be less than or equal to the size of the AccessControlEntry collection");
}
AccessControlEntryImpl ace = new AccessControlEntryImpl(null, this, sid, permission, granting, false, false);
synchronized (aces) {
this.aces.add(atIndexLocation, ace);
}
}
public boolean isEntriesInheriting() {
return entriesInheriting;
}
@@ -198,8 +207,8 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
* @throws UnloadedSidException if the passed SIDs are unknown to this ACL because the ACL was only loaded for a
* subset of SIDs
*/
public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
public boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
Assert.notEmpty(permission, "Permissions required");
Assert.notEmpty(sids, "SIDs required");
@@ -209,14 +218,16 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
AccessControlEntry firstRejection = null;
for (Permission p : permission) {
for (Sid sid: sids) {
for (int i = 0; i < permission.length; i++) {
for (int x = 0; x < sids.length; x++) {
// Attempt to find exact match for this permission mask and SID
Iterator acesIterator = aces.iterator();
boolean scanNextSid = true;
for (AccessControlEntry ace : aces ) {
while (acesIterator.hasNext()) {
AccessControlEntry ace = (AccessControlEntry) acesIterator.next();
if ((ace.getPermission().getMask() == p.getMask()) && ace.getSid().equals(sid)) {
if ((ace.getPermission().getMask() == permission[i].getMask()) && ace.getSid().equals(sids[x])) {
// Found a matching ACE, so its authorization decision will prevail
if (ace.isGranting()) {
// Success
@@ -236,7 +247,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
scanNextSid = false; // helps break the loop
break; // exit aces loop
break; // exit "aceIterator" while loop
}
}
}
@@ -267,19 +278,19 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
}
}
public boolean isSidLoaded(List<Sid> sids) {
public boolean isSidLoaded(Sid[] sids) {
// If loadedSides is null, this indicates all SIDs were loaded
// Also return true if the caller didn't specify a SID to find
if ((this.loadedSids == null) || (sids == null) || (sids.size() == 0)) {
if ((this.loadedSids == null) || (sids == null) || (sids.length == 0)) {
return true;
}
// This ACL applies to a SID subset only. Iterate to check it applies.
for (Sid sid: sids) {
for (int i = 0; i < sids.length; i++) {
boolean found = false;
for (Sid loadedSid : loadedSids) {
if (sid.equals(loadedSid)) {
for (int y = 0; y < this.loadedSids.length; y++) {
if (sids[i].equals(this.loadedSids[y])) {
// this SID is OK
found = true;
@@ -306,20 +317,12 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
this.owner = newOwner;
}
public Sid getOwner() {
return this.owner;
}
public void setParent(Acl newParent) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.isTrue(newParent == null || !newParent.equals(this), "Cannot be the parent of yourself");
this.parentAcl = newParent;
}
public Acl getParentAcl() {
return parentAcl;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("AclImpl[");
@@ -327,16 +330,17 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
sb.append("objectIdentity: ").append(this.objectIdentity).append("; ");
sb.append("owner: ").append(this.owner).append("; ");
Iterator iterator = this.aces.iterator();
int count = 0;
for (AccessControlEntry ace : aces) {
while (iterator.hasNext()) {
count++;
if (count == 1) {
sb.append("\r\n");
}
sb.append(ace).append("\r\n");
sb.append(iterator.next().toString()).append("\r\n");
}
if (count == 0) {
@@ -356,7 +360,7 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
throws NotFoundException {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_GENERAL);
verifyAceIndexExists(aceIndex);
synchronized (aces) {
AccessControlEntryImpl ace = (AccessControlEntryImpl) aces.get(aceIndex);
ace.setPermission(permission);
@@ -366,42 +370,42 @@ public class AclImpl implements Acl, MutableAcl, AuditableAcl, OwnershipAcl {
public void updateAuditing(int aceIndex, boolean auditSuccess, boolean auditFailure) {
aclAuthorizationStrategy.securityCheck(this, AclAuthorizationStrategy.CHANGE_AUDITING);
verifyAceIndexExists(aceIndex);
synchronized (aces) {
AccessControlEntryImpl ace = (AccessControlEntryImpl) aces.get(aceIndex);
ace.setAuditSuccess(auditSuccess);
ace.setAuditFailure(auditFailure);
}
}
public boolean equals(Object obj) {
if (obj instanceof AclImpl) {
AclImpl rhs = (AclImpl) obj;
if (this.aces.equals(rhs.aces)) {
if ((this.parentAcl == null && rhs.parentAcl == null) || (this.parentAcl.equals(rhs.parentAcl))) {
if ((this.objectIdentity == null && rhs.objectIdentity == null) || (this.objectIdentity.equals(rhs.objectIdentity))) {
if ((this.id == null && rhs.id == null) || (this.id.equals(rhs.id))) {
if ((this.owner == null && rhs.owner == null) || this.owner.equals(rhs.owner)) {
if (this.entriesInheriting == rhs.entriesInheriting) {
if ((this.loadedSids == null && rhs.loadedSids == null)) {
return true;
}
if (this.loadedSids.size() == rhs.loadedSids.size()) {
for (int i = 0; i < this.loadedSids.size(); i++) {
if (!this.loadedSids.get(i).equals(rhs.loadedSids.get(i))) {
return false;
}
}
return true;
}
}
}
}
}
}
}
}
return false;
}
public boolean equals(Object obj) {
if (obj instanceof AclImpl) {
AclImpl rhs = (AclImpl) obj;
if (this.aces.equals(rhs.aces)) {
if ((this.parentAcl == null && rhs.parentAcl == null) || (this.parentAcl.equals(rhs.parentAcl))) {
if ((this.objectIdentity == null && rhs.objectIdentity == null) || (this.objectIdentity.equals(rhs.objectIdentity))) {
if ((this.id == null && rhs.id == null) || (this.id.equals(rhs.id))) {
if ((this.owner == null && rhs.owner == null) || this.owner.equals(rhs.owner)) {
if (this.entriesInheriting == rhs.entriesInheriting) {
if ((this.loadedSids == null && rhs.loadedSids == null)) {
return true;
}
if (this.loadedSids.length == rhs.loadedSids.length) {
for (int i = 0; i < this.loadedSids.length; i++) {
if (!this.loadedSids[i].equals(rhs.loadedSids[i])) {
return false;
}
}
return true;
}
}
}
}
}
}
}
}
return false;
}
}
@@ -14,59 +14,157 @@
*/
package org.springframework.security.acls.domain;
import org.springframework.security.acls.AclFormattingUtils;
import org.springframework.security.acls.Permission;
import org.springframework.util.Assert;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* A set of standard permissions.
*
* <p>
* You may subclass this class to add additional permissions, or use this class as a guide
* for creating your own permission classes.
* </p>
*
* @author Ben Alex
* @version $Id$
*/
public class BasePermission extends AbstractPermission {
public final class BasePermission implements Permission {
//~ Static fields/initializers =====================================================================================
public static final Permission READ = new BasePermission(1 << 0, 'R'); // 1
public static final Permission WRITE = new BasePermission(1 << 1, 'W'); // 2
public static final Permission CREATE = new BasePermission(1 << 2, 'C'); // 4
public static final Permission DELETE = new BasePermission(1 << 3, 'D'); // 8
public static final Permission ADMINISTRATION = new BasePermission(1 << 4, 'A'); // 16
private static Map locallyDeclaredPermissionsByInteger = new HashMap();
private static Map locallyDeclaredPermissionsByName = new HashMap();
protected static DefaultPermissionFactory defaultPermissionFactory = new DefaultPermissionFactory();
static {
Field[] fields = BasePermission.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
Object fieldValue = fields[i].get(null);
if (BasePermission.class.isAssignableFrom(fieldValue.getClass())) {
// Found a BasePermission static field
BasePermission perm = (BasePermission) fieldValue;
locallyDeclaredPermissionsByInteger.put(new Integer(perm.getMask()), perm);
locallyDeclaredPermissionsByName.put(fields[i].getName(), perm);
}
} catch (Exception ignore) {}
}
}
//~ Instance fields ================================================================================================
private char code;
private int mask;
//~ Constructors ===================================================================================================
private BasePermission(int mask, char code) {
this.mask = mask;
this.code = code;
}
//~ Methods ========================================================================================================
/**
* Registers the public static permissions defined on this class. This is mandatory so
* that the static methods will operate correctly.
* Dynamically creates a <code>CumulativePermission</code> or <code>BasePermission</code> representing the
* active bits in the passed mask.
*
* @param mask to build
*
* @return a Permission representing the requested object
*/
static {
registerPermissionsFor(BasePermission.class);
public static Permission buildFromMask(int mask) {
if (locallyDeclaredPermissionsByInteger.containsKey(new Integer(mask))) {
// The requested mask has an exactly match against a statically-defined BasePermission, so return it
return (Permission) locallyDeclaredPermissionsByInteger.get(new Integer(mask));
}
// To get this far, we have to use a CumulativePermission
CumulativePermission permission = new CumulativePermission();
for (int i = 0; i < 32; i++) {
int permissionToCheck = 1 << i;
if ((mask & permissionToCheck) == permissionToCheck) {
Permission p = (Permission) locallyDeclaredPermissionsByInteger.get(new Integer(permissionToCheck));
Assert.state(p != null,
"Mask " + permissionToCheck + " does not have a corresponding static BasePermission");
permission.set(p);
}
}
return permission;
}
protected BasePermission(int mask, char code) {
super(mask, code);
public static Permission[] buildFromMask(int[] masks) {
if ((masks == null) || (masks.length == 0)) {
return new Permission[0];
}
Permission[] permissions = new Permission[masks.length];
for (int i = 0; i < masks.length; i++) {
permissions[i] = buildFromMask(masks[i]);
}
return permissions;
}
protected final static void registerPermissionsFor(Class<?> subClass) {
defaultPermissionFactory.registerPublicPermissions(subClass);
public static Permission buildFromName(String name) {
Assert.isTrue(locallyDeclaredPermissionsByName.containsKey(name), "Unknown permission '" + name + "'");
return (Permission) locallyDeclaredPermissionsByName.get(name);
}
public final static Permission buildFromMask(int mask) {
return defaultPermissionFactory.buildFromMask(mask);
public static Permission[] buildFromName(String[] names) {
if ((names == null) || (names.length == 0)) {
return new Permission[0];
}
Permission[] permissions = new Permission[names.length];
for (int i = 0; i < names.length; i++) {
permissions[i] = buildFromName(names[i]);
}
return permissions;
}
public final static Permission[] buildFromMask(int[] masks) {
return defaultPermissionFactory.buildFromMask(masks);
public boolean equals(Object arg0) {
if (arg0 == null) {
return false;
}
if (!(arg0 instanceof Permission)) {
return false;
}
Permission rhs = (Permission) arg0;
return (this.mask == rhs.getMask());
}
public final static Permission buildFromName(String name) {
return defaultPermissionFactory.buildFromName(name);
public int getMask() {
return mask;
}
public final static Permission[] buildFromName(String[] names) {
return defaultPermissionFactory.buildFromName(names);
public String getPattern() {
return AclFormattingUtils.printBinary(mask, code);
}
public String toString() {
return "BasePermission[" + getPattern() + "=" + mask + "]";
}
public int hashCode() {
return this.mask;
}
}
@@ -19,21 +19,20 @@ import org.springframework.security.acls.Permission;
/**
* Represents a <code>Permission</code> that is constructed at runtime from other permissions.
*
* <p>Methods return <code>this</code>, in order to facilitate method chaining.</p>
* Represents a <code>Permission</code> that is constructed at runtime from other permissions.<p>Methods return
* <code>this</code>, in order to facilitate method chaining.</p>
*
* @author Ben Alex
* @version $Id$
*/
public class CumulativePermission extends AbstractPermission {
public class CumulativePermission implements Permission {
//~ Instance fields ================================================================================================
private String pattern = THIRTY_TWO_RESERVED_OFF;
private int mask = 0;
//~ Methods ========================================================================================================
public CumulativePermission() {
super(0, ' ');
}
public CumulativePermission clear(Permission permission) {
this.mask &= ~permission.getMask();
this.pattern = AclFormattingUtils.demergePatterns(this.pattern, permission.getPattern());
@@ -47,16 +46,43 @@ public class CumulativePermission extends AbstractPermission {
return this;
}
public boolean equals(Object arg0) {
if (arg0 == null)
{
return false;
}
if (!(arg0 instanceof Permission)) {
return false;
}
Permission rhs = (Permission) arg0;
return (this.mask == rhs.getMask());
}
public int hashCode() {
return this.mask;
}
public int getMask() {
return this.mask;
}
public String getPattern() {
return this.pattern;
}
public CumulativePermission set(Permission permission) {
this.mask |= permission.getMask();
this.pattern = AclFormattingUtils.mergePatterns(this.pattern, permission.getPattern());
return this;
}
public String getPattern() {
return this.pattern;
}
public String toString() {
return "CumulativePermission[" + pattern + "=" + this.mask + "]";
}
}
@@ -1,127 +0,0 @@
package org.springframework.security.acls.domain;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.util.Assert;
/**
* Default implementation of {@link PermissionFactory}.
*
* <p>
* Generally this class will be used by a {@link Permission} instance, as opposed to being dependency
* injected into a {@link LookupStrategy} or similar. Nevertheless, the latter mode of operation is
* fully supported (in which case your {@link Permission} implementations probably should extend
* {@link AbstractPermission} instead of {@link AbstractRegisteredPermission}).
* </p>
*
* @author Ben Alex
* @since 2.0.3
*
*/
public class DefaultPermissionFactory implements PermissionFactory {
private Map registeredPermissionsByInteger = new HashMap();
private Map registeredPermissionsByName = new HashMap();
/**
* Permit registration of a {@link DefaultPermissionFactory} class. The class must provide
* public static fields of type {@link Permission} to represent the possible permissions.
*
* @param clazz a {@link Permission} class with public static fields to register
*/
public void registerPublicPermissions(Class clazz) {
Assert.notNull(clazz, "Class required");
Assert.isAssignable(Permission.class, clazz);
Field[] fields = clazz.getFields();
for (int i = 0; i < fields.length; i++) {
try {
Object fieldValue = fields[i].get(null);
if (Permission.class.isAssignableFrom(fieldValue.getClass())) {
// Found a Permission static field
Permission perm = (Permission) fieldValue;
String permissionName = fields[i].getName();
registerPermission(perm, permissionName);
}
} catch (Exception ignore) {}
}
}
public void registerPermission(Permission perm, String permissionName) {
Assert.notNull(perm, "Permission required");
Assert.hasText(permissionName, "Permission name required");
Integer mask = new Integer(perm.getMask());
// Ensure no existing Permission uses this integer or code
Assert.isTrue(!registeredPermissionsByInteger.containsKey(mask), "An existing Permission already provides mask " + mask);
Assert.isTrue(!registeredPermissionsByName.containsKey(permissionName), "An existing Permission already provides name '" + permissionName + "'");
// Register the new Permission
registeredPermissionsByInteger.put(mask, perm);
registeredPermissionsByName.put(permissionName, perm);
}
public Permission buildFromMask(int mask) {
if (registeredPermissionsByInteger.containsKey(new Integer(mask))) {
// The requested mask has an exactly match against a statically-defined Permission, so return it
return (Permission) registeredPermissionsByInteger.get(new Integer(mask));
}
// To get this far, we have to use a CumulativePermission
CumulativePermission permission = new CumulativePermission();
for (int i = 0; i < 32; i++) {
int permissionToCheck = 1 << i;
if ((mask & permissionToCheck) == permissionToCheck) {
Permission p = (Permission) registeredPermissionsByInteger.get(new Integer(permissionToCheck));
Assert.state(p != null, "Mask " + permissionToCheck + " does not have a corresponding static Permission");
permission.set(p);
}
}
return permission;
}
public Permission[] buildFromMask(int[] masks) {
if ((masks == null) || (masks.length == 0)) {
return new Permission[0];
}
Permission[] permissions = new Permission[masks.length];
for (int i = 0; i < masks.length; i++) {
permissions[i] = buildFromMask(masks[i]);
}
return permissions;
}
public Permission buildFromName(String name) {
Assert.isTrue(registeredPermissionsByName.containsKey(name), "Unknown permission '" + name + "'");
return (Permission) registeredPermissionsByName.get(name);
}
public Permission[] buildFromName(String[] names) {
if ((names == null) || (names.length == 0)) {
return new Permission[0];
}
Permission[] permissions = new Permission[names.length];
for (int i = 0; i < names.length; i++) {
permissions[i] = buildFromName(names[i]);
}
return permissions;
}
}
@@ -1,24 +0,0 @@
package org.springframework.security.acls.domain;
import org.springframework.security.acls.Permission;
/**
* Provides a simple mechanism to retrieve {@link Permission} instances from integer masks.
*
* @author Ben Alex
* @since 2.0.3
*
*/
public interface PermissionFactory {
/**
* Dynamically creates a <code>CumulativePermission</code> or <code>BasePermission</code> representing the
* active bits in the passed mask.
*
* @param mask to build
*
* @return a Permission representing the requested object
*/
public abstract Permission buildFromMask(int mask);
}
@@ -18,7 +18,6 @@ import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -98,30 +97,30 @@ public final class BasicLookupStrategy implements LookupStrategy {
private static String computeRepeatingSql(String repeatingSql, int requiredRepetitions) {
Assert.isTrue(requiredRepetitions >= 1, "Must be => 1");
String startSql = "select acl_object_identity.object_id_identity, "
+ "acl_entry.ace_order, "
+ "acl_object_identity.id as acl_id, "
+ "acl_object_identity.parent_object, "
+ "acl_object_identity.entries_inheriting, "
+ "acl_entry.id as ace_id, "
+ "acl_entry.mask, "
+ "acl_entry.granting, "
+ "acl_entry.audit_success, "
+ "acl_entry.audit_failure, "
+ "acl_sid.principal as ace_principal, "
+ "acl_sid.sid as ace_sid, "
+ "acli_sid.principal as acl_principal, "
+ "acli_sid.sid as acl_sid, "
+ "acl_class.class "
+ "from acl_object_identity "
+ "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid "
+ "left join acl_class on acl_class.id = acl_object_identity.object_id_class "
+ "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity "
+ "left join acl_sid on acl_entry.sid = acl_sid.id "
+ "where ( ";
String startSql = "select acl_object_identity.object_id_identity, "
+ "acl_entry.ace_order, "
+ "acl_object_identity.id as acl_id, "
+ "acl_object_identity.parent_object, "
+ "acl_object_identity.entries_inheriting, "
+ "acl_entry.id as ace_id, "
+ "acl_entry.mask, "
+ "acl_entry.granting, "
+ "acl_entry.audit_success, "
+ "acl_entry.audit_failure, "
+ "acl_sid.principal as ace_principal, "
+ "acl_sid.sid as ace_sid, "
+ "acli_sid.principal as acl_principal, "
+ "acli_sid.sid as acl_sid, "
+ "acl_class.class "
+ "from acl_object_identity "
+ "left join acl_sid acli_sid on acli_sid.id = acl_object_identity.owner_sid "
+ "left join acl_class on acl_class.id = acl_object_identity.object_id_class "
+ "left join acl_entry on acl_object_identity.id = acl_entry.acl_object_identity "
+ "left join acl_sid on acl_entry.sid = acl_sid.id "
+ "where ( ";
String endSql = ") order by acl_object_identity.object_id_identity"
+ " asc, acl_entry.ace_order asc";
String endSql = ") order by acl_object_identity.object_id_identity"
+ " asc, acl_entry.ace_order asc";
StringBuffer sqlStringBuffer = new StringBuffer();
sqlStringBuffer.append(startSql);
@@ -146,8 +145,11 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @param inputMap the unconverted <code>AclImpl</code>s
* @param currentIdentity the current<code>Acl</code> that we wish to convert (this may be
*
* @return
*
* @throws IllegalStateException DOCUMENT ME!
*/
private AclImpl convert(Map<Long,AclImpl> inputMap, Long currentIdentity) {
private AclImpl convert(Map inputMap, Long currentIdentity) {
Assert.notEmpty(inputMap, "InputMap required");
Assert.notNull(currentIdentity, "CurrentIdentity required");
@@ -170,33 +172,15 @@ public final class BasicLookupStrategy implements LookupStrategy {
auditLogger, parent, null, inputAcl.isEntriesInheriting(), inputAcl.getOwner());
// Copy the "aces" from the input to the destination
Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
Field fieldAcl = FieldUtils.getField(AccessControlEntryImpl.class, "acl");
Field field = FieldUtils.getField(AclImpl.class, "aces");
try {
fieldAces.setAccessible(true);
fieldAcl.setAccessible(true);
// Obtain the "aces" from the input ACL
List<AccessControlEntryImpl> aces = (List<AccessControlEntryImpl>) fieldAces.get(inputAcl);
// Create a list in which to store the "aces" for the "result" AclImpl instance
List<AccessControlEntryImpl> acesNew = new ArrayList<AccessControlEntryImpl>();
// Iterate over the "aces" input and replace each nested AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance
// This ensures StubAclParent instances are removed, as per SEC-951
for (AccessControlEntryImpl ace : aces) {
fieldAcl.set(ace, result);
acesNew.add(ace);
}
// Finally, now that the "aces" have been converted to have the "result" AclImpl instance, modify the "result" AclImpl instance
fieldAces.set(result, acesNew);
field.setAccessible(true);
field.set(result, field.get(inputAcl));
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Could not obtain or set AclImpl or AccessControlEntryImpl fields");
throw new IllegalStateException("Could not obtain or set AclImpl.ace field");
}
return result;
}
@@ -208,8 +192,10 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @param rs the ResultSet focused on a current row
*
* @throws SQLException if something goes wrong converting values
* @throws IllegalStateException DOCUMENT ME!
*/
private void convertCurrentResultIntoObject(Map<Long,AclImpl> acls, ResultSet rs) throws SQLException {
private void convertCurrentResultIntoObject(Map acls, ResultSet rs)
throws SQLException {
Long id = new Long(rs.getLong("acl_id"));
// If we already have an ACL for this ID, just create the ACE
@@ -253,8 +239,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
recipient = new GrantedAuthoritySid(rs.getString("ace_sid"));
}
int mask = rs.getInt("mask");
Permission permission = convertMaskIntoPermission(mask);
Permission permission = BasePermission.buildFromMask(rs.getInt("mask"));
boolean granting = rs.getBoolean("granting");
boolean auditSuccess = rs.getBoolean("audit_success");
boolean auditFailure = rs.getBoolean("audit_failure");
@@ -263,11 +248,11 @@ public final class BasicLookupStrategy implements LookupStrategy {
auditSuccess, auditFailure);
Field acesField = FieldUtils.getField(AclImpl.class, "aces");
List<AccessControlEntryImpl> aces;
List aces;
try {
acesField.setAccessible(true);
aces = (List<AccessControlEntryImpl>) acesField.get(acl);
aces = (List) acesField.get(acl);
} catch (IllegalAccessException ex) {
throw new IllegalStateException("Could not obtain AclImpl.ace field: cause[" + ex.getMessage() + "]");
}
@@ -279,8 +264,66 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
protected Permission convertMaskIntoPermission(int mask) {
return BasePermission.buildFromMask(mask);
/**
* Looks up a batch of <code>ObjectIdentity</code>s directly from the database.<p>The caller is responsible
* for optimization issues, such as selecting the identities to lookup, ensuring the cache doesn't contain them
* already, and adding the returned elements to the cache etc.</p>
* <p>This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
* parent ACLs.</p>
*
* @param objectIdentities DOCUMENT ME!
* @param sids DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private Map lookupObjectIdentities(final ObjectIdentity[] objectIdentities, Sid[] sids) {
Assert.notEmpty(objectIdentities, "Must provide identities to lookup");
final Map acls = new HashMap(); // contains Acls with StubAclParents
// Make the "acls" map contain all requested objectIdentities
// (including markers to each parent in the hierarchy)
String sql = computeRepeatingSql("(acl_object_identity.object_id_identity = ? and acl_class.class = ?)",
objectIdentities.length);
Set parentsToLookup = (Set) jdbcTemplate.query(sql,
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps)
throws SQLException {
for (int i = 0; i < objectIdentities.length; i++) {
// Determine prepared statement values for this iteration
String javaType = objectIdentities[i].getJavaType().getName();
Assert.isInstanceOf(Long.class, objectIdentities[i].getIdentifier(),
"This class requires ObjectIdentity.getIdentifier() to be a Long");
long id = ((Long) objectIdentities[i].getIdentifier()).longValue();
// Inject values
ps.setLong((2 * i) + 1, id);
ps.setString((2 * i) + 2, javaType);
}
}
}, new ProcessResultSet(acls, sids));
// Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547)
if (parentsToLookup.size() > 0) {
lookupPrimaryKeys(acls, parentsToLookup, sids);
}
// Finally, convert our "acls" containing StubAclParents into true Acls
Map resultMap = new HashMap();
Iterator iter = acls.values().iterator();
while (iter.hasNext()) {
Acl inputAcl = (Acl) iter.next();
Assert.isInstanceOf(AclImpl.class, inputAcl, "Map should have contained an AclImpl");
Assert.isInstanceOf(Long.class, ((AclImpl) inputAcl).getId(), "Acl.getId() must be Long");
Acl result = convert(acls, (Long) ((AclImpl) inputAcl).getId());
resultMap.put(result.getObjectIdentity(), result);
}
return resultMap;
}
/**
@@ -289,9 +332,9 @@ public final class BasicLookupStrategy implements LookupStrategy {
*
* @param acls the AclImpls (with StubAclParents)
* @param findNow Long-based primary keys to retrieve
* @param sids
* @param sids DOCUMENT ME!
*/
private void lookupPrimaryKeys(final Map acls, final Set findNow, final List<Sid> sids) {
private void lookupPrimaryKeys(final Map acls, final Set findNow, final Sid[] sids) {
Assert.notNull(acls, "ACLs are required");
Assert.notEmpty(findNow, "Items to find now required");
@@ -310,22 +353,19 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
}, new ProcessResultSet(acls, sids));
// Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547)
if (parentsToLookup.size() > 0) {
lookupPrimaryKeys(acls, parentsToLookup, sids);
lookupPrimaryKeys(acls, parentsToLookup, sids);
}
}
/**
* The main method.
* <p>
* WARNING: This implementation completely disregards the "sids" argument! Every item in the cache is expected to
* contain all SIDs. If you have serious performance needs (e.g. a very large number of
* The main method.<p>WARNING: This implementation completely disregards the "sids" argument! Every item
* in the cache is expected to contain all SIDs. If you have serious performance needs (eg a very large number of
* SIDs per object identity), you'll probably want to develop a custom {@link LookupStrategy} implementation
* instead.
* <p>
* The implementation works in batch sizes specified by {@link #batchSize}.
* instead.</p>
* <p>The implementation works in batch sizes specfied by {@link #batchSize}.</p>
*
* @param objects the identities to lookup (required)
* @param sids the SIDs for which identities are required (ignored by this implementation)
@@ -333,29 +373,29 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values
* are the located {@link Acl} (never <tt>null</tt> although some entries may be missing; this method
* should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used
* to automatically create entries if required)
* to automatically create entries if required)
*/
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) {
public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) {
Assert.isTrue(batchSize >= 1, "BatchSize must be >= 1");
Assert.notEmpty(objects, "Objects to lookup required");
// Map<ObjectIdentity,Acl>
Map<ObjectIdentity, Acl> result = new HashMap<ObjectIdentity, Acl>(); // contains FULLY loaded Acl objects
Map result = new HashMap(); // contains FULLY loaded Acl objects
Set<ObjectIdentity> currentBatchToLoad = new HashSet<ObjectIdentity>(); // contains ObjectIdentitys
Set currentBatchToLoad = new HashSet(); // contains ObjectIdentitys
for (int i = 0; i < objects.size(); i++) {
boolean aclFound = false;
for (int i = 0; i < objects.length; i++) {
boolean aclFound = false;
// Check we don't already have this ACL in the results
if (result.containsKey(objects.get(i))) {
// Check we don't already have this ACL in the results
if (result.containsKey(objects[i])) {
aclFound = true;
}
// Check cache for the present ACL entry
if (!aclFound) {
Acl acl = aclCache.getFromCache(objects.get(i));
Acl acl = aclCache.getFromCache(objects[i]);
// Ensure any cached element supports all the requested SIDs
// (they should always, as our base impl doesn't filter on SID)
if (acl != null) {
@@ -369,97 +409,35 @@ public final class BasicLookupStrategy implements LookupStrategy {
}
}
}
// Load the ACL from the database
if (!aclFound) {
currentBatchToLoad.add(objects.get(i));
currentBatchToLoad.add(objects[i]);
}
// Is it time to load from JDBC the currentBatchToLoad?
if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.size())) {
if (currentBatchToLoad.size() > 0) {
Map<ObjectIdentity, Acl> loadedBatch = lookupObjectIdentities(currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids);
if ((currentBatchToLoad.size() == this.batchSize) || ((i + 1) == objects.length)) {
if (currentBatchToLoad.size() > 0) {
Map loadedBatch = lookupObjectIdentities((ObjectIdentity[]) currentBatchToLoad.toArray(new ObjectIdentity[] {}), sids);
// Add loaded batch (all elements 100% initialized) to results
result.putAll(loadedBatch);
// Add the loaded batch to the cache
Iterator<Acl> loadedAclIterator = loadedBatch.values().iterator();
while (loadedAclIterator.hasNext()) {
aclCache.putInCache((AclImpl) loadedAclIterator.next());
}
currentBatchToLoad.clear();
}
// Add loaded batch (all elements 100% initialized) to results
result.putAll(loadedBatch);
// Add the loaded batch to the cache
Iterator loadedAclIterator = loadedBatch.values().iterator();
while (loadedAclIterator.hasNext()) {
aclCache.putInCache((AclImpl) loadedAclIterator.next());
}
currentBatchToLoad.clear();
}
}
}
return result;
}
/**
* Looks up a batch of <code>ObjectIdentity</code>s directly from the database.
* <p>
* The caller is responsible for optimization issues, such as selecting the identities to lookup, ensuring the
* cache doesn't contain them already, and adding the returned elements to the cache etc.
* <p>
* This subclass is required to return fully valid <code>Acl</code>s, including properly-configured
* parent ACLs.
*
*/
@SuppressWarnings("unchecked")
private Map<ObjectIdentity, Acl> lookupObjectIdentities(final ObjectIdentity[] objectIdentities, List<Sid> sids) {
Assert.notEmpty(objectIdentities, "Must provide identities to lookup");
final Map acls = new HashMap(); // contains Acls with StubAclParents
// Make the "acls" map contain all requested objectIdentities
// (including markers to each parent in the hierarchy)
String sql = computeRepeatingSql("(acl_object_identity.object_id_identity = ? and acl_class.class = ?)",
objectIdentities.length);
Set parentsToLookup = (Set) jdbcTemplate.query(sql,
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps)
throws SQLException {
for (int i = 0; i < objectIdentities.length; i++) {
// Determine prepared statement values for this iteration
String javaType = objectIdentities[i].getJavaType().getName();
// No need to check for nulls, as guaranteed non-null by ObjectIdentity.getIdentifier() interface contract
String identifier = objectIdentities[i].getIdentifier().toString();
long id = (Long.valueOf(identifier)).longValue();
// Inject values
ps.setLong((2 * i) + 1, id);
ps.setString((2 * i) + 2, javaType);
}
}
}, new ProcessResultSet(acls, sids));
// Lookup the parents, now that our JdbcTemplate has released the database connection (SEC-547)
if (parentsToLookup.size() > 0) {
lookupPrimaryKeys(acls, parentsToLookup, sids);
}
// Finally, convert our "acls" containing StubAclParents into true Acls
Map<ObjectIdentity, Acl> resultMap = new HashMap<ObjectIdentity, Acl>();
Iterator iter = acls.values().iterator();
while (iter.hasNext()) {
Acl inputAcl = (Acl) iter.next();
Assert.isInstanceOf(AclImpl.class, inputAcl, "Map should have contained an AclImpl");
Assert.isInstanceOf(Long.class, ((AclImpl) inputAcl).getId(), "Acl.getId() must be Long");
Acl result = convert(acls, (Long) ((AclImpl) inputAcl).getId());
resultMap.put(result.getObjectIdentity(), result);
}
return resultMap;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
@@ -468,9 +446,9 @@ public final class BasicLookupStrategy implements LookupStrategy {
private class ProcessResultSet implements ResultSetExtractor {
private Map acls;
private List<Sid> sids;
private Sid[] sids;
public ProcessResultSet(Map acls, List<Sid> sids) {
public ProcessResultSet(Map acls, Sid[] sids) {
Assert.notNull(acls, "ACLs cannot be null");
this.acls = acls;
this.sids = sids; // can be null
@@ -488,7 +466,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
* @throws DataAccessException
*/
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
Set<Long> parentIdsToLookup = new HashSet<Long>(); // Set of parent_id Longs
Set parentIdsToLookup = new HashSet(); // Set of parent_id Longs
while (rs.next()) {
// Convert current row into an Acl (albeit with a StubAclParent)
@@ -528,7 +506,7 @@ public final class BasicLookupStrategy implements LookupStrategy {
this.id = id;
}
public List<AccessControlEntry> getEntries() {
public AccessControlEntry[] getEntries() {
throw new UnsupportedOperationException("Stub only");
}
@@ -552,12 +530,12 @@ public final class BasicLookupStrategy implements LookupStrategy {
throw new UnsupportedOperationException("Stub only");
}
public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode)
public boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
throw new UnsupportedOperationException("Stub only");
}
public boolean isSidLoaded(List<Sid> sids) {
public boolean isSidLoaded(Sid[] sids) {
throw new UnsupportedOperationException("Stub only");
}
}
@@ -94,7 +94,7 @@ public class EhCacheBasedAclCache implements AclCache {
return initializeTransientFields((MutableAcl)element.getValue());
}
public MutableAcl getFromCache(Serializable pk) {
public MutableAcl getFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
Element element = null;
@@ -117,8 +117,8 @@ public class EhCacheBasedAclCache implements AclCache {
if (this.aclAuthorizationStrategy == null) {
if (acl instanceof AclImpl) {
this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl);
this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl);
this.aclAuthorizationStrategy = (AclAuthorizationStrategy) FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", acl);
this.auditLogger = (AuditLogger) FieldUtils.getProtectedFieldValue("auditLogger", acl);
}
}
@@ -131,10 +131,10 @@ public class EhCacheBasedAclCache implements AclCache {
}
private MutableAcl initializeTransientFields(MutableAcl value) {
if (value instanceof AclImpl) {
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger);
}
return value;
}
if (value instanceof AclImpl) {
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("auditLogger", value, this.auditLogger);
}
return value;
}
}
@@ -14,31 +14,35 @@
*/
package org.springframework.security.acls.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.NotFoundException;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
import org.springframework.security.acls.sid.Sid;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
/**
* Simple JDBC-based implementation of <code>AclService</code>.
* <p>
* Requires the "dirty" flags in {@link org.springframework.security.acls.domain.AclImpl} and
* Requires the "dirty" flags in {@link org.springframework.security.acls.domain.AclImpl} and
* {@link org.springframework.security.acls.domain.AccessControlEntryImpl} to be set, so that the implementation can
* detect changed parameters easily.
*
@@ -49,7 +53,7 @@ public class JdbcAclService implements AclService {
//~ Static fields/initializers =====================================================================================
protected static final Log log = LogFactory.getLog(JdbcAclService.class);
private static final String selectAclObjectWithParent = "select obj.object_id_identity as obj_id, class.class as class "
private static final String selectAclObjectWithParent = "select obj.object_id_identity obj_id, class.class class "
+ "from acl_object_identity obj, acl_object_identity parent, acl_class class "
+ "where obj.parent_object = parent.id and obj.object_id_class = class.id "
+ "and parent.object_id_identity = ? and parent.object_id_class = ("
@@ -71,7 +75,7 @@ public class JdbcAclService implements AclService {
//~ Methods ========================================================================================================
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
public ObjectIdentity[] findChildren(ObjectIdentity parentIdentity) {
Object[] args = {parentIdentity.getIdentifier(), parentIdentity.getJavaType().getName()};
List objects = jdbcTemplate.query(selectAclObjectWithParent, args,
new RowMapper() {
@@ -85,14 +89,14 @@ public class JdbcAclService implements AclService {
});
if (objects.size() == 0) {
return null;
return null;
}
return objects;
return (ObjectIdentityImpl[]) objects.toArray(new ObjectIdentityImpl[objects.size()]);
}
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids);
public Acl readAclById(ObjectIdentity object, Sid[] sids) throws NotFoundException {
Map map = readAclsById(new ObjectIdentity[] {object}, sids);
Assert.isTrue(map.containsKey(object), "There should have been an Acl entry for ObjectIdentity " + object);
return (Acl) map.get(object);
@@ -102,21 +106,21 @@ public class JdbcAclService implements AclService {
return readAclById(object, null);
}
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException {
public Map readAclsById(ObjectIdentity[] objects) throws NotFoundException {
return readAclsById(objects, null);
}
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException {
Map<ObjectIdentity, Acl> result = lookupStrategy.readAclsById(objects, sids);
public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) throws NotFoundException {
Map result = lookupStrategy.readAclsById(objects, sids);
// Check every requested object identity was found (throw NotFoundException if needed)
for (int i = 0; i < objects.size(); i++) {
if (!result.containsKey(objects.get(i))) {
for (int i = 0; i < objects.length; i++) {
if (!result.containsKey(objects[i])) {
throw new NotFoundException("Unable to find ACL information for object identity '"
+ objects.get(i).toString() + "'");
+ objects[i].toString() + "'");
}
}
return result;
}
}
@@ -14,15 +14,8 @@
*/
package org.springframework.security.acls.jdbc;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.security.Authentication;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AlreadyExistsException;
@@ -36,10 +29,26 @@ import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
import org.springframework.security.acls.sid.GrantedAuthoritySid;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import java.lang.reflect.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
/**
* Provides a base implementation of {@link MutableAclService}.
@@ -51,12 +60,11 @@ import org.springframework.util.Assert;
public class JdbcMutableAclService extends JdbcAclService implements MutableAclService {
//~ Instance fields ================================================================================================
private boolean foreignKeysInDatabase = true;
private boolean foreignKeysInDatabase = true;
private AclCache aclCache;
private String deleteEntryByObjectIdentityForeignKey = "delete from acl_entry where acl_object_identity=?";
private String deleteObjectIdentityByPrimaryKey = "delete from acl_object_identity where id=?";
private String classIdentityQuery = "call identity()"; // should be overridden for postgres : select currval('acl_class_seq')
private String sidIdentityQuery = "call identity()"; // should be overridden for postgres : select currval('acl_siq_seq')
private String identityQuery = "call identity()";
private String insertClass = "insert into acl_class (class) values (?)";
private String insertEntry = "insert into acl_entry "
+ "(acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure)"
@@ -82,7 +90,8 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
//~ Methods ========================================================================================================
public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
public MutableAcl createAcl(ObjectIdentity objectIdentity)
throws AlreadyExistsException {
Assert.notNull(objectIdentity, "Object Identity required");
// Check this object identity hasn't already been persisted
@@ -113,13 +122,14 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
jdbcTemplate.batchUpdate(insertEntry,
new BatchPreparedStatementSetter() {
public int getBatchSize() {
return acl.getEntries().size();
return acl.getEntries().length;
}
public void setValues(PreparedStatement stmt, int i)
throws SQLException {
AccessControlEntry entry_ = acl.getEntries().get(i);
AccessControlEntry entry_ = (AccessControlEntry) Array.get(acl.getEntries(), i);
Assert.isTrue(entry_ instanceof AccessControlEntryImpl, "Unknown ACE class");
AccessControlEntryImpl entry = (AccessControlEntryImpl) entry_;
stmt.setLong(1, ((Long) acl.getId()).longValue());
@@ -156,21 +166,23 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*
* @return the primary key or null if not found
*/
protected Long createOrRetrieveClassPrimaryKey(Class<?> clazz, boolean allowCreate) {
List<Long> classIds = jdbcTemplate.queryForList(selectClassPrimaryKey, new Object[] {clazz.getName()}, Long.class);
protected Long createOrRetrieveClassPrimaryKey(Class clazz, boolean allowCreate) {
List classIds = jdbcTemplate.queryForList(selectClassPrimaryKey, new Object[] {clazz.getName()}, Long.class);
Long classId = null;
if (!classIds.isEmpty()) {
return classIds.get(0);
if (classIds.isEmpty()) {
if (allowCreate) {
classId = null;
jdbcTemplate.update(insertClass, new Object[] {clazz.getName()});
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
"Transaction must be running");
classId = new Long(jdbcTemplate.queryForLong(identityQuery));
}
} else {
classId = (Long) classIds.iterator().next();
}
if (allowCreate) {
jdbcTemplate.update(insertClass, new Object[] {clazz.getName()});
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
"Transaction must be running");
return new Long(jdbcTemplate.queryForLong(classIdentityQuery));
}
return null;
return classId;
}
/**
@@ -182,7 +194,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*
* @return the primary key or null if not found
*
* @throws IllegalArgumentException if the <tt>Sid</tt> is not a recognized implementation.
* @throws IllegalArgumentException DOCUMENT ME!
*/
protected Long createOrRetrieveSidPrimaryKey(Sid sid, boolean allowCreate) {
Assert.notNull(sid, "Sid required");
@@ -199,48 +211,51 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
throw new IllegalArgumentException("Unsupported implementation of Sid");
}
List<Long> sidIds = jdbcTemplate.queryForList(selectSidPrimaryKey,
new Object[] {new Boolean(principal), sidName}, Long.class);
List sidIds = jdbcTemplate.queryForList(selectSidPrimaryKey, new Object[] {new Boolean(principal), sidName},
Long.class);
Long sidId = null;
if (!sidIds.isEmpty()) {
return sidIds.get(0);
if (sidIds.isEmpty()) {
if (allowCreate) {
sidId = null;
jdbcTemplate.update(insertSid, new Object[] {new Boolean(principal), sidName});
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
"Transaction must be running");
sidId = new Long(jdbcTemplate.queryForLong(identityQuery));
}
} else {
sidId = (Long) sidIds.iterator().next();
}
if (allowCreate) {
jdbcTemplate.update(insertSid, new Object[] {new Boolean(principal), sidName});
Assert.isTrue(TransactionSynchronizationManager.isSynchronizationActive(),
"Transaction must be running");
return new Long(jdbcTemplate.queryForLong(sidIdentityQuery));
}
return null;
return sidId;
}
public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException {
public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren)
throws ChildrenExistException {
Assert.notNull(objectIdentity, "Object Identity required");
Assert.notNull(objectIdentity.getIdentifier(), "Object Identity doesn't provide an identifier");
if (deleteChildren) {
List<ObjectIdentity> children = findChildren(objectIdentity);
if (children != null) {
for (int i = 0; i < children.size(); i++) {
deleteAcl(children.get(i), true);
ObjectIdentity[] children = findChildren(objectIdentity);
if (children != null) {
for (int i = 0; i < children.length; i++) {
deleteAcl(children[i], true);
}
}
}
} else {
if (!foreignKeysInDatabase) {
// We need to perform a manual verification for what a FK would normally do
// We generally don't do this, in the interests of deadlock management
List<ObjectIdentity> children = findChildren(objectIdentity);
if (children != null) {
throw new ChildrenExistException("Cannot delete '" + objectIdentity + "' (has " + children.size()
if (!foreignKeysInDatabase) {
// We need to perform a manual verification for what a FK would normally do
// We generally don't do this, in the interests of deadlock management
ObjectIdentity[] children = findChildren(objectIdentity);
if (children != null) {
throw new ChildrenExistException("Cannot delete '" + objectIdentity + "' (has " + children.length
+ " children)");
}
}
}
}
}
Long oidPrimaryKey = retrieveObjectIdentityPrimaryKey(objectIdentity);
// Delete this ACL's ACEs in the acl_entry table
deleteEntries(oidPrimaryKey);
@@ -257,15 +272,17 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
* @param oidPrimaryKey the rows in acl_entry to delete
*/
protected void deleteEntries(Long oidPrimaryKey) {
jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey,
jdbcTemplate.update(deleteEntryByObjectIdentityForeignKey,
new Object[] {oidPrimaryKey});
}
/**
* Deletes a single row from acl_object_identity that is associated with the presented ObjectIdentity primary key.
*
* <p>
* We do not delete any entries from acl_class, even if no classes are using that class any longer. This is a
* deadlock avoidance approach.
* </p>
*
* @param oidPrimaryKey to delete the acl_object_identity
*/
@@ -296,6 +313,12 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
* This implementation will simply delete all ACEs in the database and recreate them on each invocation of
* this method. A more comprehensive implementation might use dirty state checking, or more likely use ORM
* capabilities for create, update and delete operations of {@link MutableAcl}.
*
* @param acl DOCUMENT ME!
*
* @return DOCUMENT ME!
*
* @throws NotFoundException DOCUMENT ME!
*/
public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException {
Assert.notNull(acl.getId(), "Object Identity doesn't provide an identifier");
@@ -315,14 +338,14 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
// Retrieve the ACL via superclass (ensures cache registration, proper retrieval etc)
return (MutableAcl) super.readAclById(acl.getObjectIdentity());
}
private void clearCacheIncludingChildren(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
List<ObjectIdentity> children = findChildren(objectIdentity);
Assert.notNull(objectIdentity, "ObjectIdentity required");
ObjectIdentity[] children = findChildren(objectIdentity);
if (children != null) {
for (int i = 0; i < children.size(); i++) {
clearCacheIncludingChildren(children.get(i));
}
for (int i = 0; i < children.length; i++) {
clearCacheIncludingChildren(children[i]);
}
}
aclCache.evictFromCache(objectIdentity);
}
@@ -333,7 +356,7 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
*
* @param acl to modify (a row must already exist in acl_object_identity)
*
* @throws NotFoundException if the ACL could not be found to update.
* @throws NotFoundException DOCUMENT ME!
*/
protected void updateObjectIdentity(MutableAcl acl) {
Long parentId = null;
@@ -357,20 +380,16 @@ public class JdbcMutableAclService extends JdbcAclService implements MutableAclS
}
}
public void setClassIdentityQuery(String identityQuery) {
Assert.hasText(identityQuery, "New identity query is required");
this.classIdentityQuery = identityQuery;
}
public void setIdentityQuery(String identityQuery) {
Assert.hasText(identityQuery, "New identity query is required");
this.identityQuery = identityQuery;
}
public void setSidIdentityQuery(String identityQuery) {
Assert.hasText(identityQuery, "New identity query is required");
this.sidIdentityQuery = identityQuery;
}
/**
* @param foreignKeysInDatabase if false this class will perform additional FK constrain checking, which may
* cause deadlocks (the default is true, so deadlocks are avoided but the database is expected to enforce FKs)
*/
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
this.foreignKeysInDatabase = foreignKeysInDatabase;
}
/**
* @param foreignKeysInDatabase if false this class will perform additional FK constrain checking, which may
* cause deadlocks (the default is true, so deadlocks are avoided but the database is expected to enforce FKs)
*/
public void setForeignKeysInDatabase(boolean foreignKeysInDatabase) {
this.foreignKeysInDatabase = foreignKeysInDatabase;
}
}
@@ -14,18 +14,16 @@
*/
package org.springframework.security.acls.jdbc;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.NotFoundException;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.Sid;
import java.util.List;
import java.util.Map;
/**
* Performs lookups for {@link org.springframework.security.acls.AclService}.
*
*
* @author Ben Alex
* @version $Id$
*/
@@ -42,7 +40,7 @@ public interface LookupStrategy {
* @return a <tt>Map</tt> where keys represent the {@link ObjectIdentity} of the located {@link Acl} and values
* are the located {@link Acl} (never <tt>null</tt> although some entries may be missing; this method
* should not throw {@link NotFoundException}, as a chain of {@link LookupStrategy}s may be used
* to automatically create entries if required)
* to automatically create entries if required)
*/
Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids);
Map readAclsById(ObjectIdentity[] objects, Sid[] sids);
}
@@ -62,7 +62,7 @@ public interface ObjectIdentity extends Serializable {
*
* @return the Java type of the domain object (never <tt>null</tt>)
*/
Class<?> getJavaType();
Class getJavaType();
/**
* @return a hash code representation of the <tt>ObjectIdentity</tt>
@@ -1,23 +0,0 @@
package org.springframework.security.acls.objectidentity;
import java.io.Serializable;
/**
* Strategy which creates an <tt>ObjectIdentity</tt> from object identity and type information.
* Used in situations when the actual object instance isn't available.
*
* @author Luke Taylor
* @version $Id$
* @since 2.5
*/
public interface ObjectIdentityGenerator {
/**
*
* @param id the identifier of the domain object, not null
* @param type the type of the object (usually a class name), not null
* @return
*/
ObjectIdentity createObjectIdentity(Serializable id, String type);
}
@@ -15,7 +15,6 @@
package org.springframework.security.acls.objectidentity;
import org.springframework.security.acls.IdentityUnavailableException;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
@@ -38,7 +37,7 @@ import java.lang.reflect.Method;
public class ObjectIdentityImpl implements ObjectIdentity {
//~ Instance fields ================================================================================================
private Class<?> javaType;
private Class javaType;
private Serializable identifier;
//~ Constructors ===================================================================================================
@@ -56,14 +55,14 @@ public class ObjectIdentityImpl implements ObjectIdentity {
this.identifier = identifier;
}
public ObjectIdentityImpl(Class<?> javaType, Serializable identifier) {
public ObjectIdentityImpl(Class javaType, Serializable identifier) {
Assert.notNull(javaType, "Java Type required");
Assert.notNull(identifier, "identifier required");
this.javaType = javaType;
this.identifier = identifier;
}
/**
/**
* Creates the <code>ObjectIdentityImpl</code> based on the passed
* object instance. The passed object must provide a <code>getId()</code>
* method, otherwise an exception will be thrown. The object passed will
@@ -99,12 +98,6 @@ public class ObjectIdentityImpl implements ObjectIdentity {
* Important so caching operates properly.<P>Considers an object of the same class equal if it has the same
* <code>classname</code> and <code>id</code> properties.</p>
*
* <p>
* Note that this class uses string equality for the identifier field, which ensures it better supports
* differences between {@link LookupStrategy} requirements and the domain object represented by this
* <code>ObjectIdentityImpl</code>.
* </p>
*
* @param arg0 object to compare
*
* @return <code>true</code> if the presented object matches this object
@@ -120,7 +113,7 @@ public class ObjectIdentityImpl implements ObjectIdentity {
ObjectIdentityImpl other = (ObjectIdentityImpl) arg0;
if (this.getIdentifier().toString().equals(other.getIdentifier().toString()) && this.getJavaType().equals(other.getJavaType())) {
if (this.getIdentifier().equals(other.getIdentifier()) && this.getJavaType().equals(other.getJavaType())) {
return true;
}
@@ -131,7 +124,7 @@ public class ObjectIdentityImpl implements ObjectIdentity {
return identifier;
}
public Class<?> getJavaType() {
public Class getJavaType() {
return javaType;
}
@@ -15,23 +15,17 @@
package org.springframework.security.acls.objectidentity;
import java.io.Serializable;
/**
* Basic implementation of {@link ObjectIdentityRetrievalStrategy} and <tt>ObjectIdentityGenerator</tt>
* that uses the constructors of {@link ObjectIdentityImpl} to create the {@link ObjectIdentity}.
* Basic implementation of {@link ObjectIdentityRetrievalStrategy} that uses the constructor of {@link
* ObjectIdentityImpl} to create the {@link ObjectIdentity}.
*
* @author Ben Alex
* @version $Id$
*/
public class ObjectIdentityRetrievalStrategyImpl implements ObjectIdentityRetrievalStrategy, ObjectIdentityGenerator {
public class ObjectIdentityRetrievalStrategyImpl implements ObjectIdentityRetrievalStrategy {
//~ Methods ========================================================================================================
public ObjectIdentity getObjectIdentity(Object domainObject) {
return new ObjectIdentityImpl(domainObject);
}
public ObjectIdentity createObjectIdentity(Serializable id, String type) {
return new ObjectIdentityImpl(type, id);
}
}
@@ -15,8 +15,6 @@
package org.springframework.security.acls.sid;
import java.util.List;
import org.springframework.security.Authentication;
@@ -30,5 +28,5 @@ import org.springframework.security.Authentication;
public interface SidRetrievalStrategy {
//~ Methods ========================================================================================================
List<Sid> getSids(Authentication authentication);
Sid[] getSids(Authentication authentication);
}
@@ -15,9 +15,6 @@
package org.springframework.security.acls.sid;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
@@ -33,14 +30,14 @@ import org.springframework.security.GrantedAuthority;
public class SidRetrievalStrategyImpl implements SidRetrievalStrategy {
//~ Methods ========================================================================================================
public List<Sid> getSids(Authentication authentication) {
List<GrantedAuthority> authorities = authentication.getAuthorities();
List<Sid> sids = new ArrayList<Sid>(authorities.size() + 1);
public Sid[] getSids(Authentication authentication) {
GrantedAuthority[] authorities = authentication.getAuthorities();
Sid[] sids = new Sid[authorities.length + 1];
sids.add(new PrincipalSid(authentication));
sids[0] = new PrincipalSid(authentication);
for (GrantedAuthority authority : authorities) {
sids.add(new GrantedAuthoritySid(authority));
for (int i = 1; i <= authorities.length; i++) {
sids[i] = new GrantedAuthoritySid(authorities[i - 1]);
}
return sids;
@@ -13,10 +13,7 @@
* limitations under the License.
*/
package org.springframework.security.acls.afterinvocation;
import java.util.Arrays;
import java.util.List;
package org.springframework.security.afterinvocation;
import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttribute;
@@ -32,34 +29,33 @@ import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalS
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategyImpl;
import org.springframework.security.afterinvocation.AfterInvocationProvider;
import org.springframework.util.Assert;
/**
* Abstract {@link AfterInvocationProvider} which provides commonly-used ACL-related services.
* DOCUMENT ME!
*
* @author Ben Alex
* @version $Id$
* @author $author$
* @version $Revision$
*/
public abstract class AbstractAclProvider implements AfterInvocationProvider {
//~ Instance fields ================================================================================================
protected AclService aclService;
protected Class<?> processDomainObjectClass = Object.class;
protected ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
protected SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
protected String processConfigAttribute;
protected List<Permission> requirePermission = Arrays.asList(BasePermission.READ);
private AclService aclService;
private Class processDomainObjectClass = Object.class;
private ObjectIdentityRetrievalStrategy objectIdentityRetrievalStrategy = new ObjectIdentityRetrievalStrategyImpl();
private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
private String processConfigAttribute;
private Permission[] requirePermission = {BasePermission.READ};
//~ Constructors ===================================================================================================
public AbstractAclProvider(AclService aclService, String processConfigAttribute, List<Permission> requirePermission) {
public AbstractAclProvider(AclService aclService, String processConfigAttribute, Permission[] requirePermission) {
Assert.hasText(processConfigAttribute, "A processConfigAttribute is mandatory");
Assert.notNull(aclService, "An AclService is mandatory");
if (requirePermission == null || requirePermission.isEmpty()) {
if ((requirePermission == null) || (requirePermission.length == 0)) {
throw new IllegalArgumentException("One or more requirePermission entries is mandatory");
}
@@ -70,7 +66,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
//~ Methods ========================================================================================================
protected Class<?> getProcessDomainObjectClass() {
protected Class getProcessDomainObjectClass() {
return processDomainObjectClass;
}
@@ -79,7 +75,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication);
Sid[] sids = sidRetrievalStrategy.getSids(authentication);
Acl acl = null;
@@ -103,7 +99,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
this.processConfigAttribute = processConfigAttribute;
}
public void setProcessDomainObjectClass(Class<?> processDomainObjectClass) {
public void setProcessDomainObjectClass(Class processDomainObjectClass) {
Assert.notNull(processDomainObjectClass, "processDomainObjectClass cannot be set to null");
this.processDomainObjectClass = processDomainObjectClass;
}
@@ -124,7 +120,7 @@ public abstract class AbstractAclProvider implements AfterInvocationProvider {
*
* @return always <code>true</code>
*/
public boolean supports(Class<?> clazz) {
public boolean supports(Class clazz) {
return true;
}
}
@@ -12,20 +12,23 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.afterinvocation;
package org.springframework.security.afterinvocation;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthorizationServiceException;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.Permission;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Collection;
import java.util.Iterator;
/**
* <p>
@@ -38,8 +41,8 @@ import org.springframework.security.acls.Permission;
* <p>
* This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} matches the {@link
* #processConfigAttribute}. The provider will then lookup the ACLs from the <code>AclService</code> and ensure the
* principal is {@link org.springframework.security.acls.Acl#isGranted(List,
* List, boolean) Acl.isGranted(Permission[], Sid[], boolean)}
* principal is {@link org.springframework.security.acls.Acl#isGranted(org.springframework.security.acls.Permission[],
* org.springframework.security.acls.sid.Sid[], boolean) Acl.isGranted(Permission[], Sid[], boolean)}
* when presenting the {@link #requirePermission} array to that method.
* <p>
* If the principal does not have permission, that element will not be included in the returned
@@ -66,14 +69,13 @@ public class AclEntryAfterInvocationCollectionFilteringProvider extends Abstract
//~ Constructors ===================================================================================================
public AclEntryAfterInvocationCollectionFilteringProvider(AclService aclService, List<Permission> requirePermission) {
public AclEntryAfterInvocationCollectionFilteringProvider(AclService aclService, Permission[] requirePermission) {
super(aclService, "AFTER_ACL_COLLECTION_READ", requirePermission);
}
//~ Methods ========================================================================================================
@SuppressWarnings("unchecked")
public Object decide(Authentication authentication, Object object, List<ConfigAttribute> config,
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
if (returnedObject == null) {
@@ -84,7 +86,11 @@ public class AclEntryAfterInvocationCollectionFilteringProvider extends Abstract
return null;
}
for (ConfigAttribute attr : config) {
Iterator iter = config.getConfigAttributes().iterator();
while (iter.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) iter.next();
if (!this.supports(attr)) {
continue;
}
@@ -102,7 +108,11 @@ public class AclEntryAfterInvocationCollectionFilteringProvider extends Abstract
}
// Locate unauthorised Collection elements
for (Object domainObject : filterer) {
Iterator collectionIter = filterer.iterator();
while (collectionIter.hasNext()) {
Object domainObject = collectionIter.next();
// Ignore nulls or entries which aren't instances of the configured domain object class
if (domainObject == null || !getProcessDomainObjectClass().isAssignableFrom(domainObject.getClass())) {
continue;
@@ -12,21 +12,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.afterinvocation;
package org.springframework.security.afterinvocation;
import java.util.List;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.Permission;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.Authentication;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.Permission;
import java.util.Iterator;
/**
@@ -38,8 +42,8 @@ import org.springframework.security.acls.Permission;
* <p>
* This after invocation provider will fire if any {@link ConfigAttribute#getAttribute()} matches the {@link
* #processConfigAttribute}. The provider will then lookup the ACLs from the <tt>AclService</tt> and ensure the
* principal is {@link org.springframework.security.acls.Acl#isGranted(List,
List, boolean) Acl.isGranted(Permission[], Sid[], boolean)}
* principal is {@link org.springframework.security.acls.Acl#isGranted(org.springframework.security.acls.Permission[],
org.springframework.security.acls.sid.Sid[], boolean) Acl.isGranted(Permission[], Sid[], boolean)}
* when presenting the {@link #requirePermission} array to that method.
* <p>
* Often users will setup an <code>AclEntryAfterInvocationProvider</code> with a {@link
@@ -64,15 +68,17 @@ public class AclEntryAfterInvocationProvider extends AbstractAclProvider impleme
//~ Constructors ===================================================================================================
public AclEntryAfterInvocationProvider(AclService aclService, List<Permission> requirePermission) {
public AclEntryAfterInvocationProvider(AclService aclService, Permission[] requirePermission) {
super(aclService, "AFTER_ACL_READ", requirePermission);
}
//~ Methods ========================================================================================================
public Object decide(Authentication authentication, Object object, List<ConfigAttribute> config,
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
Iterator iter = config.getConfigAttributes().iterator();
if (returnedObject == null) {
// AclManager interface contract prohibits nulls
// As they have permission to null/nothing, grant access
@@ -89,9 +95,11 @@ public class AclEntryAfterInvocationProvider extends AbstractAclProvider impleme
}
return returnedObject;
}
}
while (iter.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) iter.next();
for (ConfigAttribute attr : config) {
if (!this.supports(attr)) {
continue;
}
@@ -12,18 +12,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.vote;
package org.springframework.security.vote;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.Authentication;
import org.springframework.security.AuthorizationServiceException;
import org.springframework.security.ConfigAttribute;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AclService;
import org.springframework.security.acls.NotFoundException;
@@ -34,7 +32,8 @@ import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalS
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategyImpl;
import org.springframework.security.vote.AbstractAclVoter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -50,8 +49,8 @@ import org.springframework.util.StringUtils;
* The voter will vote if any {@link ConfigAttribute#getAttribute()} matches the {@link #processConfigAttribute}.
* The provider will then locate the first method argument of type {@link #processDomainObjectClass}. Assuming that
* method argument is non-null, the provider will then lookup the ACLs from the <code>AclManager</code> and ensure the
* principal is {@link Acl#isGranted(List,
* List, boolean)} when presenting the {@link #requirePermission} array to that
* principal is {@link Acl#isGranted(org.springframework.security.acls.Permission[],
* org.springframework.security.acls.sid.Sid[], boolean)} when presenting the {@link #requirePermission} array to that
* method.
* <p>
* If the method argument is <tt>null</tt>, the voter will abstain from voting. If the method argument
@@ -92,7 +91,7 @@ public class AclEntryVoter extends AbstractAclVoter {
private SidRetrievalStrategy sidRetrievalStrategy = new SidRetrievalStrategyImpl();
private String internalMethod;
private String processConfigAttribute;
private List<Permission> requirePermission;
private Permission[] requirePermission;
//~ Constructors ===================================================================================================
@@ -106,7 +105,7 @@ public class AclEntryVoter extends AbstractAclVoter {
this.aclService = aclService;
this.processConfigAttribute = processConfigAttribute;
this.requirePermission = Arrays.asList(requirePermission);
this.requirePermission = requirePermission;
}
//~ Methods ========================================================================================================
@@ -151,9 +150,11 @@ public class AclEntryVoter extends AbstractAclVoter {
}
}
public int vote(Authentication authentication, Object object, List<ConfigAttribute> attributes) {
public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config) {
Iterator iter = config.getConfigAttributes().iterator();
for(ConfigAttribute attr : attributes) {
while (iter.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) iter.next();
if (!this.supports(attr)) {
continue;
@@ -168,13 +169,13 @@ public class AclEntryVoter extends AbstractAclVoter {
logger.debug("Voting to abstain - domainObject is null");
}
return ACCESS_ABSTAIN;
return AccessDecisionVoter.ACCESS_ABSTAIN;
}
// Evaluate if we are required to use an inner domain object
if (StringUtils.hasText(internalMethod)) {
try {
Class<?> clazz = domainObject.getClass();
Class clazz = domainObject.getClass();
Method method = clazz.getMethod(internalMethod, new Class[0]);
domainObject = method.invoke(domainObject, new Object[0]);
} catch (NoSuchMethodException nsme) {
@@ -197,7 +198,7 @@ public class AclEntryVoter extends AbstractAclVoter {
ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy.getObjectIdentity(domainObject);
// Obtain the SIDs applicable to the principal
List<Sid> sids = sidRetrievalStrategy.getSids(authentication);
Sid[] sids = sidRetrievalStrategy.getSids(authentication);
Acl acl;
@@ -209,7 +210,7 @@ public class AclEntryVoter extends AbstractAclVoter {
logger.debug("Voting to deny access - no ACLs apply for this principal");
}
return ACCESS_DENIED;
return AccessDecisionVoter.ACCESS_DENIED;
}
try {
@@ -218,25 +219,25 @@ public class AclEntryVoter extends AbstractAclVoter {
logger.debug("Voting to grant access");
}
return ACCESS_GRANTED;
return AccessDecisionVoter.ACCESS_GRANTED;
} else {
if (logger.isDebugEnabled()) {
logger.debug(
"Voting to deny access - ACLs returned, but insufficient permissions for this principal");
}
return ACCESS_DENIED;
return AccessDecisionVoter.ACCESS_DENIED;
}
} catch (NotFoundException nfe) {
if (logger.isDebugEnabled()) {
logger.debug("Voting to deny access - no ACLs apply for this principal");
}
return ACCESS_DENIED;
return AccessDecisionVoter.ACCESS_DENIED;
}
}
// No configuration attribute matched, so abstain
return ACCESS_ABSTAIN;
return AccessDecisionVoter.ACCESS_ABSTAIN;
}
}
@@ -10,58 +10,60 @@
-->
<beans>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="aclCache" class="org.springframework.security.acls.jdbc.EhCacheBasedAclCache">
<constructor-arg>
<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
</property>
<property name="cacheName" value="aclCache"/>
</bean>
</constructor-arg>
</bean>
<bean id="databaseSeeder" class="org.springframework.security.acls.jdbc.DatabaseSeeder">
<constructor-arg ref="dataSource"/>
<constructor-arg value="classpath:org/springframework/security/acls/jdbc/testData.sql"/>
</bean>
<bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="aclCache"/>
<constructor-arg ref="aclAuthorizationStrategy"/>
<constructor-arg>
<bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/>
</constructor-arg>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="aclAuthorizationStrategy" class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
<constructor-arg>
<list>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
</list>
</constructor-arg>
</bean>
<bean id="aclCache" class="org.springframework.security.acls.jdbc.EhCacheBasedAclCache">
<constructor-arg>
<bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
</property>
<property name="cacheName" value="aclCache"/>
</bean>
</constructor-arg>
</bean>
<bean id="aclService" class="org.springframework.security.acls.jdbc.JdbcMutableAclService">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="lookupStrategy"/>
<constructor-arg ref="aclCache"/>
</bean>
<bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="aclCache"/>
<constructor-arg ref="aclAuthorizationStrategy"/>
<constructor-arg>
<bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/>
</constructor-arg>
</bean>
<bean id="aclAuthorizationStrategy" class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl">
<constructor-arg>
<list>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
<bean class="org.springframework.security.GrantedAuthorityImpl">
<constructor-arg value="ROLE_ADMINISTRATOR"/>
</bean>
</list>
</constructor-arg>
</bean>
<bean id="aclService" class="org.springframework.security.acls.jdbc.JdbcMutableAclService">
<constructor-arg ref="dataSource"/>
<constructor-arg ref="lookupStrategy"/>
<constructor-arg ref="aclCache"/>
</bean>
<bean id="dataSource" class="org.springframework.security.TestDataSource">
<constructor-arg value="acltest" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
@@ -17,7 +17,7 @@ ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,
CLASS VARCHAR_IGNORECASE(100) NOT NULL,
CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));
--INSERT INTO ACL_CLASS VALUES (1, 'sample.contact.Contact');
INSERT INTO ACL_CLASS VALUES (1, 'sample.contact.Contact');
CREATE TABLE ACL_OBJECT_IDENTITY(
ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY,
@@ -10,115 +10,115 @@ import junit.framework.TestCase;
*/
public class AclFormattingUtilsTests extends TestCase {
//~ Methods ========================================================================================================
public final void testDemergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.demergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
//~ Methods ========================================================================================================
public final void testDemergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.demergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
public final void testDemergePatterns() throws Exception {
String original = "...........................A...R";
String removeBits = "...............................R";
Assert.assertEquals("...........................A....", AclFormattingUtils
.demergePatterns(original, removeBits));
public final void testDemergePatterns() throws Exception {
String original = "...........................A...R";
String removeBits = "...............................R";
Assert.assertEquals("...........................A....", AclFormattingUtils
.demergePatterns(original, removeBits));
Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......"));
Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL"));
}
public final void testMergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.mergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
Assert.assertEquals("ABCDEF", AclFormattingUtils.demergePatterns("ABCDEF", "......"));
Assert.assertEquals("......", AclFormattingUtils.demergePatterns("ABCDEF", "GHIJKL"));
}
public final void testMergePatternsParametersConstraints() throws Exception {
try {
AclFormattingUtils.mergePatterns(null, "SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
public final void testMergePatterns() throws Exception {
String original = "...............................R";
String extraBits = "...........................A....";
Assert.assertEquals("...........................A...R", AclFormattingUtils
.mergePatterns(original, extraBits));
public final void testMergePatterns() throws Exception {
String original = "...............................R";
String extraBits = "...........................A....";
Assert.assertEquals("...........................A...R", AclFormattingUtils
.mergePatterns(original, extraBits));
Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......"));
Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"));
}
public final void testBinaryPrints() throws Exception {
Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15));
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x'));
}
Assert.assertEquals("ABCDEF", AclFormattingUtils.mergePatterns("ABCDEF", "......"));
Assert.assertEquals("GHIJKL", AclFormattingUtils.mergePatterns("ABCDEF", "GHIJKL"));
}
public final void testBinaryPrints() throws Exception {
Assert.assertEquals("............................****", AclFormattingUtils.printBinary(15));
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
Assert.assertTrue(true);
}
Assert.assertEquals("............................xxxx", AclFormattingUtils.printBinary(15, 'x'));
}
}
@@ -1,57 +0,0 @@
package org.springframework.security.acls;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.Authentication;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.objectidentity.ObjectIdentityRetrievalStrategy;
import org.springframework.security.acls.sid.SidRetrievalStrategy;
/**
*
* @author Luke Taylor
* @version $Id$
* @since 2.5
*/
public class AclPermissionEvaluatorTests {
Mockery jmock = new JUnit4Mockery();
Authentication user;
private AclService service;
private ObjectIdentityRetrievalStrategy oidStrategy;
private SidRetrievalStrategy sidStrategy;
@Before
public void setup() throws Exception {
user = jmock.mock(Authentication.class);
service = jmock.mock(AclService.class);
oidStrategy = jmock.mock(ObjectIdentityRetrievalStrategy.class);
sidStrategy = jmock.mock(SidRetrievalStrategy.class);
}
@Test
public void hasPermissionReturnsTrueIfAclGrantsPermission() throws Exception {
AclPermissionEvaluator pe = new AclPermissionEvaluator(service);
final Acl acl = jmock.mock(Acl.class);
pe.setObjectIdentityRetrievalStrategy(oidStrategy);
pe.setSidRetrievalStrategy(sidStrategy);
jmock.checking(new Expectations() {{
ignoring(user);
ignoring(oidStrategy);
ignoring(sidStrategy);
oneOf(service).readAclById(with(any(ObjectIdentity.class)), with(any(List.class)));
will(returnValue(acl));
oneOf(acl).isGranted(with(any(List.class)), with(any(List.class)), with(equal(false)));
will(returnValue(true));
}});
assertTrue(pe.hasPermission(user, new Object(), "READ"));
}
}
@@ -0,0 +1,136 @@
package org.springframework.security.acls.domain;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AuditableAccessControlEntry;
import org.springframework.security.acls.NotFoundException;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.UnloadedSidException;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
/**
* Test class for {@link AccessControlEntryImpl}
*
* @author Andrei Stefan
*/
public class AccessControlEntryTests extends TestCase {
//~ Methods ========================================================================================================
public void testConstructorRequiredFields() throws Exception {
// Check Acl field is present
try {
AccessControlEntry ace = new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"),
BasePermission.ADMINISTRATION, true, true, true);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
// Check Sid field is present
try {
AccessControlEntry ace = new AccessControlEntryImpl(null, new MockAcl(), null,
BasePermission.ADMINISTRATION, true, true, true);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
// Check Permission field is present
try {
AccessControlEntry ace = new AccessControlEntryImpl(null, new MockAcl(), new PrincipalSid("johndoe"), null,
true, true, true);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
}
public void testAccessControlEntryImplGetters() throws Exception {
Acl mockAcl = new MockAcl();
Sid sid = new PrincipalSid("johndoe");
// Create a sample entry
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
true, true, true);
// and check every get() method
Assert.assertEquals(new Long(1), ace.getId());
Assert.assertEquals(mockAcl, ace.getAcl());
Assert.assertEquals(sid, ace.getSid());
Assert.assertTrue(ace.isGranting());
Assert.assertEquals(BasePermission.ADMINISTRATION, ace.getPermission());
Assert.assertTrue(((AuditableAccessControlEntry) ace).isAuditFailure());
Assert.assertTrue(((AuditableAccessControlEntry) ace).isAuditSuccess());
}
public void testEquals() throws Exception {
Acl mockAcl = new MockAcl();
Sid sid = new PrincipalSid("johndoe");
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
true, true, true);
Assert.assertFalse(ace.equals(null));
Assert.assertFalse(ace.equals(new Long(100)));
Assert.assertTrue(ace.equals(ace));
Assert.assertTrue(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(2), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, new PrincipalSid("scott"),
BasePermission.ADMINISTRATION, true, true, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.WRITE, true,
true, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, false, true, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, false, true)));
Assert.assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, false)));
}
//~ Inner Classes ==================================================================================================
private class MockAcl implements Acl {
public AccessControlEntry[] getEntries() {
return null;
}
public ObjectIdentity getObjectIdentity() {
return null;
}
public Sid getOwner() {
return null;
}
public Acl getParentAcl() {
return null;
}
public boolean isEntriesInheriting() {
return false;
}
public boolean isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
return false;
}
public boolean isSidLoaded(Sid[] sids) {
return false;
}
}
}
@@ -1,106 +0,0 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AuditableAccessControlEntry;
import org.springframework.security.acls.objectidentity.ObjectIdentity;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
/**
* Tests for {@link AccessControlEntryImpl}.
*
* @author Andrei Stefan
* @version $Id$
*/
public class AccessControlImplEntryTests {
Mockery jmock = new JUnit4Mockery();
//~ Methods ========================================================================================================
@Test
public void testConstructorRequiredFields() {
// Check Acl field is present
try {
new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"),
BasePermission.ADMINISTRATION, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check Sid field is present
try {
new AccessControlEntryImpl(null, jmock.mock(Acl.class), null,
BasePermission.ADMINISTRATION, true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check Permission field is present
try {
new AccessControlEntryImpl(null, jmock.mock(Acl.class), new PrincipalSid("johndoe"), null,
true, true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testAccessControlEntryImplGetters() {
Acl mockAcl = jmock.mock(Acl.class);
Sid sid = new PrincipalSid("johndoe");
// Create a sample entry
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
true, true, true);
// and check every get() method
assertEquals(new Long(1), ace.getId());
assertEquals(mockAcl, ace.getAcl());
assertEquals(sid, ace.getSid());
assertTrue(ace.isGranting());
assertEquals(BasePermission.ADMINISTRATION, ace.getPermission());
assertTrue(((AuditableAccessControlEntry) ace).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) ace).isAuditSuccess());
}
@Test
public void testEquals() {
final Acl mockAcl = jmock.mock(Acl.class);
final ObjectIdentity oid = jmock.mock(ObjectIdentity.class);
jmock.checking(new Expectations() {{
allowing(mockAcl).getObjectIdentity(); will(returnValue(oid));
}});
Sid sid = new PrincipalSid("johndoe");
AccessControlEntry ace = new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.ADMINISTRATION,
true, true, true);
assertFalse(ace.equals(null));
assertFalse(ace.equals(new Long(100)));
assertTrue(ace.equals(ace));
assertTrue(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(2), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, new PrincipalSid("scott"),
BasePermission.ADMINISTRATION, true, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid, BasePermission.WRITE, true,
true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, false, true, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, false, true)));
assertFalse(ace.equals(new AccessControlEntryImpl(new Long(1), mockAcl, sid,
BasePermission.ADMINISTRATION, true, true, false)));
}
}
@@ -1,18 +1,11 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
@@ -36,146 +29,186 @@ import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.security.util.FieldUtils;
/**
* Tests for {@link AclImpl}.
*
*
* @author Andrei Stefan
*/
public class AclImplTests {
private static final List<Permission> READ = Arrays.asList(BasePermission.READ );
private static final List<Permission> WRITE = Arrays.asList(BasePermission.WRITE);
private static final List<Permission> CREATE = Arrays.asList(BasePermission.CREATE );
private static final List<Permission> DELETE = Arrays.asList(BasePermission.DELETE );
private static final List<Sid> SCOTT = Arrays.asList((Sid)new PrincipalSid("scott"));
private static final List<Sid> BEN = Arrays.asList((Sid)new PrincipalSid("ben"));
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored", "ROLE_ADMINISTRATOR");
Mockery jmockCtx = new Mockery();
AclAuthorizationStrategy mockAuthzStrategy;
AuditLogger mockAuditLogger;
ObjectIdentity objectIdentity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
public class AclImplTests extends TestCase {
// ~ Methods ========================================================================================================
@Before
public void setUp() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
mockAuthzStrategy = jmockCtx.mock(AclAuthorizationStrategy.class);
mockAuditLogger = jmockCtx.mock(AuditLogger.class);;
jmockCtx.checking(new Expectations() {{
ignoring(mockAuthzStrategy);
ignoring(mockAuditLogger);
}});
auth.setAuthenticated(true);
@Override
protected void setUp() throws Exception {
super.setUp();
}
@After
public void tearDown() throws Exception {
@Override
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
super.tearDown();
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorsRejectNullObjectIdentity() throws Exception {
try {
new AclImpl(null, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid("johndoe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new AclImpl(null, new Long(1), mockAuthzStrategy, mockAuditLogger);
}
public void testConstructorsRejectNullParameters() throws Exception {
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
@Test(expected=IllegalArgumentException.class)
public void testConstructorsRejectNullId() throws Exception {
try {
new AclImpl(objectIdentity, null, mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid("johndoe"));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new AclImpl(objectIdentity, null, mockAuthzStrategy, mockAuditLogger);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorsRejectNullAclAuthzStrategy() throws Exception {
try {
new AclImpl(objectIdentity, new Long(1), null, mockAuditLogger, null, null, true, new PrincipalSid("johndoe"));
Acl acl = new AclImpl(null, new Long(1), strategy, auditLogger);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
new AclImpl(objectIdentity, new Long(1), null, mockAuditLogger);
}
@Test(expected=IllegalArgumentException.class)
public void testConstructorsRejectNullAuditLogger() throws Exception {
try {
new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, null, null, null, true, new PrincipalSid("johndoe"));
Acl acl = new AclImpl(identity, null, strategy, auditLogger);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, new Long(1), null, auditLogger);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, new Long(1), strategy, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(null, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid("johndoe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, null, strategy, auditLogger, null, null, true, new PrincipalSid("johndoe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, new Long(1), null, auditLogger, null, null, true, new PrincipalSid("johndoe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, new Long(1), strategy, null, null, null, true, new PrincipalSid("johndoe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
Acl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, null);
}
@Test
public void testInsertAceRejectsNullParameters() throws Exception {
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
try {
acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
acl.insertAce(0, BasePermission.READ, null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@Test
public void testInsertAceAddsElementAtCorrectIndex() throws Exception {
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid("johndoe"));
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
// Insert one permission
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
// Check it was successfully added
assertEquals(1, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getAcl(), acl);
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid("ROLE_TEST1"));
assertEquals(1, acl.getEntries().length);
assertEquals(acl.getEntries()[0].getAcl(), acl);
assertEquals(acl.getEntries()[0].getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[0].getSid(), new GrantedAuthoritySid("ROLE_TEST1"));
// Add a second permission
acl.insertAce(1, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
service.updateAcl(acl);
// Check it was added on the last position
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(1).getAcl(), acl);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(2, acl.getEntries().length);
assertEquals(acl.getEntries()[1].getAcl(), acl);
assertEquals(acl.getEntries()[1].getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[1].getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
// Add a third permission, after the first one
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"), false);
service.updateAcl(acl);
assertEquals(3, acl.getEntries().size());
assertEquals(3, acl.getEntries().length);
// Check the third entry was added between the two existent ones
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid("ROLE_TEST1"));
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid("ROLE_TEST3"));
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(2).getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(acl.getEntries()[0].getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[0].getSid(), new GrantedAuthoritySid("ROLE_TEST1"));
assertEquals(acl.getEntries()[1].getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries()[1].getSid(), new GrantedAuthoritySid("ROLE_TEST3"));
assertEquals(acl.getEntries()[2].getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[2].getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
}
@Test(expected=NotFoundException.class)
public void testInsertAceFailsForInexistentElement() throws Exception {
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
@@ -183,12 +216,26 @@ public class AclImplTests {
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
service.updateAcl(acl);
acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
try {
acl.insertAce(55, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
}
@Test
public void testDeleteAceKeepsInitialOrdering() throws Exception {
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
@@ -200,68 +247,83 @@ public class AclImplTests {
// Delete first permission and check the order of the remaining permissions is kept
acl.deleteAce(0);
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid("ROLE_TEST3"));
assertEquals(2, acl.getEntries().length);
assertEquals(acl.getEntries()[0].getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(acl.getEntries()[1].getSid(), new GrantedAuthoritySid("ROLE_TEST3"));
// Add one more permission and remove the permission in the middle
acl.insertAce(2, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true);
service.updateAcl(acl);
acl.deleteAce(1);
assertEquals(2, acl.getEntries().size());
assertEquals(acl.getEntries().get(0).getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(acl.getEntries().get(1).getSid(), new GrantedAuthoritySid("ROLE_TEST4"));
assertEquals(2, acl.getEntries().length);
assertEquals(acl.getEntries()[0].getSid(), new GrantedAuthoritySid("ROLE_TEST2"));
assertEquals(acl.getEntries()[1].getSid(), new GrantedAuthoritySid("ROLE_TEST4"));
// Remove remaining permissions
acl.deleteAce(1);
acl.deleteAce(0);
assertEquals(0, acl.getEntries().size());
assertEquals(0, acl.getEntries().length);
}
@Test
public void testDeleteAceFailsForInexistentElement() throws Exception {
Authentication auth = new TestingAuthenticationToken("johndoe", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
try {
acl.deleteAce(99);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
}
@Test
public void testIsGrantingRejectsEmptyParameters() throws Exception {
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
Sid ben = new PrincipalSid("ben");
try {
acl.isGranted(new ArrayList<Permission>(0), Arrays.asList(ben) , false);
acl.isGranted(new Permission[] {}, new Sid[] { new PrincipalSid("ben") }, false);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
acl.isGranted(READ, new ArrayList<Sid>(0), false);
acl.isGranted(new Permission[] { BasePermission.READ }, new Sid[] {}, false);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@Test
public void testIsGrantingGrantsAccessForAclWithNoParent() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_GENERAL","ROLE_GUEST");
Authentication auth = new TestingAuthenticationToken("ben", "ignored", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL"), new GrantedAuthorityImpl("ROLE_GUEST") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity rootOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
// Create an ACL which owner is not the authenticated principal
MutableAcl rootAcl = new AclImpl(rootOid, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, false, new PrincipalSid(
MutableAcl rootAcl = new AclImpl(rootOid, new Long(1), strategy, auditLogger, null, null, false, new PrincipalSid(
"johndoe"));
// Grant some permissions
@@ -271,33 +333,42 @@ public class AclImplTests {
rootAcl.insertAce(3, BasePermission.WRITE, new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), true);
// Check permissions granting
List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE);
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
Permission[] permissions = new Permission[] { BasePermission.READ, BasePermission.CREATE };
Sid[] sids = new Sid[] { new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST") };
assertFalse(rootAcl.isGranted(permissions, sids, false));
try {
rootAcl.isGranted(permissions, SCOTT, false);
rootAcl.isGranted(permissions, new Sid[] { new PrincipalSid("scott") }, false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
assertTrue(rootAcl.isGranted(WRITE, SCOTT, false));
assertFalse(rootAcl.isGranted(WRITE,
Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false));
assertTrue(rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false));
assertTrue(rootAcl.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] { new PrincipalSid("scott") },
false));
assertFalse(rootAcl.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] { new PrincipalSid("rod"),
new GrantedAuthoritySid("WRITE_ACCESS_ROLE") }, false));
assertTrue(rootAcl.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] {
new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod") }, false));
try {
// Change the type of the Sid and check the granting process
rootAcl.isGranted(WRITE, Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false);
rootAcl.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] { new GrantedAuthoritySid("rod"),
new PrincipalSid("WRITE_ACCESS_ROLE") }, false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
}
@Test
public void testIsGrantingGrantsAccessForInheritableAcls() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored","ROLE_GENERAL");
Authentication auth = new TestingAuthenticationToken("ben", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity grandParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity parentOid1 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity parentOid2 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
@@ -305,15 +376,15 @@ public class AclImplTests {
ObjectIdentity childOid2 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(104));
// Create ACLs
MutableAcl grandParentAcl = new AclImpl(grandParentOid, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, false,
MutableAcl grandParentAcl = new AclImpl(grandParentOid, new Long(1), strategy, auditLogger, null, null, false,
new PrincipalSid("johndoe"));
MutableAcl parentAcl1 = new AclImpl(parentOid1, new Long(2), mockAuthzStrategy, mockAuditLogger, null, null, true,
MutableAcl parentAcl1 = new AclImpl(parentOid1, new Long(2), strategy, auditLogger, null, null, true,
new PrincipalSid("johndoe"));
MutableAcl parentAcl2 = new AclImpl(parentOid2, new Long(3), mockAuthzStrategy, mockAuditLogger, null, null, true,
MutableAcl parentAcl2 = new AclImpl(parentOid2, new Long(3), strategy, auditLogger, null, null, true,
new PrincipalSid("johndoe"));
MutableAcl childAcl1 = new AclImpl(childOid1, new Long(4), mockAuthzStrategy, mockAuditLogger, null, null, true,
MutableAcl childAcl1 = new AclImpl(childOid1, new Long(4), strategy, auditLogger, null, null, true,
new PrincipalSid("johndoe"));
MutableAcl childAcl2 = new AclImpl(childOid2, new Long(4), mockAuthzStrategy, mockAuditLogger, null, null, false,
MutableAcl childAcl2 = new AclImpl(childOid2, new Long(4), strategy, auditLogger, null, null, false,
new PrincipalSid("johndoe"));
// Create hierarchies
@@ -333,33 +404,45 @@ public class AclImplTests {
childAcl1.insertAce(0, BasePermission.CREATE, new PrincipalSid("scott"), true);
// Check granting process for parent1
assertTrue(parentAcl1.isGranted(READ, SCOTT, false));
assertTrue(parentAcl1.isGranted(READ, Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_USER_READ")), false));
assertTrue(parentAcl1.isGranted(WRITE, BEN, false));
assertFalse(parentAcl1.isGranted(DELETE, BEN, false));
assertFalse(parentAcl1.isGranted(DELETE, SCOTT, false));
assertTrue(parentAcl1.isGranted(new Permission[] { BasePermission.READ }, new Sid[] { new PrincipalSid("scott") },
false));
assertTrue(parentAcl1.isGranted(new Permission[] { BasePermission.READ }, new Sid[] { new GrantedAuthoritySid(
"ROLE_USER_READ") }, false));
assertTrue(parentAcl1.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] { new PrincipalSid("ben") },
false));
assertFalse(parentAcl1.isGranted(new Permission[] { BasePermission.DELETE }, new Sid[] { new PrincipalSid("ben") },
false));
assertFalse(parentAcl1.isGranted(new Permission[] { BasePermission.DELETE },
new Sid[] { new PrincipalSid("scott") }, false));
// Check granting process for parent2
assertTrue(parentAcl2.isGranted(CREATE, BEN, false));
assertTrue(parentAcl2.isGranted(WRITE, BEN, false));
assertFalse(parentAcl2.isGranted(DELETE, BEN, false));
assertTrue(parentAcl2.isGranted(new Permission[] { BasePermission.CREATE }, new Sid[] { new PrincipalSid("ben") },
false));
assertTrue(parentAcl2.isGranted(new Permission[] { BasePermission.WRITE }, new Sid[] { new PrincipalSid("ben") },
false));
assertFalse(parentAcl2.isGranted(new Permission[] { BasePermission.DELETE }, new Sid[] { new PrincipalSid("ben") },
false));
// Check granting process for child1
assertTrue(childAcl1.isGranted(CREATE, SCOTT,
assertTrue(childAcl1.isGranted(new Permission[] { BasePermission.CREATE }, new Sid[] { new PrincipalSid("scott") },
false));
assertTrue(childAcl1.isGranted(new Permission[] { BasePermission.READ }, new Sid[] { new GrantedAuthoritySid(
"ROLE_USER_READ") }, false));
assertFalse(childAcl1.isGranted(new Permission[] { BasePermission.DELETE }, new Sid[] { new PrincipalSid("ben") },
false));
assertTrue(childAcl1.isGranted(READ, Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_USER_READ")), false));
assertFalse(childAcl1.isGranted(DELETE, BEN, false));
// Check granting process for child2 (doesn't inherit the permissions from its parent)
try {
assertTrue(childAcl2.isGranted(CREATE, SCOTT, false));
assertTrue(childAcl2.isGranted(new Permission[] { BasePermission.CREATE },
new Sid[] { new PrincipalSid("scott") }, false));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
try {
assertTrue(childAcl2.isGranted(CREATE, Arrays.asList((Sid)new PrincipalSid("johndoe")), false));
assertTrue(childAcl2.isGranted(new Permission[] { BasePermission.CREATE }, new Sid[] { new PrincipalSid(
"johndoe") }, false));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
@@ -367,12 +450,17 @@ public class AclImplTests {
}
}
@Test
public void testUpdateAce() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored","ROLE_GENERAL");
Authentication auth = new TestingAuthenticationToken("ben", "ignored",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, false, new PrincipalSid(
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, false, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
@@ -381,9 +469,9 @@ public class AclImplTests {
acl.insertAce(2, BasePermission.CREATE, new PrincipalSid("ben"), true);
service.updateAcl(acl);
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.CREATE);
assertEquals(acl.getEntries()[0].getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[1].getPermission(), BasePermission.WRITE);
assertEquals(acl.getEntries()[2].getPermission(), BasePermission.CREATE);
// Change each permission
acl.updateAce(0, BasePermission.CREATE);
@@ -391,17 +479,22 @@ public class AclImplTests {
acl.updateAce(2, BasePermission.READ);
// Check the change was successfuly made
assertEquals(acl.getEntries().get(0).getPermission(), BasePermission.CREATE);
assertEquals(acl.getEntries().get(1).getPermission(), BasePermission.DELETE);
assertEquals(acl.getEntries().get(2).getPermission(), BasePermission.READ);
assertEquals(acl.getEntries()[0].getPermission(), BasePermission.CREATE);
assertEquals(acl.getEntries()[1].getPermission(), BasePermission.DELETE);
assertEquals(acl.getEntries()[2].getPermission(), BasePermission.READ);
}
@Test
public void testUpdateAuditing() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_AUDITING", "ROLE_GENERAL");
Authentication auth = new TestingAuthenticationToken("ben", "ignored", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_AUDITING"), new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, false, new PrincipalSid(
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, false, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
@@ -409,74 +502,82 @@ public class AclImplTests {
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditSuccess());
assertFalse(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditSuccess());
assertFalse(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditFailure());
assertFalse(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditSuccess());
assertFalse(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditSuccess());
// Change each permission
((AuditableAcl) acl).updateAuditing(0, true, true);
((AuditableAcl) acl).updateAuditing(1, true, true);
// Check the change was successfuly made
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(0)).isAuditSuccess());
assertTrue(((AuditableAccessControlEntry) acl.getEntries().get(1)).isAuditSuccess());
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditFailure());
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditSuccess());
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditSuccess());
}
@Test
public void testGettersSetters() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL"), new GrantedAuthorityImpl("ROLE_GENERAL"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity identity2 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
MutableAcl acl = new AclImpl(identity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
MutableAcl parentAcl = new AclImpl(identity2, new Long(2), mockAuthzStrategy, mockAuditLogger, null, null, true, new PrincipalSid(
MutableAcl parentAcl = new AclImpl(identity2, new Long(2), strategy, auditLogger, null, null, true, new PrincipalSid(
"johndoe"));
MockAclService service = new MockAclService();
acl.insertAce(0, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
acl.insertAce(1, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
service.updateAcl(acl);
assertEquals(acl.getId(), new Long(1));
assertEquals(acl.getObjectIdentity(), identity);
assertEquals(acl.getOwner(), new PrincipalSid("johndoe"));
assertNull(acl.getParentAcl());
assertTrue(acl.isEntriesInheriting());
assertEquals(2, acl.getEntries().size());
assertEquals(2, acl.getEntries().length);
acl.setParent(parentAcl);
assertEquals(acl.getParentAcl(), parentAcl);
acl.setEntriesInheriting(false);
assertFalse(acl.isEntriesInheriting());
((OwnershipAcl) acl).setOwner(new PrincipalSid("ben"));
assertEquals(acl.getOwner(), new PrincipalSid("ben"));
}
@Test
public void testIsSidLoaded() throws Exception {
List<Sid> loadedSids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED"));
MutableAcl acl = new AclImpl(objectIdentity, new Long(1), mockAuthzStrategy, mockAuditLogger, null, loadedSids, true, new PrincipalSid(
AclAuthorizationStrategyImpl strategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL"), new GrantedAuthorityImpl("ROLE_GENERAL"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
AuditLogger auditLogger = new ConsoleAuditLogger();
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
Sid[] loadedSids = new Sid[] { new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_IGNORED") };
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, loadedSids, true, new PrincipalSid(
"johndoe"));
assertTrue(acl.isSidLoaded(loadedSids));
assertTrue(acl.isSidLoaded(Arrays.asList(new GrantedAuthoritySid("ROLE_IGNORED"), new PrincipalSid("ben"))));
assertTrue(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_IGNORED"))));
assertTrue(acl.isSidLoaded(BEN));
assertTrue(acl.isSidLoaded(new Sid[] { new GrantedAuthoritySid("ROLE_IGNORED"), new PrincipalSid("ben") }));
assertTrue(acl.isSidLoaded(new Sid[] { new GrantedAuthoritySid("ROLE_IGNORED")}));
assertTrue(acl.isSidLoaded(new Sid[] { new PrincipalSid("ben") }));
assertTrue(acl.isSidLoaded(null));
assertTrue(acl.isSidLoaded(new ArrayList<Sid>(0)));
assertTrue(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED"))));
assertFalse(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED"))));
assertFalse(acl.isSidLoaded(Arrays.asList((Sid)new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL"))));
assertTrue(acl.isSidLoaded(new Sid[] { }));
assertTrue(acl.isSidLoaded(new Sid[] { new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_IGNORED") }));
assertFalse(acl.isSidLoaded(new Sid[] { new GrantedAuthoritySid("ROLE_GENERAL"), new GrantedAuthoritySid("ROLE_IGNORED") }));
assertFalse(acl.isSidLoaded(new Sid[] { new GrantedAuthoritySid("ROLE_IGNORED"), new GrantedAuthoritySid("ROLE_GENERAL") }));
}
//~ Inner Classes ==================================================================================================
// ~ Inner Classes ==================================================================================================
private class MockAclService implements MutableAclService {
public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
@@ -490,9 +591,8 @@ public class AclImplTests {
* Mock implementation that populates the aces list with fully initialized AccessControlEntries
* @see org.springframework.security.acls.MutableAclService#updateAcl(org.springframework.security.acls.MutableAcl)
*/
@SuppressWarnings("unchecked")
public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException {
List<AccessControlEntry> oldAces = acl.getEntries();
AccessControlEntry[] oldAces = acl.getEntries();
Field acesField = FieldUtils.getField(AclImpl.class, "aces");
acesField.setAccessible(true);
List newAces;
@@ -500,8 +600,8 @@ public class AclImplTests {
newAces = (List) acesField.get(acl);
newAces.clear();
for (int i = 0; i < oldAces.size(); i++) {
AccessControlEntry ac = oldAces.get(i);
for (int i = 0; i < oldAces.length; i++) {
AccessControlEntry ac = oldAces[i];
// Just give an ID to all this acl's aces, rest of the fields are just copied
newAces.add(new AccessControlEntryImpl(new Long(i + 1), ac.getAcl(), ac.getSid(), ac.getPermission(), ac
.isGranting(), ((AuditableAccessControlEntry) ac).isAuditSuccess(),
@@ -515,7 +615,7 @@ public class AclImplTests {
return acl;
}
public List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity) {
public ObjectIdentity[] findChildren(ObjectIdentity parentIdentity) {
return null;
}
@@ -523,15 +623,15 @@ public class AclImplTests {
return null;
}
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
public Acl readAclById(ObjectIdentity object, Sid[] sids) throws NotFoundException {
return null;
}
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects) throws NotFoundException {
public Map readAclsById(ObjectIdentity[] objects) throws NotFoundException {
return null;
}
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException {
public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) throws NotFoundException {
return null;
}
}
@@ -19,243 +19,278 @@ import org.springframework.security.providers.TestingAuthenticationToken;
/**
* Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl}
* security checks.
*
*
* @author Andrei Stefan
*/
public class AclImplementationSecurityCheckTests extends TestCase {
//~ Methods ========================================================================================================
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
SecurityContextHolder.clearContext();
}
protected void setUp() throws Exception {
SecurityContextHolder.clearContext();
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
protected void tearDown() throws Exception {
SecurityContextHolder.clearContext();
}
public void testSecurityCheckNoACEs() throws Exception {
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_OWNERSHIP") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
public void testSecurityCheckNoACEs() throws Exception {
Authentication auth = new TestingAuthenticationToken("user", "password","ROLE_GENERAL","ROLE_AUDITING","ROLE_OWNERSHIP");
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
Acl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
Acl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
// Create another authorization strategy
AclAuthorizationStrategy aclAuthorizationStrategy2 = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"),
new GrantedAuthorityImpl("ROLE_THREE") });
Acl acl2 = new AclImpl(identity, new Long(1), aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
}
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
public void testSecurityCheckWithMultipleACEs() throws Exception {
// Create a simple authentication with ROLE_GENERAL
Authentication auth = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
// Create another authorization strategy
AclAuthorizationStrategy aclAuthorizationStrategy2 = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"),
new GrantedAuthorityImpl("ROLE_THREE") });
Acl acl2 = new AclImpl(identity, new Long(1), aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
}
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
public void testSecurityCheckWithMultipleACEs() throws Exception {
// Create a simple authentication with ROLE_GENERAL
Authentication auth = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
// Let's give the principal the ADMINISTRATION permission, without
// granting access
MutableAcl aclFirstDeny = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
// The CHANGE_GENERAL test should pass as the principal has ROLE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities,
// nor granting access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
Assert.assertTrue(true);
}
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
Assert.assertTrue(true);
}
// Let's give the principal the ADMINISTRATION permission, without
// granting access
MutableAcl aclFirstDeny = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
aclFirstDeny.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
// Add granting access to this principal
aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag
// (false) will deny this access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
Assert.assertTrue(true);
}
// The CHANGE_GENERAL test should pass as the principal has ROLE_GENERAL
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_GENERAL);
// Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access
MutableAcl aclFirstAllow = new AclImpl(identity, new Long(1), aclAuthorizationStrategy,
new ConsoleAuditLogger());
aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities,
// nor granting access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// The CHANGE_AUDITING test should pass as there is one ACE with
// granting access
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
// Add granting access to this principal
aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag
// (false) will deny this access
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// Add a deny ACE and test again for CHANGE_AUDITING
aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
// Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access
MutableAcl aclFirstAllow = new AclImpl(identity, new Long(1), aclAuthorizationStrategy,
new ConsoleAuditLogger());
aclFirstAllow.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// Create an ACL with no ACE
MutableAcl aclNoACE = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
// and still grant access for CHANGE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
}
// The CHANGE_AUDITING test should pass as there is one ACE with
// granting access
public void testSecurityCheckWithInheritableACEs() throws Exception {
// Create a simple authentication with ROLE_GENERAL
Authentication auth = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
// Add a deny ACE and test again for CHANGE_AUDITING
aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
// Let's give the principal an ADMINISTRATION permission, with granting
// access
MutableAcl parentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
MutableAcl childAcl = new AclImpl(identity, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
// Create an ACL with no ACE
MutableAcl aclNoACE = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
// and still grant access for CHANGE_GENERAL
try {
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
}
// Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
public void testSecurityCheckWithInheritableACEs() throws Exception {
// Create a simple authentication with ROLE_GENERAL
Authentication auth = new TestingAuthenticationToken("user", "password",
new GrantedAuthority[] { new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
// Link the child with its parent and test again against the
// CHANGE_OWNERSHIP right
childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
// Authorization strategy will require a different role for each access
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
// Create a root parent and link it to the middle parent
MutableAcl rootParentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy,
new ConsoleAuditLogger());
parentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
rootParentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
parentAcl.setEntriesInheriting(true);
parentAcl.setParent(rootParentAcl);
childAcl.setParent(parentAcl);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
}
// Let's give the principal an ADMINISTRATION permission, with granting
// access
MutableAcl parentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
MutableAcl childAcl = new AclImpl(identity, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
public void testSecurityCheckPrincipalOwner() throws Exception {
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_ONE"),
new GrantedAuthorityImpl("ROLE_ONE") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
// Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
// Link the child with its parent and test again against the
// CHANGE_OWNERSHIP right
childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
// Create a root parent and link it to the middle parent
MutableAcl rootParentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy,
new ConsoleAuditLogger());
parentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
rootParentAcl.insertAce(0, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
parentAcl.setEntriesInheriting(true);
parentAcl.setParent(rootParentAcl);
childAcl.setParent(parentAcl);
try {
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (NotFoundException expected) {
Assert.fail("It shouldn't have thrown NotFoundException");
}
}
public void testSecurityCheckPrincipalOwner() throws Exception {
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_ONE"),
new GrantedAuthorityImpl("ROLE_ONE") });
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
new GrantedAuthorityImpl("ROLE_GENERAL") });
Acl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger(), null, null,
false, new PrincipalSid(auth));
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
}
Acl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger(), null, null,
false, new PrincipalSid(auth));
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
catch (NotFoundException expected) {
Assert.assertTrue(true);
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
Assert.assertTrue(true);
}
catch (AccessDeniedException notExpected) {
Assert.fail("It shouldn't have thrown AccessDeniedException");
}
}
}
@@ -1,92 +1,137 @@
package org.springframework.security.acls.domain;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AuditableAccessControlEntry;
import org.springframework.security.acls.Permission;
import org.springframework.security.acls.sid.Sid;
/**
* Test class for {@link ConsoleAuditLogger}.
*
*
* @author Andrei Stefan
* @version $Id$
*/
public class AuditLoggerTests {
public class AuditLoggerTests extends TestCase {
//~ Instance fields ================================================================================================
private Mockery jmock = new JUnit4Mockery();
private PrintStream console;
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
private ConsoleAuditLogger logger;
private AuditableAccessControlEntry ace;
private Expectations aceRequiresAudit;
private Expectations aceDoesntRequireAudit;
private PrintStream console;
//~ Methods ========================================================================================================
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//~ Methods ========================================================================================================
@Before
public void setUp() throws Exception {
logger = new ConsoleAuditLogger();
ace = jmock.mock(AuditableAccessControlEntry.class);
aceRequiresAudit = new Expectations() {{
allowing(ace).isAuditSuccess(); will(returnValue(true));
allowing(ace).isAuditFailure(); will(returnValue(true));
}};
aceDoesntRequireAudit = new Expectations() {{
allowing(ace).isAuditSuccess(); will(returnValue(false));
allowing(ace).isAuditFailure(); will(returnValue(false));
}};
public void setUp() throws Exception {
console = System.out;
System.setOut(new PrintStream(bytes));
}
console = System.out;
System.setOut(new PrintStream(bytes));
}
public void tearDown() throws Exception {
System.setOut(console);
}
@After
public void tearDown() throws Exception {
System.setOut(console);
bytes.reset();
}
public void testLoggingTests() throws Exception {
ConsoleAuditLogger logger = new ConsoleAuditLogger();
MockAccessControlEntryImpl auditableAccessControlEntry = new MockAccessControlEntryImpl();
@Test
public void nonAuditableAceIsIgnored() {
AccessControlEntry ace = jmock.mock(AccessControlEntry.class);
logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size());
}
logger.logIfNeeded(true, auditableAccessControlEntry);
Assert.assertTrue(bytes.size() == 0);
@Test
public void successIsNotLoggedIfAceDoesntRequireSuccessAudit() throws Exception {
jmock.checking(aceDoesntRequireAudit);
logger.logIfNeeded(true, ace);
assertEquals(0, bytes.size());
}
bytes.reset();
logger.logIfNeeded(false, auditableAccessControlEntry);
Assert.assertTrue(bytes.size() == 0);
@Test
public void successIsLoggedIfAceRequiresSuccessAudit() throws Exception {
jmock.checking(aceRequiresAudit);
logger.logIfNeeded(true, ace);
assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
}
auditableAccessControlEntry.setAuditSuccess(true);
bytes.reset();
@Test
public void failureIsntLoggedIfAceDoesntRequireFailureAudit() throws Exception {
jmock.checking(aceDoesntRequireAudit);
logger.logIfNeeded(false, ace);
assertEquals(0, bytes.size());
}
logger.logIfNeeded(true, auditableAccessControlEntry);
Assert.assertTrue(bytes.toString().length() > 0);
Assert.assertTrue(bytes.toString().startsWith("GRANTED due to ACE"));
@Test
public void failureIsLoggedIfAceRequiresFailureAudit() throws Exception {
jmock.checking(aceRequiresAudit);
logger.logIfNeeded(false, ace);
assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
}
auditableAccessControlEntry.setAuditFailure(true);
bytes.reset();
logger.logIfNeeded(false, auditableAccessControlEntry);
Assert.assertTrue(bytes.toString().length() > 0);
Assert.assertTrue(bytes.toString().startsWith("DENIED due to ACE"));
MockAccessControlEntry accessControlEntry = new MockAccessControlEntry();
bytes.reset();
logger.logIfNeeded(true, accessControlEntry);
Assert.assertTrue(bytes.size() == 0);
}
//~ Inner Classes ==================================================================================================
private class MockAccessControlEntryImpl implements AuditableAccessControlEntry {
private boolean auditFailure = false;
private boolean auditSuccess = false;
public boolean isAuditFailure() {
return auditFailure;
}
public boolean isAuditSuccess() {
return auditSuccess;
}
public Acl getAcl() {
return null;
}
public Serializable getId() {
return null;
}
public Permission getPermission() {
return null;
}
public Sid getSid() {
return null;
}
public boolean isGranting() {
return false;
}
public void setAuditFailure(boolean auditFailure) {
this.auditFailure = auditFailure;
}
public void setAuditSuccess(boolean auditSuccess) {
this.auditSuccess = auditSuccess;
}
}
private class MockAccessControlEntry implements AccessControlEntry {
public Acl getAcl() {
return null;
}
public Serializable getId() {
return null;
}
public Permission getPermission() {
return null;
}
public Sid getSid() {
return null;
}
public boolean isGranting() {
return false;
}
}
}
@@ -22,7 +22,7 @@ import org.springframework.security.acls.Permission;
/**
* Tests classes associated with Permission.
* Tests BasePermission and CumulativePermission.
*
* @author Ben Alex
* @version $Id${date}
@@ -32,12 +32,6 @@ public class PermissionTests {
//~ Methods ========================================================================================================
@Test
public void basePermissionTest() {
Permission p = BasePermission.buildFromName("WRITE");
assertNotNull(p);
}
@Test
public void expectedIntegerValues() {
assertEquals(1, BasePermission.READ.getMask());
@@ -69,9 +63,9 @@ public class PermissionTests {
assertEquals("CumulativePermission[...............................R=1]",
new CumulativePermission().set(BasePermission.READ).toString());
System.out.println("A = " + new CumulativePermission().set(SpecialPermission.ENTER).set(BasePermission.ADMINISTRATION).toString());
assertEquals("CumulativePermission[..........................EA....=48]",
new CumulativePermission().set(SpecialPermission.ENTER).set(BasePermission.ADMINISTRATION).toString());
System.out.println("A = " + new CumulativePermission().set(BasePermission.ADMINISTRATION).toString());
assertEquals("CumulativePermission[...........................A....=16]",
new CumulativePermission().set(BasePermission.ADMINISTRATION).toString());
System.out.println("RA = "
+ new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString());
@@ -12,6 +12,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.acls.MutableAcl;
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
@@ -23,155 +24,155 @@ import org.springframework.security.acls.sid.GrantedAuthoritySid;
import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.util.AuthorityUtils;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public class AclPermissionInheritanceTests extends TestCase {
private JdbcMutableAclService aclService;
private JdbcTemplate jdbcTemplate;
private DriverManagerDataSource dataSource;
private DataSourceTransactionManager txManager;
private TransactionStatus txStatus;
private JdbcMutableAclService aclService;
private JdbcTemplate jdbcTemplate;
private DriverManagerDataSource dataSource;
private DataSourceTransactionManager txManager;
private TransactionStatus txStatus;
protected void setUp() throws Exception {
protected void setUp() throws Exception {
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:mem:permissiontest");
dataSource.setUsername("sa");
dataSource.setPassword("");
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:mem:permissiontest");
dataSource.setUsername("sa");
dataSource.setPassword("");
jdbcTemplate = new JdbcTemplate(dataSource);
txManager = new DataSourceTransactionManager();
txManager.setDataSource(dataSource);
txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
aclService = createAclService(dataSource);
Authentication auth = new UsernamePasswordAuthenticationToken("system", "secret",
AuthorityUtils.createAuthorityList("ROLE_IGNORED"));
jdbcTemplate = new JdbcTemplate(dataSource);
txManager = new DataSourceTransactionManager();
txManager.setDataSource(dataSource);
txStatus = txManager.getTransaction(new DefaultTransactionDefinition());
aclService = createAclService(dataSource);
Authentication auth = new UsernamePasswordAuthenticationToken(
"system", "secret", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_IGNORED")});
SecurityContextHolder.getContext().setAuthentication(auth);
}
}
protected void tearDown() throws Exception {
txManager.rollback(txStatus);
SecurityContextHolder.clearContext();
}
protected void tearDown() throws Exception {
txManager.rollback(txStatus);
SecurityContextHolder.clearContext();
}
public void test1() throws Exception {
public void test1() throws Exception {
createAclSchema(jdbcTemplate);
createAclSchema(jdbcTemplate);
ObjectIdentityImpl rootObject =
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
ObjectIdentityImpl rootObject =
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
MutableAcl parent = aclService.createAcl(rootObject);
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child.setParent(parent);
aclService.updateAcl(child);
MutableAcl parent = aclService.createAcl(rootObject);
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child.setParent(parent);
aclService.updateAcl(child);
parent = (AclImpl) aclService.readAclById(rootObject);
parent.insertAce(0, BasePermission.READ,
new PrincipalSid("john"), true);
aclService.updateAcl(parent);
parent = (AclImpl) aclService.readAclById(rootObject);
parent.insertAce(0, BasePermission.READ,
new PrincipalSid("john"), true);
aclService.updateAcl(parent);
parent = (AclImpl) aclService.readAclById(rootObject);
parent.insertAce(1, BasePermission.READ,
new PrincipalSid("joe"), true);
aclService.updateAcl(parent);
parent = (AclImpl) aclService.readAclById(rootObject);
parent.insertAce(1, BasePermission.READ,
new PrincipalSid("joe"), true);
aclService.updateAcl(parent);
child = (MutableAcl) aclService.readAclById(
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child = (MutableAcl) aclService.readAclById(
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
parent = (MutableAcl) child.getParentAcl();
parent = (MutableAcl) child.getParentAcl();
assertEquals("Fails because child has a stale reference to its parent", 2, parent.getEntries().size());
assertEquals(1, parent.getEntries().get(0).getPermission().getMask());
assertEquals(new PrincipalSid("john"), parent.getEntries().get(0).getSid());
assertEquals(1, parent.getEntries().get(1).getPermission().getMask());
assertEquals(new PrincipalSid("joe"), parent.getEntries().get(1).getSid());
assertEquals("Fails because child has a stale reference to its parent",
2, parent.getEntries().length);
assertEquals(1, parent.getEntries()[0].getPermission().getMask());
assertEquals(new PrincipalSid("john"), parent.getEntries()[0].getSid());
assertEquals(1, parent.getEntries()[1].getPermission().getMask());
assertEquals(new PrincipalSid("joe"), parent.getEntries()[1].getSid());
}
public void test2() throws Exception {
}
public void test2() throws Exception {
createAclSchema(jdbcTemplate);
createAclSchema(jdbcTemplate);
ObjectIdentityImpl rootObject =
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
ObjectIdentityImpl rootObject =
new ObjectIdentityImpl(TestDomainObject.class, new Long(1));
MutableAcl parent = aclService.createAcl(rootObject);
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child.setParent(parent);
aclService.updateAcl(child);
MutableAcl parent = aclService.createAcl(rootObject);
MutableAcl child = aclService.createAcl(new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child.setParent(parent);
aclService.updateAcl(child);
parent.insertAce(0, BasePermission.ADMINISTRATION,
new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
aclService.updateAcl(parent);
parent.insertAce(0, BasePermission.ADMINISTRATION,
new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), true);
aclService.updateAcl(parent);
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
aclService.updateAcl(parent);
parent.insertAce(1, BasePermission.DELETE, new PrincipalSid("terry"), true);
aclService.updateAcl(parent);
child = (MutableAcl) aclService.readAclById(
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
child = (MutableAcl) aclService.readAclById(
new ObjectIdentityImpl(TestDomainObject.class, new Long(2)));
parent = (MutableAcl) child.getParentAcl();
parent = (MutableAcl) child.getParentAcl();
assertEquals(2, parent.getEntries().size());
assertEquals(16, parent.getEntries().get(0).getPermission().getMask());
assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries().get(0).getSid());
assertEquals(8, parent.getEntries().get(1).getPermission().getMask());
assertEquals(new PrincipalSid("terry"), parent.getEntries().get(1).getSid());
assertEquals(2, parent.getEntries().length);
assertEquals(16, parent.getEntries()[0].getPermission().getMask());
assertEquals(new GrantedAuthoritySid("ROLE_ADMINISTRATOR"), parent.getEntries()[0].getSid());
assertEquals(8, parent.getEntries()[1].getPermission().getMask());
assertEquals(new PrincipalSid("terry"), parent.getEntries()[1].getSid());
}
}
private JdbcMutableAclService createAclService(DriverManagerDataSource ds)
throws IOException {
private JdbcMutableAclService createAclService(DriverManagerDataSource ds)
throws IOException {
GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl(
new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority});
GrantedAuthorityImpl adminAuthority = new GrantedAuthorityImpl("ROLE_ADMINISTRATOR");
AclAuthorizationStrategyImpl authStrategy = new AclAuthorizationStrategyImpl(
new GrantedAuthorityImpl[]{adminAuthority,adminAuthority,adminAuthority});
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.afterPropertiesSet();
CacheManager cacheManager = (CacheManager) ehCacheManagerFactoryBean.getObject();
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.afterPropertiesSet();
CacheManager cacheManager = (CacheManager) ehCacheManagerFactoryBean.getObject();
EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
ehCacheFactoryBean.setCacheName("aclAche");
ehCacheFactoryBean.setCacheManager(cacheManager);
ehCacheFactoryBean.afterPropertiesSet();
Ehcache ehCache = (Ehcache) ehCacheFactoryBean.getObject();
AclCache aclAche = new EhCacheBasedAclCache(ehCache);
BasicLookupStrategy lookupStrategy =
new BasicLookupStrategy(ds, aclAche, authStrategy, new ConsoleAuditLogger());
return new JdbcMutableAclService(ds,lookupStrategy, aclAche);
}
EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
ehCacheFactoryBean.setCacheName("aclAche");
ehCacheFactoryBean.setCacheManager(cacheManager);
ehCacheFactoryBean.afterPropertiesSet();
Ehcache ehCache = (Ehcache) ehCacheFactoryBean.getObject();
AclCache aclAche = new EhCacheBasedAclCache(ehCache);
BasicLookupStrategy lookupStrategy =
new BasicLookupStrategy(ds, aclAche, authStrategy, new ConsoleAuditLogger());
return new JdbcMutableAclService(ds,lookupStrategy, aclAche);
}
private void createAclSchema(JdbcTemplate jdbcTemplate) {
jdbcTemplate.execute("DROP TABLE ACL_ENTRY IF EXISTS;");
jdbcTemplate.execute("DROP TABLE ACL_OBJECT_IDENTITY IF EXISTS;");
jdbcTemplate.execute("DROP TABLE ACL_CLASS IF EXISTS");
jdbcTemplate.execute("DROP TABLE ACL_SID IF EXISTS");
jdbcTemplate.execute(
private void createAclSchema(JdbcTemplate jdbcTemplate) {
jdbcTemplate.execute("DROP TABLE ACL_ENTRY IF EXISTS;");
jdbcTemplate.execute("DROP TABLE ACL_OBJECT_IDENTITY IF EXISTS;");
jdbcTemplate.execute("DROP TABLE ACL_CLASS IF EXISTS");
jdbcTemplate.execute("DROP TABLE ACL_SID IF EXISTS");
jdbcTemplate.execute(
"CREATE TABLE ACL_SID(" +
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
"PRINCIPAL BOOLEAN NOT NULL," +
"SID VARCHAR_IGNORECASE(100) NOT NULL," +
"CONSTRAINT UNIQUE_UK_1 UNIQUE(SID,PRINCIPAL));");
jdbcTemplate.execute(
jdbcTemplate.execute(
"CREATE TABLE ACL_CLASS(" +
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
"CLASS VARCHAR_IGNORECASE(100) NOT NULL," +
"CONSTRAINT UNIQUE_UK_2 UNIQUE(CLASS));");
jdbcTemplate.execute(
jdbcTemplate.execute(
"CREATE TABLE ACL_OBJECT_IDENTITY(" +
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
"OBJECT_ID_CLASS BIGINT NOT NULL," +
@@ -183,7 +184,7 @@ public class AclPermissionInheritanceTests extends TestCase {
"CONSTRAINT FOREIGN_FK_1 FOREIGN KEY(PARENT_OBJECT)REFERENCES ACL_OBJECT_IDENTITY(ID)," +
"CONSTRAINT FOREIGN_FK_2 FOREIGN KEY(OBJECT_ID_CLASS)REFERENCES ACL_CLASS(ID)," +
"CONSTRAINT FOREIGN_FK_3 FOREIGN KEY(OWNER_SID)REFERENCES ACL_SID(ID));");
jdbcTemplate.execute(
jdbcTemplate.execute(
"CREATE TABLE ACL_ENTRY(" +
"ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 100) NOT NULL PRIMARY KEY," +
"ACL_OBJECT_IDENTITY BIGINT NOT NULL,ACE_ORDER INT NOT NULL,SID BIGINT NOT NULL," +
@@ -191,18 +192,18 @@ public class AclPermissionInheritanceTests extends TestCase {
"AUDIT_FAILURE BOOLEAN NOT NULL,CONSTRAINT UNIQUE_UK_4 UNIQUE(ACL_OBJECT_IDENTITY,ACE_ORDER)," +
"CONSTRAINT FOREIGN_FK_4 FOREIGN KEY(ACL_OBJECT_IDENTITY) REFERENCES ACL_OBJECT_IDENTITY(ID)," +
"CONSTRAINT FOREIGN_FK_5 FOREIGN KEY(SID) REFERENCES ACL_SID(ID));");
}
}
public static class TestDomainObject {
public static class TestDomainObject {
private Long id;
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
}
@@ -1,7 +1,5 @@
package org.springframework.security.acls.jdbc;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
@@ -37,15 +35,18 @@ import org.springframework.util.FileCopyUtils;
/**
* Tests {@link BasicLookupStrategy}
*
*
* @author Andrei Stefan
*/
public class BasicLookupStrategyTests {
//~ Instance fields ================================================================================================
private static JdbcTemplate jdbcTemplate;
private LookupStrategy strategy;
private static TestDataSource dataSource;
private static CacheManager cacheManager;
//~ Methods ========================================================================================================
@@ -119,25 +120,24 @@ public class BasicLookupStrategyTests {
public void testAclsRetrievalWithDefaultBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
// Deliberately use an integer for the child, to reproduce bug report in SEC-819
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(102));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@Test
public void testAclsRetrievalFromCacheOnly() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(100));
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
// Objects were put in cache
strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
// Let's empty the database to force acls retrieval from cache
emptyDatabase();
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
@@ -145,17 +145,17 @@ public class BasicLookupStrategyTests {
@Test
public void testAclsRetrievalWithCustomBatchSize() throws Exception {
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(101));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
// Set a batch size to allow multiple database queries in order to retrieve all acls
((BasicLookupStrategy) this.strategy).setBatchSize(1);
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid), null);
Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
checkEntries(topParentOid, middleParentOid, childOid, map);
}
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid,
Map<ObjectIdentity, Acl> map) throws Exception {
private void checkEntries(ObjectIdentity topParentOid, ObjectIdentity middleParentOid, ObjectIdentity childOid, Map map)
throws Exception {
Assert.assertEquals(3, map.size());
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
@@ -173,9 +173,9 @@ public class BasicLookupStrategyTests {
Assert.assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
// Check their ACEs were correctly retrieved
Assert.assertEquals(2, topParent.getEntries().size());
Assert.assertEquals(1, middleParent.getEntries().size());
Assert.assertEquals(1, child.getEntries().size());
Assert.assertEquals(2, topParent.getEntries().length);
Assert.assertEquals(1, middleParent.getEntries().length);
Assert.assertEquals(1, child.getEntries().length);
// Check object identities were correctly retrieved
Assert.assertEquals(topParentOid, topParent.getObjectIdentity());
@@ -186,54 +186,54 @@ public class BasicLookupStrategyTests {
Assert.assertTrue(topParent.isEntriesInheriting());
Assert.assertEquals(topParent.getId(), new Long(1));
Assert.assertEquals(topParent.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(topParent.getEntries().get(0).getId(), new Long(1));
Assert.assertEquals(topParent.getEntries().get(0).getPermission(), BasePermission.READ);
Assert.assertEquals(topParent.getEntries().get(0).getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isAuditSuccess());
Assert.assertTrue(((AuditableAccessControlEntry) topParent.getEntries().get(0)).isGranting());
Assert.assertEquals(topParent.getEntries()[0].getId(), new Long(1));
Assert.assertEquals(topParent.getEntries()[0].getPermission(), BasePermission.READ);
Assert.assertEquals(topParent.getEntries()[0].getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries()[0]).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries()[0]).isAuditSuccess());
Assert.assertTrue(((AuditableAccessControlEntry) topParent.getEntries()[0]).isGranting());
Assert.assertEquals(topParent.getEntries().get(1).getId(), new Long(2));
Assert.assertEquals(topParent.getEntries().get(1).getPermission(), BasePermission.WRITE);
Assert.assertEquals(topParent.getEntries().get(1).getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isAuditSuccess());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries().get(1)).isGranting());
Assert.assertEquals(topParent.getEntries()[1].getId(), new Long(2));
Assert.assertEquals(topParent.getEntries()[1].getPermission(), BasePermission.WRITE);
Assert.assertEquals(topParent.getEntries()[1].getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries()[1]).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries()[1]).isAuditSuccess());
Assert.assertFalse(((AuditableAccessControlEntry) topParent.getEntries()[1]).isGranting());
Assert.assertTrue(middleParent.isEntriesInheriting());
Assert.assertEquals(middleParent.getId(), new Long(2));
Assert.assertEquals(middleParent.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(middleParent.getEntries().get(0).getId(), new Long(3));
Assert.assertEquals(middleParent.getEntries().get(0).getPermission(), BasePermission.DELETE);
Assert.assertEquals(middleParent.getEntries().get(0).getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isAuditSuccess());
Assert.assertTrue(((AuditableAccessControlEntry) middleParent.getEntries().get(0)).isGranting());
Assert.assertEquals(middleParent.getEntries()[0].getId(), new Long(3));
Assert.assertEquals(middleParent.getEntries()[0].getPermission(), BasePermission.DELETE);
Assert.assertEquals(middleParent.getEntries()[0].getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries()[0]).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) middleParent.getEntries()[0]).isAuditSuccess());
Assert.assertTrue(((AuditableAccessControlEntry) middleParent.getEntries()[0]).isGranting());
Assert.assertTrue(child.isEntriesInheriting());
Assert.assertEquals(child.getId(), new Long(3));
Assert.assertEquals(child.getOwner(), new PrincipalSid("ben"));
Assert.assertEquals(child.getEntries().get(0).getId(), new Long(4));
Assert.assertEquals(child.getEntries().get(0).getPermission(), BasePermission.DELETE);
Assert.assertEquals(child.getEntries().get(0).getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries().get(0)).isAuditSuccess());
Assert.assertFalse((child.getEntries().get(0)).isGranting());
Assert.assertEquals(child.getEntries()[0].getId(), new Long(4));
Assert.assertEquals(child.getEntries()[0].getPermission(), BasePermission.DELETE);
Assert.assertEquals(child.getEntries()[0].getSid(), new PrincipalSid("ben"));
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries()[0]).isAuditFailure());
Assert.assertFalse(((AuditableAccessControlEntry) child.getEntries()[0]).isAuditSuccess());
Assert.assertFalse((child.getEntries()[0]).isGranting());
}
@Test
public void testAllParentsAreRetrievedWhenChildIsLoaded() throws Exception {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,2,103,1,1,1);";
jdbcTemplate.execute(query);
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(101));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
ObjectIdentity middleParent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(103));
// Retrieve the child
Map<ObjectIdentity, Acl> map = this.strategy.readAclsById(Arrays.asList(childOid), null);
Map map = this.strategy.readAclsById(new ObjectIdentity[] { childOid }, null);
// Check that the child and all its parents were retrieved
Assert.assertNotNull(map.get(childOid));
Assert.assertEquals(childOid, ((Acl) map.get(childOid)).getObjectIdentity());
@@ -241,7 +241,7 @@ public class BasicLookupStrategyTests {
Assert.assertEquals(middleParentOid, ((Acl) map.get(middleParentOid)).getObjectIdentity());
Assert.assertNotNull(map.get(topParentOid));
Assert.assertEquals(topParentOid, ((Acl) map.get(topParentOid)).getObjectIdentity());
// The second parent shouldn't have been retrieved
Assert.assertNull(map.get(middleParent2Oid));
}
@@ -260,16 +260,16 @@ public class BasicLookupStrategyTests {
ObjectIdentity grandParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(104));
ObjectIdentity parent1Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(105));
ObjectIdentity parent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(106));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(107));
ObjectIdentity parent2Oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(106));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(107));
// First lookup only child, thus populating the cache with grandParent, parent1 and child
List<Permission> checkPermission = Arrays.asList(BasePermission.READ);
List<Sid> sids = Arrays.asList((Sid)new PrincipalSid("ben"));
List<ObjectIdentity> childOids = Arrays.asList(childOid);
Permission[] checkPermission = new Permission[] { BasePermission.READ };
Sid[] sids = new Sid[] { new PrincipalSid("ben") };
ObjectIdentity[] childOids = new ObjectIdentity[] { childOid };
((BasicLookupStrategy) this.strategy).setBatchSize(6);
Map<ObjectIdentity, Acl> foundAcls = strategy.readAclsById(childOids, sids);
Map foundAcls = strategy.readAclsById(childOids, sids);
Acl foundChildAcl = (Acl) foundAcls.get(childOid);
Assert.assertNotNull(foundChildAcl);
@@ -277,7 +277,7 @@ public class BasicLookupStrategyTests {
// Search for object identities has to be done in the following order: last element have to be one which
// is already in cache and the element before it must not be stored in cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
ObjectIdentity[] allOids = new ObjectIdentity[] { grandParentOid, parent1Oid, parent2Oid, childOid };
try {
foundAcls = strategy.readAclsById(allOids, sids);
Assert.assertTrue(true);
@@ -289,5 +289,22 @@ public class BasicLookupStrategyTests {
Assert.assertNotNull(foundParent2Acl);
Assert.assertTrue(foundParent2Acl.isGranted(checkPermission, sids, false));
}
@Test
public void testAclsWithDifferentSerializableTypesAsObjectIdentities() throws Exception {
String query = "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (4,2,104,null,1,1);"
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (5,4,0,1,1,1,0,0)";
jdbcTemplate.execute(query);
}
ObjectIdentity oid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Integer(104));
Sid[] sids = new Sid[] { new PrincipalSid("ben") };
ObjectIdentity[] childOids = new ObjectIdentity[] { oid };
try {
Map foundAcls = strategy.readAclsById(childOids, sids);
Assert.fail("It should have thrown IllegalArgumentException");
} catch(IllegalArgumentException expected) {
Assert.assertTrue(true);
}
}
}
@@ -68,10 +68,11 @@ public class EhCacheBasedAclCacheTests {
return cache;
}
@Test(expected=IllegalArgumentException.class)
public void constructorRejectsNullParameters() throws Exception {
new EhCacheBasedAclCache(null);
AclCache aclCache = new EhCacheBasedAclCache(null);
fail("It should have thrown IllegalArgumentException");
}
@Test
@@ -124,7 +125,7 @@ public class EhCacheBasedAclCacheTests {
assertTrue(true);
}
}
// SEC-527
@Test
public void testDiskSerializationOfMutableAclObjectInstance() throws Exception {
@@ -137,20 +138,20 @@ public class EhCacheBasedAclCacheTests {
// Serialization test
File file = File.createTempFile("SEC_TEST", ".object");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(acl);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close();
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(acl);
oos.close();
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
MutableAcl retrieved = (MutableAcl) ois.readObject();
ois.close();
assertEquals(acl, retrieved);
Object retrieved1 = FieldUtils.getProtectedFieldValue("aclAuthorizationStrategy", retrieved);
assertEquals(null, retrieved1);
Object retrieved2 = FieldUtils.getProtectedFieldValue("auditLogger", retrieved);
assertEquals(null, retrieved2);
}
@@ -172,7 +173,7 @@ public class EhCacheBasedAclCacheTests {
assertEquals(2, cache.getDiskStoreSize());
assertTrue(cache.isElementOnDisk(acl.getObjectIdentity()));
assertFalse(cache.isElementInMemory(acl.getObjectIdentity()));
// Check we can get from cache the same objects we put in
assertEquals(myCache.getFromCache(new Long(1)), acl);
assertEquals(myCache.getFromCache(identity), acl);
@@ -207,7 +208,7 @@ public class EhCacheBasedAclCacheTests {
public void cacheOperationsAclWithParent() throws Exception {
Ehcache cache = getCache();
EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache);
Authentication auth = new TestingAuthenticationToken("user", "password", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_GENERAL") });
auth.setAuthenticated(true);
@@ -220,7 +221,7 @@ public class EhCacheBasedAclCacheTests {
new GrantedAuthorityImpl("ROLE_GENERAL") });
MutableAcl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
MutableAcl parentAcl = new AclImpl(identityParent, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
acl.setParent(parentAcl);
assertEquals(0, cache.getDiskStoreSize());
@@ -14,22 +14,11 @@
*/
package org.springframework.security.acls.jdbc;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.acls.AccessControlEntry;
import org.springframework.security.acls.Acl;
import org.springframework.security.acls.AlreadyExistsException;
@@ -44,10 +33,8 @@ import org.springframework.security.acls.sid.PrincipalSid;
import org.springframework.security.acls.sid.Sid;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.TestingAuthenticationToken;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;
/**
* Integration tests the ACL system using an in-memory database.
@@ -56,58 +43,67 @@ import org.springframework.transaction.annotation.Transactional;
* @author Andrei Stefan
* @version $Id:JdbcAclServiceTests.java 1754 2006-11-17 02:01:21Z benalex $
*/
@ContextConfiguration(locations={"/org/springframework/security/acls/jdbc/applicationContext-test.xml"})
public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContextTests {
public class JdbcAclServiceTests extends AbstractTransactionalDataSourceSpringContextTests {
//~ Constant fields ================================================================================================
private final Authentication auth = new TestingAuthenticationToken("ben", "ignored","ROLE_ADMINISTRATOR");
public static final String SELECT_ALL_CLASSES = "SELECT * FROM acl_class WHERE class = ?";
public static final String SELECT_ALL_OBJECT_IDENTITIES = "SELECT * FROM acl_object_identity";
public static final String SELECT_OBJECT_IDENTITY = "SELECT * FROM acl_object_identity WHERE object_id_identity = ?";
public static final String SELECT_ACL_ENTRY = "SELECT * FROM acl_entry, acl_object_identity WHERE " +
"acl_object_identity.id = acl_entry.acl_object_identity " +
"AND acl_object_identity.object_id_identity <= ?";
//~ Instance fields ================================================================================================
private final ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
private final ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
private final ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
@Autowired
private JdbcMutableAclService jdbcMutableAclService;
@Autowired
private AclCache aclCache;
@Autowired
private LookupStrategy lookupStrategy;
@Autowired
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
//~ Methods ========================================================================================================
@Before
public void createTables() throws IOException {
new DatabaseSeeder(dataSource, new ClassPathResource("org/springframework/security/acls/jdbc/testData.sql"));
protected String[] getConfigLocations() {
return new String[] {"classpath:org/springframework/security/acls/jdbc/applicationContext-test.xml"};
}
@After
public void clearContextAndData() throws Exception {
public void setJdbcMutableAclService(JdbcMutableAclService jdbcAclService) {
this.jdbcMutableAclService = jdbcAclService;
}
public void setAclCache(AclCache aclCache) {
this.aclCache = aclCache;
}
public void setLookupStrategy(LookupStrategy lookupStrategy) {
this.lookupStrategy = lookupStrategy;
}
protected void onTearDown() throws Exception {
super.onTearDown();
SecurityContextHolder.clearContext();
jdbcTemplate.execute("drop table acl_entry");
jdbcTemplate.execute("drop table acl_object_identity");
jdbcTemplate.execute("drop table acl_class");
jdbcTemplate.execute("drop table acl_sid");
}
@Test
@Transactional
@Rollback
public void testLifecycle() {
setComplete();
Authentication auth = new TestingAuthenticationToken("ben", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADMINISTRATOR")});
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
MutableAcl topParent = jdbcMutableAclService.createAcl(topParentOid);
MutableAcl middleParent = jdbcMutableAclService.createAcl(middleParentOid);
MutableAcl child = jdbcMutableAclService.createAcl(childOid);
// Specify the inheritance hierarchy
// Specify the inheritence hierarchy
middleParent.setParent(topParent);
child.setParent(middleParent);
@@ -117,13 +113,13 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
middleParent.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), true);
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), false);
// Explicitly save the changed ACL
// Explictly save the changed ACL
jdbcMutableAclService.updateAcl(topParent);
jdbcMutableAclService.updateAcl(middleParent);
jdbcMutableAclService.updateAcl(child);
// Let's check if we can read them back correctly
Map<ObjectIdentity, Acl> map = jdbcMutableAclService.readAclsById(Arrays.asList(topParentOid, middleParentOid, childOid));
Map map = jdbcMutableAclService.readAclsById(new ObjectIdentity[] {topParentOid, middleParentOid, childOid});
assertEquals(3, map.size());
// Replace our current objects with their retrieved versions
@@ -142,33 +138,27 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
// Check their ACEs were correctly persisted
assertEquals(2, topParent.getEntries().size());
assertEquals(1, middleParent.getEntries().size());
assertEquals(1, child.getEntries().size());
assertEquals(2, topParent.getEntries().length);
assertEquals(1, middleParent.getEntries().length);
assertEquals(1, child.getEntries().length);
// Check the retrieved rights are correct
List<Permission> read = Arrays.asList(BasePermission.READ);
List<Permission> write = Arrays.asList(BasePermission.WRITE);
List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid)new PrincipalSid(auth));
assertTrue(topParent.isGranted(read, pSid, false));
assertFalse(topParent.isGranted(write, pSid, false));
assertTrue(middleParent.isGranted(delete, pSid, false));
assertFalse(child.isGranted(delete, pSid, false));
assertTrue(topParent.isGranted(new Permission[] {BasePermission.READ}, new Sid[] {new PrincipalSid(auth)}, false));
assertFalse(topParent.isGranted(new Permission[] {BasePermission.WRITE}, new Sid[] {new PrincipalSid(auth)}, false));
assertTrue(middleParent.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, false));
assertFalse(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, false));
try {
child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false);
child.isGranted(new Permission[] {BasePermission.ADMINISTRATION}, new Sid[] {new PrincipalSid(auth)}, false);
fail("Should have thrown NotFoundException");
} catch (NotFoundException expected) {
assertTrue(true);
}
// Now check the inherited rights (when not explicitly overridden) also look OK
assertTrue(child.isGranted(read, pSid, false));
assertFalse(child.isGranted(write, pSid, false));
assertFalse(child.isGranted(delete, pSid, false));
assertTrue(child.isGranted(new Permission[] {BasePermission.READ}, new Sid[] {new PrincipalSid(auth)}, false));
assertFalse(child.isGranted(new Permission[] {BasePermission.WRITE}, new Sid[] {new PrincipalSid(auth)}, false));
assertFalse(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, false));
// Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false);
@@ -177,17 +167,17 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
assertFalse(child.isEntriesInheriting());
// Check the child permissions no longer inherit
assertFalse(child.isGranted(delete, pSid, true));
assertFalse(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, true));
try {
child.isGranted(read, pSid, true);
child.isGranted(new Permission[] {BasePermission.READ}, new Sid[] {new PrincipalSid(auth)}, true);
fail("Should have thrown NotFoundException");
} catch (NotFoundException expected) {
assertTrue(true);
}
try {
child.isGranted(write, pSid, true);
child.isGranted(new Permission[] {BasePermission.WRITE}, new Sid[] {new PrincipalSid(auth)}, true);
fail("Should have thrown NotFoundException");
} catch (NotFoundException expected) {
assertTrue(true);
@@ -202,19 +192,19 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
// Save the changed child
jdbcMutableAclService.updateAcl(child);
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
assertEquals(3, child.getEntries().size());
assertEquals(3, child.getEntries().length);
// Output permissions
for (int i = 0; i < child.getEntries().size(); i++) {
System.out.println(child.getEntries().get(i));
for (int i = 0; i < child.getEntries().length; i++) {
System.out.println(child.getEntries()[i]);
}
// Check the permissions are as they should be
assertFalse(child.isGranted(delete, pSid, true)); // as earlier permission overrode
assertTrue(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true));
assertFalse(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, true)); // as earlier permission overrode
assertTrue(child.isGranted(new Permission[] {BasePermission.CREATE}, new Sid[] {new PrincipalSid(auth)}, true));
// Now check the first ACE (index 0) really is DELETE for our Sid and is non-granting
AccessControlEntry entry = child.getEntries().get(0);
AccessControlEntry entry = child.getEntries()[0];
assertEquals(BasePermission.DELETE.getMask(), entry.getPermission().getMask());
assertEquals(new PrincipalSid(auth), entry.getSid());
assertFalse(entry.isGranting());
@@ -225,160 +215,142 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
// Save and check it worked
child = jdbcMutableAclService.updateAcl(child);
assertEquals(2, child.getEntries().size());
assertTrue(child.isGranted(delete, pSid, false));
assertEquals(2, child.getEntries().length);
assertTrue(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, false));
SecurityContextHolder.clearContext();
}
/**
* Test method that demonstrates eviction failure from cache - SEC-676
*/
@Test
@Transactional
@Rollback
public void testDeleteAclAlsoDeletesChildren() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
jdbcMutableAclService.createAcl(topParentOid);
MutableAcl middleParent = jdbcMutableAclService.createAcl(middleParentOid);
MutableAcl child = jdbcMutableAclService.createAcl(childOid);
child.setParent(middleParent);
jdbcMutableAclService.updateAcl(middleParent);
jdbcMutableAclService.updateAcl(child);
// Check the childOid really is a child of middleParentOid
Acl childAcl = jdbcMutableAclService.readAclById(childOid);
assertEquals(middleParentOid, childAcl.getParentAcl().getObjectIdentity());
// Delete the mid-parent and test if the child was deleted, as well
jdbcMutableAclService.deleteAcl(middleParentOid, true);
try {
jdbcMutableAclService.readAclById(middleParentOid);
Acl acl = jdbcMutableAclService.readAclById(middleParentOid);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
try {
jdbcMutableAclService.readAclById(childOid);
Acl acl = jdbcMutableAclService.readAclById(childOid);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
assertTrue(true);
}
Acl acl = jdbcMutableAclService.readAclById(topParentOid);
assertNotNull(acl);
assertEquals(((MutableAcl) acl).getObjectIdentity(), topParentOid);
}
@Test
public void testConstructorRejectsNullParameters() throws Exception {
try {
new JdbcMutableAclService(null, lookupStrategy, aclCache);
JdbcAclService service = new JdbcMutableAclService(null, lookupStrategy, aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new JdbcMutableAclService(dataSource, null, aclCache);
JdbcAclService service = new JdbcMutableAclService(this.getJdbcTemplate().getDataSource(), null, aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new JdbcMutableAclService(dataSource, lookupStrategy, null);
JdbcAclService service = new JdbcMutableAclService(this.getJdbcTemplate().getDataSource(), lookupStrategy, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@Test
public void testCreateAclRejectsNullParameter() throws Exception {
try {
jdbcMutableAclService.createAcl(null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@Test
@Transactional
@Rollback
public void testCreateAclForADuplicateDomainObject() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
ObjectIdentity duplicateOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time
try {
jdbcMutableAclService.createAcl(duplicateOid);
fail("It should have thrown AlreadyExistsException");
}
catch (AlreadyExistsException expected) {
assertTrue(true);
}
}
@Test
@Transactional
@Rollback
public void testDeleteAclRejectsNullParameters() throws Exception {
try {
jdbcMutableAclService.deleteAcl(null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
@Test
@Transactional
@Rollback
public void testDeleteAclWithChildrenThrowsException() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl parent = jdbcMutableAclService.createAcl(topParentOid);
MutableAcl child = jdbcMutableAclService.createAcl(middleParentOid);
// Specify the inheritance hierarchy
child.setParent(parent);
jdbcMutableAclService.updateAcl(child);
try {
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK checking in the class, not database
jdbcMutableAclService.deleteAcl(topParentOid, false);
fail("It should have thrown ChildrenExistException");
}
catch (ChildrenExistException expected) {
assertTrue(true);
} finally {
jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the default
}
}
@Test
@Transactional
@Rollback
public void testDeleteAclRemovesRowsFromDatabase() throws Exception {
Authentication auth = new TestingAuthenticationToken("ben", "ignored",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADMINISTRATOR")});
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
MutableAcl child = jdbcMutableAclService.createAcl(childOid);
child.insertAce(0, BasePermission.DELETE, new PrincipalSid(auth), false);
jdbcMutableAclService.updateAcl(child);
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
ObjectIdentity middleParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
// Remove the child and check all related database rows were removed accordingly
jdbcMutableAclService.deleteAcl(childOid, false);
assertEquals(1, jdbcTemplate.queryForList(SELECT_ALL_CLASSES, new Object[] {"org.springframework.security.TargetObject"} ).size());
assertEquals(0, jdbcTemplate.queryForList("select * from acl_object_identity").size());
assertEquals(0, jdbcTemplate.queryForList("select * from acl_entry").size());
assertEquals(1, getJdbcTemplate().queryForList(SELECT_ALL_CLASSES, new Object[] {"org.springframework.security.TargetObject"} ).size());
assertEquals(0, getJdbcTemplate().queryForList(SELECT_OBJECT_IDENTITY, new Object[] {new Long(102)}).size());
assertEquals(2, getJdbcTemplate().queryForList(SELECT_ALL_OBJECT_IDENTITIES).size());
assertEquals(3, getJdbcTemplate().queryForList(SELECT_ACL_ENTRY, new Object[] {new Long(103)} ).size());
// Check the cache
assertNull(aclCache.getFromCache(childOid));
assertNull(aclCache.getFromCache(new Long(102)));
}
/**
* SEC-655
*/
@@ -393,7 +365,7 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
MutableAcl parent = jdbcMutableAclService.createAcl(parentOid);
MutableAcl child = jdbcMutableAclService.createAcl(childOid);
child.setParent(parent);
jdbcMutableAclService.updateAcl(child);
@@ -408,13 +380,13 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
parent = (MutableAcl) child.getParentAcl();
assertEquals("Fails because child has a stale reference to its parent", 2, parent.getEntries().size());
assertEquals("Fails because child has a stale reference to its parent", 2, parent.getEntries().length);
assertEquals(1, parent.getEntries()[0].getPermission().getMask());
assertEquals(new PrincipalSid("ben"), parent.getEntries()[0].getSid());
assertEquals(1, parent.getEntries()[1].getPermission().getMask());
assertEquals(new PrincipalSid("scott"), parent.getEntries()[1].getSid());
}*/
/* public void testCumulativePermissions() {
setComplete();
Authentication auth = new TestingAuthenticationToken("ben", "ignored", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADMINISTRATOR")});
@@ -428,14 +400,14 @@ public class JdbcAclServiceTests extends AbstractTransactionalJUnit4SpringContex
CumulativePermission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION);
assertEquals(17, cm.getMask());
topParent.insertAce(null, cm, new PrincipalSid(auth), true);
assertEquals(1, topParent.getEntries().size());
assertEquals(1, topParent.getEntries().length);
// Explictly save the changed ACL
topParent = jdbcMutableAclService.updateAcl(topParent);
// Check the mask was retrieved correctly
assertEquals(17, topParent.getEntries()[0].getPermission().getMask());
assertTrue(topParent.isGranted(new Permission[] {cm}, pSid, true));
assertTrue(topParent.isGranted(new Permission[] {cm}, new Sid[] {new PrincipalSid(auth)}, true));
SecurityContextHolder.clearContext();
}
@@ -1,178 +1,204 @@
package org.springframework.security.acls.objectidentity;
import static org.junit.Assert.*;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.security.acls.IdentityUnavailableException;
/**
* Tests for {@link ObjectIdentityImpl}.
*
*
* @author Andrei Stefan
*/
public class ObjectIdentityTests {
public class ObjectIdentityTests extends TestCase {
//~ Methods ========================================================================================================
private static final String DOMAIN_CLASS =
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject";
public void testConstructorsRequiredFields() throws Exception {
// Check one-argument constructor required field
try {
ObjectIdentity obj = new ObjectIdentityImpl(null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
//~ Methods ========================================================================================================
// Check String-Serializable constructor required field
try {
ObjectIdentity obj = new ObjectIdentityImpl("", new Long(1));
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
@Test
public void constructorsRespectRequiredFields() throws Exception {
// Check one-argument constructor required field
try {
new ObjectIdentityImpl(null);
fail("It should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
// Check Serializable parameter is not null
try {
ObjectIdentity obj = new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
// Check String-Serializable constructor required field
try {
new ObjectIdentityImpl("", new Long(1));
fail("It should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
}
// The correct way of using String-Serializable constructor
try {
ObjectIdentity obj = new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject",
new Long(1));
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
// Check Serializable parameter is not null
try {
new ObjectIdentityImpl(DOMAIN_CLASS, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check the Class-Serializable constructor
try {
ObjectIdentity obj = new ObjectIdentityImpl(MockIdDomainObject.class, null);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
}
// The correct way of using String-Serializable constructor
try {
new ObjectIdentityImpl(DOMAIN_CLASS, new Long(1));
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
public void testGetIdMethodConstraints() throws Exception {
// Check the getId() method is present
try {
ObjectIdentity obj = new ObjectIdentityImpl("A_STRING_OBJECT");
Assert.fail("It should have thrown IdentityUnavailableException");
}
catch (IdentityUnavailableException expected) {
Assert.assertTrue(true);
}
// Check the Class-Serializable constructor
try {
new ObjectIdentityImpl(MockIdDomainObject.class, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
// getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject();
try {
ObjectIdentity obj = new ObjectIdentityImpl(mockId);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
}
}
// getId() should return a Serializable object
mockId.setId(new MockIdDomainObject());
try {
ObjectIdentity obj = new ObjectIdentityImpl(mockId);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
Assert.assertTrue(true);
}
@Test
public void testGetIdMethodConstraints() throws Exception {
// Check the getId() method is present
try {
new ObjectIdentityImpl("A_STRING_OBJECT");
fail("It should have thrown IdentityUnavailableException");
}
catch (IdentityUnavailableException expected) {
// getId() should return a Serializable object
mockId.setId(new Long(100));
try {
ObjectIdentity obj = new ObjectIdentityImpl(mockId);
Assert.assertTrue(true);
}
catch (IllegalArgumentException expected) {
Assert.fail("It shouldn't have thrown IllegalArgumentException");
}
}
}
public void testConstructorInvalidClassParameter() throws Exception {
try {
ObjectIdentity obj = new ObjectIdentityImpl("not.a.Class", new Long(1));
}
catch (IllegalStateException expected) {
return;
}
Assert.fail("It should have thrown IllegalStateException");
}
// getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject();
try {
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
public void testEquals() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1));
MockIdDomainObject mockObj = new MockIdDomainObject();
mockObj.setId(new Long(1));
}
// getId() should return a Serializable object
mockId.setId(new MockIdDomainObject());
try {
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// getId() should return a Serializable object
mockId.setId(new Long(100));
try {
new ObjectIdentityImpl(mockId);
}
catch (IllegalArgumentException expected) {
}
}
@Test(expected=IllegalStateException.class)
public void testConstructorInvalidClassParameter() throws Exception {
new ObjectIdentityImpl("not.a.Class", new Long(1));
}
@Test
public void testEquals() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, new Long(1));
MockIdDomainObject mockObj = new MockIdDomainObject();
mockObj.setId(new Long(1));
String string = "SOME_STRING";
assertNotSame(obj, string);
assertFalse(obj.equals(null));
assertFalse(obj.equals("DIFFERENT_OBJECT_TYPE"));
assertFalse(obj.equals(new ObjectIdentityImpl(DOMAIN_CLASS,new Long(2))));
assertFalse(obj.equals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockOtherIdDomainObject",
new Long(1))));
assertEquals(new ObjectIdentityImpl(DOMAIN_CLASS,new Long(1)), obj);
assertEquals(obj, new ObjectIdentityImpl(mockObj));
}
@Test
public void testHashCode() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, new Long(1));
assertEquals(new ObjectIdentityImpl(DOMAIN_CLASS, new Long(1)).hashCode(), obj.hashCode());
assertTrue(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockOtherIdDomainObject",
new Long(1)).hashCode() != obj.hashCode());
assertTrue(new ObjectIdentityImpl(DOMAIN_CLASS, new Long(2)).hashCode() != obj.hashCode());
}
String string = "SOME_STRING";
Assert.assertNotSame(obj, string);
Assert.assertTrue(!obj.equals(null));
Assert.assertTrue(!obj.equals("DIFFERENT_OBJECT_TYPE"));
Assert.assertTrue(!obj
.equals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject",
new Long(2))));
Assert.assertTrue(!obj.equals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockOtherIdDomainObject",
new Long(1))));
Assert.assertEquals(
new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject",
new Long(1)), obj);
Assert.assertTrue(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1))
.equals(obj));
Assert.assertTrue(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1))
.equals(new ObjectIdentityImpl(mockObj)));
}
public void testHashCode() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1));
Assert.assertEquals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1))
.hashCode(), obj.hashCode());
Assert.assertTrue(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockOtherIdDomainObject",
new Long(1)).hashCode() != obj.hashCode());
Assert.assertTrue(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(2))
.hashCode() != obj.hashCode());
}
/* public void testHashCodeDifferentSerializableTypes() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(
DOMAIN_CLASS, new Long(1));
assertEquals(new ObjectIdentityImpl(
DOMAIN_CLASS, "1")
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1));
Assert.assertEquals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", "1")
.hashCode(), obj.hashCode());
assertEquals(new ObjectIdentityImpl(
DOMAIN_CLASS,
Assert.assertEquals(new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject",
new Integer(1)).hashCode(), obj.hashCode());
}*/
public void testGetters() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(
"org.springframework.security.acls.objectidentity.ObjectIdentityTests$MockIdDomainObject", new Long(1));
Assert.assertEquals(new Long(1), obj.getIdentifier());
Assert.assertEquals(MockIdDomainObject.class, obj.getJavaType());
}
@Test
public void testGetters() throws Exception {
ObjectIdentity obj = new ObjectIdentityImpl(DOMAIN_CLASS, new Long(1));
assertEquals(new Long(1), obj.getIdentifier());
assertEquals(MockIdDomainObject.class, obj.getJavaType());
}
//~ Inner Classes ==================================================================================================
private class MockIdDomainObject {
private Object id;
//~ Inner Classes ==================================================================================================
public Object getId() {
return id;
}
private class MockIdDomainObject {
private Object id;
public void setId(Object id) {
this.id = id;
}
}
public Object getId() {
return id;
}
private class MockOtherIdDomainObject {
private Object id;
public void setId(Object id) {
this.id = id;
}
}
public Object getId() {
return id;
}
@SuppressWarnings("unused")
private class MockOtherIdDomainObject {
private Object id;
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
}
public void setId(Object id) {
this.id = id;
}
}
}
@@ -1,16 +1,16 @@
package org.springframework.security.acls.sid;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.TestingAuthenticationToken;
/**
* Tests for {@link SidRetrievalStrategyImpl}
*
*
* @author Andrei Stefan
*/
public class SidRetrievalStrategyTests extends TestCase {
@@ -18,22 +18,23 @@ public class SidRetrievalStrategyTests extends TestCase {
//~ Methods ========================================================================================================
public void testSidsRetrieval() throws Exception {
Authentication authentication = new TestingAuthenticationToken("scott", "password", "ROLE_1", "ROLE_2", "ROLE_3");
Authentication authentication = new TestingAuthenticationToken("scott", "password", new GrantedAuthority[] {
new GrantedAuthorityImpl("ROLE_1"), new GrantedAuthorityImpl("ROLE_2"), new GrantedAuthorityImpl("ROLE_3") });
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
List<Sid> sids = retrStrategy.getSids(authentication);
Sid[] sids = retrStrategy.getSids(authentication);
assertNotNull(sids);
assertEquals(4, sids.size());
assertNotNull(sids.get(0));
assertTrue(sids.get(0) instanceof PrincipalSid);
assertEquals(4, sids.length);
assertNotNull(sids[0]);
assertTrue(sids[0] instanceof PrincipalSid);
for (int i = 1; i < sids.size(); i++) {
assertTrue(sids.get(i) instanceof GrantedAuthoritySid);
for (int i = 1; i < sids.length; i++) {
assertTrue(sids[i] instanceof GrantedAuthoritySid);
}
Assert.assertEquals("scott", ((PrincipalSid) sids.get(0)).getPrincipal());
Assert.assertEquals("ROLE_1", ((GrantedAuthoritySid) sids.get(1)).getGrantedAuthority());
Assert.assertEquals("ROLE_2", ((GrantedAuthoritySid) sids.get(2)).getGrantedAuthority());
Assert.assertEquals("ROLE_3", ((GrantedAuthoritySid) sids.get(3)).getGrantedAuthority());
Assert.assertEquals("scott", ((PrincipalSid) sids[0]).getPrincipal());
Assert.assertEquals("ROLE_1", ((GrantedAuthoritySid) sids[1]).getGrantedAuthority());
Assert.assertEquals("ROLE_2", ((GrantedAuthoritySid) sids[2]).getGrantedAuthority());
Assert.assertEquals("ROLE_3", ((GrantedAuthoritySid) sids[3]).getGrantedAuthority());
}
}
@@ -19,7 +19,7 @@ public class SidTests extends TestCase {
// Check one String-argument constructor
try {
String string = null;
new PrincipalSid(string);
Sid principalSid = new PrincipalSid(string);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -27,7 +27,7 @@ public class SidTests extends TestCase {
}
try {
new PrincipalSid("");
Sid principalSid = new PrincipalSid("");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -35,7 +35,7 @@ public class SidTests extends TestCase {
}
try {
new PrincipalSid("johndoe");
Sid principalSid = new PrincipalSid("johndoe");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
@@ -45,7 +45,7 @@ public class SidTests extends TestCase {
// Check one Authentication-argument constructor
try {
Authentication authentication = null;
new PrincipalSid(authentication);
Sid principalSid = new PrincipalSid(authentication);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -53,8 +53,8 @@ public class SidTests extends TestCase {
}
try {
Authentication authentication = new TestingAuthenticationToken(null, "password");
new PrincipalSid(authentication);
Authentication authentication = new TestingAuthenticationToken(null, "password", null);
Sid principalSid = new PrincipalSid(authentication);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -62,8 +62,8 @@ public class SidTests extends TestCase {
}
try {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
new PrincipalSid(authentication);
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
Sid principalSid = new PrincipalSid(authentication);
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
@@ -75,7 +75,7 @@ public class SidTests extends TestCase {
// Check one String-argument constructor
try {
String string = null;
new GrantedAuthoritySid(string);
Sid gaSid = new GrantedAuthoritySid(string);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -83,7 +83,7 @@ public class SidTests extends TestCase {
}
try {
new GrantedAuthoritySid("");
Sid gaSid = new GrantedAuthoritySid("");
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -91,7 +91,7 @@ public class SidTests extends TestCase {
}
try {
new GrantedAuthoritySid("ROLE_TEST");
Sid gaSid = new GrantedAuthoritySid("ROLE_TEST");
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
@@ -101,7 +101,7 @@ public class SidTests extends TestCase {
// Check one GrantedAuthority-argument constructor
try {
GrantedAuthority ga = null;
new GrantedAuthoritySid(ga);
Sid gaSid = new GrantedAuthoritySid(ga);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -110,7 +110,7 @@ public class SidTests extends TestCase {
try {
GrantedAuthority ga = new GrantedAuthorityImpl(null);
new GrantedAuthoritySid(ga);
Sid gaSid = new GrantedAuthoritySid(ga);
Assert.fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
@@ -119,7 +119,7 @@ public class SidTests extends TestCase {
try {
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
new GrantedAuthoritySid(ga);
Sid gaSid = new GrantedAuthoritySid(ga);
Assert.assertTrue(true);
}
catch (IllegalArgumentException notExpected) {
@@ -128,15 +128,15 @@ public class SidTests extends TestCase {
}
public void testPrincipalSidEquals() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
Sid principalSid = new PrincipalSid(authentication);
Assert.assertFalse(principalSid.equals(null));
Assert.assertFalse(principalSid.equals("DIFFERENT_TYPE_OBJECT"));
Assert.assertTrue(principalSid.equals(principalSid));
Assert.assertTrue(principalSid.equals(new PrincipalSid(authentication)));
Assert.assertTrue(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("johndoe", null))));
Assert.assertFalse(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("scott", null))));
Assert.assertTrue(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("johndoe", null, null))));
Assert.assertFalse(principalSid.equals(new PrincipalSid(new TestingAuthenticationToken("scott", null, null))));
Assert.assertTrue(principalSid.equals(new PrincipalSid("johndoe")));
Assert.assertFalse(principalSid.equals(new PrincipalSid("scott")));
}
@@ -156,13 +156,14 @@ public class SidTests extends TestCase {
}
public void testPrincipalSidHashCode() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
Sid principalSid = new PrincipalSid(authentication);
Assert.assertTrue(principalSid.hashCode() == new String("johndoe").hashCode());
Assert.assertTrue(principalSid.hashCode() == new PrincipalSid("johndoe").hashCode());
Assert.assertTrue(principalSid.hashCode() != new PrincipalSid("scott").hashCode());
Assert.assertTrue(principalSid.hashCode() != new PrincipalSid(new TestingAuthenticationToken("scott", "password")).hashCode());
Assert.assertTrue(principalSid.hashCode() != new PrincipalSid(new TestingAuthenticationToken("scott", "password",
null)).hashCode());
}
public void testGrantedAuthoritySidHashCode() throws Exception {
@@ -176,7 +177,7 @@ public class SidTests extends TestCase {
}
public void testGetters() throws Exception {
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
PrincipalSid principalSid = new PrincipalSid(authentication);
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
+1
View File
@@ -0,0 +1 @@
target
+5
View File
@@ -0,0 +1,5 @@
target
.settings
.classpath
.project
.wtpmodules
+22
View File
@@ -0,0 +1,22 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-catalina</artifactId>
<name>Spring Security - Catalina adapter</name>
<dependencies>
<dependency>
<groupId>tomcat</groupId>
<artifactId>catalina</artifactId>
<version>4.1.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,236 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.catalina;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.catalina.Container;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.realm.RealmBase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import java.io.File;
import java.security.Principal;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* Adapter to enable Catalina (Tomcat) to authenticate via the Spring Security.<p>Returns a {@link
* PrincipalSpringSecurityUserToken} to Catalina's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:CatalinaSpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class CatalinaSpringSecurityUserRealm extends RealmBase {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(CatalinaSpringSecurityUserRealm.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private Container container;
private String appContextLocation;
private String key;
protected final String name = "CatalinaSpringUserRealm / $Id:CatalinaSpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $";
//~ Methods ========================================================================================================
public Principal authenticate(String username, String credentials) {
if (username == null) {
return null;
}
if (credentials == null) {
credentials = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username, credentials);
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new PrincipalSpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities(), response.getPrincipal());
}
public Principal authenticate(String username, byte[] credentials) {
return authenticate(username, new String(credentials));
}
/**
* Not supported, returns null
*
* @param username DOCUMENT ME!
* @param digest DOCUMENT ME!
* @param nonce DOCUMENT ME!
* @param nc DOCUMENT ME!
* @param cnonce DOCUMENT ME!
* @param qop DOCUMENT ME!
* @param realm DOCUMENT ME!
* @param md5a2 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public java.security.Principal authenticate(java.lang.String username, java.lang.String digest,
java.lang.String nonce, java.lang.String nc, java.lang.String cnonce, java.lang.String qop,
java.lang.String realm, java.lang.String md5a2) {
return null;
}
/**
* Not supported, returns null
*
* @param x509Certificates DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public Principal authenticate(X509Certificate[] x509Certificates) {
return null;
}
public String getAppContextLocation() {
return appContextLocation;
}
public String getKey() {
return key;
}
protected String getName() {
return this.name;
}
/**
* Always returns null (we override authenticate methods)
*
* @param arg0 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String getPassword(String arg0) {
return null;
}
/**
* Always returns null (we override authenticate methods)
*
* @param arg0 DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected Principal getPrincipal(String arg0) {
return null;
}
public boolean hasRole(Principal principal, String role) {
if ((principal == null) || (role == null)) {
return false;
}
if (!(principal instanceof PrincipalSpringSecurityUserToken)) {
logger.warn("Expected passed principal to be of type PrincipalSpringSecurityUserToken but was "
+ principal.getClass().getName());
return false;
}
PrincipalSpringSecurityUserToken test = (PrincipalSpringSecurityUserToken) principal;
return test.isUserInRole(role);
}
public void setAppContextLocation(String appContextLocation) {
this.appContextLocation = appContextLocation;
}
public void setKey(String key) {
this.key = key;
}
/**
* Provides the method that Catalina will use to start the container.
*
* @throws LifecycleException if a problem is detected
*/
public void start() throws LifecycleException {
this.start(true);
}
private void start(boolean startParent) throws LifecycleException {
if (startParent) {
super.start();
}
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new LifecycleException("appContextLocation must be defined");
}
if ((key == null) || "".equals(key)) {
throw new LifecycleException("key must be defined");
}
File xml = new File(System.getProperty("catalina.base"), appContextLocation);
if (!xml.exists()) {
throw new LifecycleException("appContextLocation does not seem to exist in " + xml.toString());
}
FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + xml.getAbsolutePath());
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
logger.info("CatalinaSpringSecurityUserRealm Started");
}
/**
* Provides a method to load the container adapter without delegating to the superclass, which cannot
* operate outside the Catalina container.
*
* @throws LifecycleException if a problem is detected
*/
protected void startForTest() throws LifecycleException {
this.start(false);
}
}
@@ -0,0 +1,7 @@
<html>
<body>
Adapter to Catalina web container (Tomcat).
<p>
</body>
</html>
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
* Copyright 2004 Acegi Technology Pty Limited
*
* 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.
*
*
* $Id$
-->
<beans>
<!-- Data access object which stores authentication information -->
<bean id="inMemoryDaoImpl" class="org.springframework.security.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
rod=koala,ROLE_TELLER,ROLE_SUPERVISOR
dianne=emu,ROLE_TELLER
scott=wombat,ROLE_TELLER
peter=opal,disabled,ROLE_TELLER
</value>
</property>
</bean>
<!-- The authentication manager is deliberately missing in order to test error detection -->
</beans>
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
* Copyright 2004 Acegi Technology Pty Limited
*
* 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.
*
*
* $Id$
-->
<beans>
<!-- Data access object which stores authentication information -->
<bean id="inMemoryDaoImpl" class="org.springframework.security.userdetails.memory.InMemoryDaoImpl">
<property name="userMap">
<value>
rod=koala,ROLE_TELLER,ROLE_SUPERVISOR
dianne=emu,ROLE_TELLER
scott=wombat,ROLE_TELLER
peter=opal,disabled,ROLE_TELLER
</value>
</property>
</bean>
<!-- Authentication provider that queries our data access object -->
<bean id="daoAuthenticationProvider" class="org.springframework.security.providers.dao.DaoAuthenticationProvider">
<property name="userDetailsService"><ref bean="inMemoryDaoImpl"/></property>
<property name="forcePrincipalAsString"><value>true</value></property>
</bean>
<!-- The authentication manager that iterates through our only authentication provider -->
<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager">
<property name="providers">
<list>
<ref bean="daoAuthenticationProvider"/>
</list>
</property>
</bean>
</beans>
@@ -0,0 +1,275 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.catalina;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.apache.catalina.LifecycleException;
import java.io.File;
import java.net.URL;
import java.security.Principal;
/**
* Tests {@link CatalinaSpringSecurityUserRealm}.
*
* @author Ben Alex
* @version $Id:CatalinaSpringSecurityUserRealmTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class CatalinaSpringSecurityUserRealmTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public CatalinaSpringSecurityUserRealmTests() {
super();
}
public CatalinaSpringSecurityUserRealmTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CatalinaSpringSecurityUserRealmTests.class);
}
private CatalinaSpringSecurityUserRealm makeAdapter(String fileName)
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
URL url = Thread.currentThread().getContextClassLoader().getResource("org/springframework/security/adapters/" + fileName);
if (url == null) {
throw new Exception("Could not find " + fileName + " - cannot continue");
}
File file = new File(url.getFile());
System.setProperty("catalina.base", file.getParentFile().getAbsolutePath());
System.out.println("catalina.base set to: " + System.getProperty("catalina.base"));
adapter.setAppContextLocation(fileName);
adapter.setKey(ADAPTER_KEY);
adapter.startForTest();
return adapter;
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
try {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-invalid.xml");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setKey("KEY");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
adapter.setAppContextLocation("");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setAppContextLocation("SOMETHING");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("key must be defined", expected.getMessage());
}
adapter.setKey("");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setAppContextLocation("SOME_INVALID_PATH");
adapter.setKey("KEY");
try {
adapter.startForTest();
fail("Should have thrown LifecycleException");
} catch (LifecycleException expected) {
assertTrue(expected.getMessage().startsWith("appContextLocation does not seem to exist in"));
}
}
public void testAdapterIdentifiesItself() throws Exception {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(adapter.getName().lastIndexOf("CatalinaSpringUserRealm") != -1);
}
public void testAdapterStartsUpSuccess() throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertTrue(true);
}
public void testAuthenticateManyParamsReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.authenticate(null, null, null, null, null, null, null, null));
}
public void testAuthenticateX509ReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.authenticate(null));
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("rod", "kangaroo"));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("melissa", "koala"));
}
public void testAuthenticationUsingByteArrayForCredentials()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
byte[] credentials = {'k', 'o', 'a', 'l', 'a'};
Principal result = adapter.authenticate("rod", credentials);
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationUsingStringForCredentials()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
Principal result = adapter.authenticate("rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate("rod", (String) null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
CatalinaSpringSecurityUserRealm adapter = makeAdapter("catalinaAdapterTest-valid.xml");
assertEquals(null, adapter.authenticate(null, "koala"));
}
public void testGetPasswordReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.getPassword(null));
}
public void testGetPrincipalReturnsNull() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertEquals(null, adapter.getPrincipal(null));
}
public void testGetters() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
adapter.setKey("KEY");
assertEquals("KEY", adapter.getKey());
adapter.setAppContextLocation("SOME_LOCATION");
assertEquals("SOME_LOCATION", adapter.getAppContextLocation());
}
public void testHasRoleWithANullPrincipalFails() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(!adapter.hasRole(null, "ROLE_ONE"));
}
public void testHasRoleWithAPrincipalTheAdapterDidNotCreateFails() {
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(!adapter.hasRole(new Principal() {
public String getName() {
return "MockPrincipal";
}
}, "ROLE_ONE"));
}
public void testHasRoleWithPrincipalAcegiUserToken() {
PrincipalSpringSecurityUserToken token = new PrincipalSpringSecurityUserToken("KEY", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
CatalinaSpringSecurityUserRealm adapter = new CatalinaSpringSecurityUserRealm();
assertTrue(adapter.hasRole(token, "ROLE_ONE"));
assertTrue(adapter.hasRole(token, "ROLE_TWO"));
assertTrue(!adapter.hasRole(token, "ROLE_WE_DO_NOT_HAVE"));
}
}
+5
View File
@@ -0,0 +1,5 @@
target
.settings
.classpath
.project
.wtpmodules
+26
View File
@@ -0,0 +1,26 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-jboss</artifactId>
<name>Spring Security - JBoss adapter</name>
<dependencies>
<dependency>
<groupId>jboss</groupId>
<artifactId>jbosssx</artifactId>
<version>3.2.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,146 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.security.Principal;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Populates a {@link SecurityContext} from JBoss' <code>java:comp/env/security/subject</code>.
* <p>This filter <b>never</b> preserves the <code>Authentication</code> on the <code>ContextHolder</code> -
* it is replaced every request.</p>
* <p>See {@link HttpSessionContextIntegrationFilter} for further information.</p>
*
* @author Ben Alex
* @version $Id$
*/
public class JbossIntegrationFilter implements Filter {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(JbossIntegrationFilter.class);
//~ Methods ========================================================================================================
/**
* Does nothing. We use IoC container lifecycle services instead.
*/
public void destroy() {}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Object principal = extractFromContainer(request);
if ((principal != null) && principal instanceof Authentication) {
SecurityContextHolder.getContext().setAuthentication((Authentication) principal);
if (logger.isDebugEnabled()) {
logger.debug("ContextHolder updated with Authentication from container: '" + principal + "'");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("ContextHolder not set with new Authentication as Principal was: '" + principal + "'");
}
}
chain.doFilter(request, response);
}
private Object extractFromContainer(ServletRequest request) {
Subject subject = null;
try {
Context lc = this.getLookupContext();
if (lc == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not obtain a Context to perform lookup");
}
return null;
}
Object result = lc.lookup("java:comp/env/security/subject");
if (result instanceof Subject) {
subject = (Subject) result;
}
} catch (NamingException ne) {
if (logger.isWarnEnabled()) {
logger.warn("Lookup on Subject failed " + ne.getLocalizedMessage());
}
}
if ((subject != null) && (subject.getPrincipals() != null)) {
Iterator principals = subject.getPrincipals().iterator();
while (principals.hasNext()) {
Principal p = (Principal) principals.next();
if (p instanceof Authentication) {
return p;
}
}
}
return null;
}
/**
* Provided so that unit tests can override.
*
* @return a <code>Context</code> that can be used for lookup
*
* @throws NamingException DOCUMENT ME!
*/
protected Context getLookupContext() throws NamingException {
return new InitialContext();
}
/**
* Does nothing. We use IoC container lifecycle services instead.
*
* @param arg0 ignored
*
* @throws ServletException ignored
*/
public void init(FilterConfig arg0) throws ServletException {}
}
@@ -0,0 +1,302 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import org.springframework.security.AccountExpiredException;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.CredentialsExpiredException;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.AbstractServerLoginModule;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.beans.factory.access.SingletonBeanFactoryLocator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
/**
* Adapter to enable JBoss to authenticate via the Spring Security System for Spring.
* <p>Returns a {@link PrincipalSpringSecurityUserToken} to JBoss' authentication system,
* which is subsequently available from <code>java:comp/env/security/subject</code>.</p>
*
* @author Ben Alex
* @author Sergio Bern
* @version $Id:JbossSpringSecurityLoginModule.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossSpringSecurityLoginModule extends AbstractServerLoginModule {
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private Principal identity;
private String key;
private char[] credential;
//~ Methods ========================================================================================================
protected Principal getIdentity() {
return this.identity;
}
protected Group[] getRoleSets() throws LoginException {
SimpleGroup roles = new SimpleGroup("Roles");
Group[] roleSets = {roles};
if (this.identity instanceof Authentication) {
Authentication user = (Authentication) this.identity;
for (int i = 0; i < user.getAuthorities().length; i++) {
roles.addMember(new SimplePrincipal(user.getAuthorities()[i].getAuthority()));
}
}
return roleSets;
}
protected String[] getUsernameAndPassword() throws LoginException {
String[] info = {null, null};
// prompt for a username and password
if (callbackHandler == null) {
throw new LoginException("Error: no CallbackHandler available " + "to collect authentication information");
}
NameCallback nc = new NameCallback("User name: ", "guest");
PasswordCallback pc = new PasswordCallback("Password: ", false);
Callback[] callbacks = {nc, pc};
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = nc.getName();
char[] tmpPassword = pc.getPassword();
if (tmpPassword != null) {
credential = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
pc.clearPassword();
password = new String(credential);
}
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("CallbackHandler does not support: " + uce.getCallback());
}
info[0] = username;
info[1] = password;
return info;
}
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
super.initialize(subject, callbackHandler, sharedState, options);
if (super.log.isInfoEnabled()) {
super.log.info("initializing jboss login module");
}
this.key = (String) options.get("key");
if ((key == null) || "".equals(key)) {
throw new IllegalArgumentException("key must be defined");
}
String singletonId = (String) options.get("singletonId");
String appContextLocation = (String) options.get("appContextLocation");
if ((((singletonId == null) || "".equals(singletonId)) && (appContextLocation == null))
|| "".equals(appContextLocation)) {
throw new IllegalArgumentException("appContextLocation must be defined");
}
String beanName = (String) options.get("authenticationManager");
// Attempt to find the appContextLocation only if no singletonId was defined
if ((singletonId == null) || "".equals(singletonId)) {
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
if (super.log.isInfoEnabled()) {
super.log.info("cannot locate " + appContextLocation);
}
throw new IllegalArgumentException("Cannot locate " + appContextLocation);
}
}
ApplicationContext ctx = null;
if ((singletonId == null) || "".equals(singletonId)) {
try {
ctx = new ClassPathXmlApplicationContext(appContextLocation);
} catch (Exception e) {
if (super.log.isInfoEnabled()) {
super.log.info("error loading spring context " + appContextLocation + " " + e);
}
throw new IllegalArgumentException("error loading spring context " + appContextLocation + " " + e);
}
} else {
if (super.log.isInfoEnabled()) {
super.log.debug("retrieving singleton instance " + singletonId);
}
BeanFactoryLocator bfl = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bf = bfl.useBeanFactory(singletonId);
ctx = (ApplicationContext) bf.getFactory();
if (ctx == null) {
if (super.log.isInfoEnabled()) {
super.log.info("singleton " + beanName + " does not exists");
}
throw new IllegalArgumentException("singleton " + singletonId + " does not exists");
}
}
if ((beanName == null) || "".equals(beanName)) {
Map beans = null;
try {
beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
} catch (Exception e) {
if (super.log.isInfoEnabled()) {
super.log.info("exception in getBeansOfType " + e);
}
throw new IllegalStateException("spring error in get beans by class");
}
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
beanName = (String) beans.keySet().iterator().next();
}
authenticationManager = (AuthenticationManager) ctx.getBean(beanName);
if (super.log.isInfoEnabled()) {
super.log.info("Successfully started JbossSpringLoginModule");
}
}
public boolean login() throws LoginException {
super.loginOk = false;
String[] info = getUsernameAndPassword();
String username = info[0];
String password = info[1];
if ((username == null) && (password == null)) {
identity = null;
super.log.trace("Authenticating as unauthenticatedIdentity=" + identity);
}
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
if (super.log.isDebugEnabled()) {
super.log.debug("checking identity");
}
if (identity == null) {
super.log.debug("creating usernamepassword token");
Authentication request = new UsernamePasswordAuthenticationToken(username, password);
Authentication response = null;
try {
if (super.log.isDebugEnabled()) {
super.log.debug("attempting authentication");
}
response = authenticationManager.authenticate(request);
if (super.log.isDebugEnabled()) {
super.log.debug("authentication succeded");
}
} catch (CredentialsExpiredException cee) {
if (super.log.isDebugEnabled()) {
super.log.debug("Credential has expired");
}
throw new javax.security.auth.login.CredentialExpiredException(
"The credential used to identify the user has expired");
} catch (AccountExpiredException cee) {
if (super.log.isDebugEnabled()) {
super.log.debug("Account has expired, throwing jaas exception");
}
throw new javax.security.auth.login.AccountExpiredException(
"The account specified in login has expired");
} catch (AuthenticationException failed) {
if (super.log.isDebugEnabled()) {
super.log.debug("Bad password for username=" + username);
}
throw new FailedLoginException("Password Incorrect/Password Required");
}
super.log.debug("user is logged. redirecting to jaas classes");
identity = new PrincipalSpringSecurityUserToken(this.key, response.getName(), response.getCredentials().toString(),
response.getAuthorities(), response.getPrincipal());
}
if (getUseFirstPass() == true) {
// Add the username and password to the shared state map
sharedState.put("javax.security.auth.login.name", username);
sharedState.put("javax.security.auth.login.password", credential);
}
super.loginOk = true;
super.log.trace("User '" + identity + "' authenticated, loginOk=" + loginOk);
return true;
}
}
@@ -0,0 +1,7 @@
<html>
<body>
Adapter to JBoss.
<p>
</body>
</html>
@@ -0,0 +1,184 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.context.SecurityContextImpl;
import org.springframework.mock.web.MockHttpServletRequest;
import java.io.IOException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Set;
import javax.naming.Context;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Tests {@link JbossIntegrationFilter}.
*
* @author Ben Alex
* @version $Id:JbossIntegrationFilterTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossIntegrationFilterTests extends TestCase {
//~ Constructors ===================================================================================================
public JbossIntegrationFilterTests() {
super();
}
public JbossIntegrationFilterTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
private void executeFilterInContainerSimulator(FilterConfig filterConfig, Filter filter, ServletRequest request,
ServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filter.init(filterConfig);
filter.doFilter(request, response, filterChain);
filter.destroy();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(JbossIntegrationFilterTests.class);
}
private Subject makeIntoSubject(Principal principal) {
Set principals = new HashSet();
principals.add(principal);
return new Subject(false, principals, new HashSet(), new HashSet());
}
protected void setUp() throws Exception {
super.setUp();
SecurityContextHolder.setContext(new SecurityContextImpl());
}
protected void tearDown() throws Exception {
super.tearDown();
SecurityContextHolder.setContext(new SecurityContextImpl());
}
public void testCorrectOperation() throws Exception {
PrincipalSpringSecurityUserToken principal = new PrincipalSpringSecurityUserToken("key", "someone", "password",
new GrantedAuthority[] {new GrantedAuthorityImpl("SOME_ROLE")}, null);
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(principal)));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertEquals(principal, SecurityContextHolder.getContext().getAuthentication());
SecurityContextHolder.setContext(new SecurityContextImpl());
}
public void testReturnsNullIfContextReturnsSomethingOtherThanASubject()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext("THIS_IS_NOT_A_SUBJECT"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullPrincipal()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(null)));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextHasNullSubject()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(null));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfInitialContextIsNull()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(null);
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testReturnsNullIfPrincipalNotAnAuthenticationImplementation()
throws Exception {
JbossIntegrationFilter filter = new MockJbossIntegrationFilter(new MockInitialContext(makeIntoSubject(
new Principal() {
public String getName() {
return "MockPrincipal";
}
})));
MockHttpServletRequest request = new MockHttpServletRequest();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, null, chain);
assertNull(SecurityContextHolder.getContext().getAuthentication());
}
public void testTestingObjectReturnsInitialContext()
throws Exception {
JbossIntegrationFilter filter = new JbossIntegrationFilter();
assertTrue(filter.getLookupContext() instanceof Context);
}
//~ Inner Classes ==================================================================================================
private class MockFilterChain implements FilterChain {
public void doFilter(ServletRequest arg0, ServletResponse arg1)
throws IOException, ServletException {}
}
}
@@ -0,0 +1,356 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import junit.framework.TestCase;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.jboss.security.SimplePrincipal;
import java.io.IOException;
import java.security.Principal;
import java.security.acl.Group;
import java.util.Properties;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
/**
* Tests {@link JbossSpringSecurityLoginModule}.
*
* @author Ben Alex
* @version $Id:JbossSpringSecurityLoginModuleTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JbossSpringSecurityLoginModuleTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public JbossSpringSecurityLoginModuleTests() {
super();
}
public JbossSpringSecurityLoginModuleTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JbossSpringSecurityLoginModuleTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-invalid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be defined", expected.getMessage());
}
props = new Properties();
props.put("key", "");
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "INVALID_PATH");
try {
adapter.initialize(null, null, null, props);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue("Cannot locate INVALID_PATH".equals(expected.getMessage()));
}
}
public void testAdapterFailsToAuthenticateIfNoCallbackHandlerAvailable()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
adapter.initialize(subject, null, null, props);
try {
adapter.login();
} catch (LoginException loginException) {
assertEquals("Error: no CallbackHandler available to collect authentication information",
loginException.getMessage());
}
}
public void testAdapterStartsUpSuccess() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
adapter.initialize(null, null, null, props);
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "kangaroo");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("melissa", "koala");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationSuccess() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "koala");
adapter.initialize(subject, callback, null, props);
assertTrue(adapter.login());
Principal result = adapter.getIdentity();
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", null);
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationWithNullUserNameAndNullPasswordHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler(null, null);
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler(null, "kangaroo");
adapter.initialize(subject, callback, null, props);
try {
adapter.login();
fail("Should have thrown FailedLoginException");
} catch (FailedLoginException expected) {
assertTrue(true);
}
}
public void testGetRoleSets() throws Exception {
JbossSpringSecurityLoginModule adapter = new JbossSpringSecurityLoginModule();
Properties props = new Properties();
props.put("key", ADAPTER_KEY);
props.put("appContextLocation", "org/springframework/security/adapters/adaptertest-valid.xml");
Subject subject = new Subject();
CallbackHandler callback = new MockCallbackHandler("rod", "koala");
adapter.initialize(subject, callback, null, props);
assertTrue(adapter.login());
Group[] result = adapter.getRoleSets();
// Expect Roles group.
assertEquals(1, result.length);
Group roles = result[0];
assertTrue(roles.isMember(new SimplePrincipal("ROLE_TELLER")));
assertTrue(roles.isMember(new SimplePrincipal("ROLE_SUPERVISOR")));
}
//~ Inner Classes ==================================================================================================
private class MockCallbackHandler implements CallbackHandler {
private String password;
private String username;
public MockCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback) callbacks[i]).setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
if (this.password == null) {
((PasswordCallback) callbacks[i]).setPassword(null);
} else {
((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
}
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
}
}
@@ -0,0 +1,167 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
/**
* Mocks a <code>javax.naming.Context</code> and returns an <code>Object</code> when queried for address
* <code>java:comp/env/security/subject</code>.
*
* @author Ben Alex
* @version $Id:MockInitialContext.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class MockInitialContext implements Context {
//~ Instance fields ================================================================================================
private Object object;
//~ Constructors ===================================================================================================
public MockInitialContext(Object object) {
this.object = object;
}
//~ Methods ========================================================================================================
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void bind(String name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void bind(Name name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void close() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public String composeName(String name, String prefix)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Name composeName(Name name, Name prefix) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Context createSubcontext(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Context createSubcontext(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void destroySubcontext(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void destroySubcontext(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Hashtable getEnvironment() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public String getNameInNamespace() throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NameParser getNameParser(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NameParser getNameParser(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration list(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration list(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration listBindings(String name)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public NamingEnumeration listBindings(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookup(String name) throws NamingException {
return this.object;
}
public Object lookup(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookupLink(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object lookupLink(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rebind(String name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rebind(Name name, Object obj) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public Object removeFromEnvironment(String propName)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rename(String oldName, String newName)
throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void rename(Name oldName, Name newName) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void unbind(String name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
public void unbind(Name name) throws NamingException {
throw new UnsupportedOperationException("mock method not implemented");
}
}
@@ -0,0 +1,45 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jboss;
import javax.naming.Context;
import javax.naming.NamingException;
/**
* Provides mock of <code>JbossIntegrationFilter</code>, using a lookup <code>Context</code> provided in the
* constructor.
*
* @author Ben Alex
* @version $Id:MockJbossIntegrationFilter.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class MockJbossIntegrationFilter extends JbossIntegrationFilter {
//~ Instance fields ================================================================================================
private Context context;
//~ Constructors ===================================================================================================
public MockJbossIntegrationFilter(Context context) {
this.context = context;
}
//~ Methods ========================================================================================================
protected Context getLookupContext() throws NamingException {
return this.context;
}
}
+5
View File
@@ -0,0 +1,5 @@
target
.settings
.classpath
.project
.wtpmodules
+22
View File
@@ -0,0 +1,22 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-jetty</artifactId>
<name>Spring Security - Jetty adapter</name>
<dependencies>
<dependency>
<groupId>jetty</groupId>
<artifactId>org.mortbay.jetty</artifactId>
<version>4.2.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,161 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jetty;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.http.HttpRequest;
import org.mortbay.http.UserPrincipal;
import org.mortbay.http.UserRealm;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Map;
/**
* Adapter to enable Jetty to authenticate via Spring Security.<p>Returns a {@link
* JettySpringSecurityUserToken} to Jetty's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserRealm.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public final class JettySpringSecurityUserRealm implements UserRealm {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(JettySpringSecurityUserRealm.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private String key;
private String realm;
//~ Constructors ===================================================================================================
/**
* Construct a <code>SpringUserRealm</code>.
*
* @param realm the name of the authentication realm (within Jetty)
* @param providerKey a password to sign all authentication objects
* @param appContextLocation the classpath location of the bean context XML
* file
*
* @throws IllegalArgumentException DOCUMENT ME!
*/
public JettySpringSecurityUserRealm(String realm, String providerKey, String appContextLocation) {
this.realm = realm;
this.key = providerKey;
if ((realm == null) || "".equals(realm)) {
throw new IllegalArgumentException("realm must be specified");
}
if ((key == null) || "".equals(key)) {
throw new IllegalArgumentException("key must be specified");
}
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new IllegalArgumentException("appContextLocation must be specified");
}
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
throw new IllegalArgumentException("Cannot locate " + appContextLocation);
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation);
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new IllegalArgumentException(
"Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
}
protected JettySpringSecurityUserRealm() {
throw new IllegalArgumentException("Cannot use default constructor");
}
//~ Methods ========================================================================================================
public UserPrincipal authenticate(String username, Object password, HttpRequest httpRequest) {
if (username == null) {
return null;
}
if (password == null) {
password = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username.toString(), password.toString());
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new JettySpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities());
}
public void disassociate(UserPrincipal userPrincipal) {
// No action required
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
/**
* Accesses the realm name.
*
* @return the name of the realm as defined when <code>SpringUserRealm</code> was created
*/
public String getName() {
return this.realm;
}
public void logout(UserPrincipal arg0) {
// Not supported
}
public UserPrincipal popRole(UserPrincipal userPrincipal) {
// Not supported
return userPrincipal;
}
public UserPrincipal pushRole(UserPrincipal userPrincipal, String role) {
// Not supported
return userPrincipal;
}
}
@@ -0,0 +1,63 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jetty;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.adapters.AbstractAdapterAuthenticationToken;
import org.mortbay.http.UserPrincipal;
/**
* A Jetty compatible {@link org.springframework.security.Authentication} object.
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserToken.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettySpringSecurityUserToken extends AbstractAdapterAuthenticationToken implements UserPrincipal {
//~ Instance fields ================================================================================================
private static final long serialVersionUID = 1L;
private String password;
private String username;
//~ Constructors ===================================================================================================
public JettySpringSecurityUserToken(String key, String username, String password, GrantedAuthority[] authorities) {
super(key, authorities);
this.username = username;
this.password = password;
}
protected JettySpringSecurityUserToken() {
throw new IllegalArgumentException("Cannot use default constructor");
}
//~ Methods ========================================================================================================
public Object getCredentials() {
return this.password;
}
public String getName() {
return this.username;
}
public Object getPrincipal() {
return this.username;
}
}
@@ -0,0 +1,7 @@
<html>
<body>
Adapter to Jetty web container.
<p>
</body>
</html>
@@ -0,0 +1,237 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jetty;
import junit.framework.TestCase;
import org.mortbay.http.UserPrincipal;
/**
* Tests {@link JettySpringSecurityUserRealm}.
*
* @author Ben Alex
* @version $Id:JettyAcegiUserRealmTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettyAcegiUserRealmTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
private final String REALM_NAME = "Acegi Powered Realm";
//~ Constructors ===================================================================================================
public JettyAcegiUserRealmTests() {
super();
}
public JettyAcegiUserRealmTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(JettyAcegiUserRealmTests.class);
}
private JettySpringSecurityUserRealm makeAdapter(String fileName)
throws Exception {
String useFile = "org/springframework/security/adapters/" + fileName;
return new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, useFile);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
try {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-invalid.xml");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("Bean context must contain at least one bean of type AuthenticationManager",
expected.getMessage());
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, "");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("appContextLocation must be specified", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, null, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(REALM_NAME, "", "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("key must be specified", expected.getMessage());
}
}
public void testAdapterAbortsIfNoRealmNameSpecified()
throws Exception {
try {
new JettySpringSecurityUserRealm(null, ADAPTER_KEY, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("realm must be specified", expected.getMessage());
}
try {
new JettySpringSecurityUserRealm(null, ADAPTER_KEY, "SOME_PATH");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertEquals("realm must be specified", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
try {
new JettySpringSecurityUserRealm(REALM_NAME, ADAPTER_KEY, "SOME_INVALID_LOCATION");
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage().startsWith("Cannot locate"));
}
}
public void testAdapterIdentifiesTheRealmItManages()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(REALM_NAME, adapter.getName());
}
public void testAdapterStartsUpSuccess() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("rod", "kangaroo", null));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("melissa", "koala", null));
}
public void testAuthenticationSuccess() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
UserPrincipal result = adapter.authenticate("rod", "koala", null);
if (!(result instanceof JettySpringSecurityUserToken)) {
fail("Should have returned JettySpringSecurityUserToken");
}
JettySpringSecurityUserToken castResult = (JettySpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate("rod", null, null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertEquals(null, adapter.authenticate(null, "koala", null));
}
public void testDisassociateImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
adapter.disassociate(new MockUserPrincipal());
assertTrue(true);
}
public void testGetAuthenticationManager() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
assertTrue(adapter.getAuthenticationManager() != null);
}
public void testLogoutImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
adapter.logout(new MockUserPrincipal());
assertTrue(true);
}
public void testNoArgsConstructor() {
try {
new JettySpringSecurityUserRealm();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testPopRoleImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
MockUserPrincipal user = new MockUserPrincipal();
assertEquals(user, adapter.popRole(user));
}
public void testPushRoleImplemented() throws Exception {
JettySpringSecurityUserRealm adapter = makeAdapter("adaptertest-valid.xml");
MockUserPrincipal user = new MockUserPrincipal();
assertEquals(user, adapter.pushRole(user, "SOME_ROLE"));
}
//~ Inner Classes ==================================================================================================
private class MockUserPrincipal implements UserPrincipal {
public String getName() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isAuthenticated() {
throw new UnsupportedOperationException("mock method not implemented");
}
public boolean isUserInRole(String arg0) {
throw new UnsupportedOperationException("mock method not implemented");
}
}
}
@@ -0,0 +1,59 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.jetty;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
/**
* Tests {@link JettySpringSecurityUserToken}.
*
* @author Ben Alex
* @version $Id:JettySpringSecurityUserTokenTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class JettySpringSecurityUserTokenTests extends TestCase {
//~ Constructors ===================================================================================================
public JettySpringSecurityUserTokenTests() {
}
public JettySpringSecurityUserTokenTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public void testGetters() throws Exception {
JettySpringSecurityUserToken token = new JettySpringSecurityUserToken("my_password", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertEquals("Test", token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("my_password".hashCode(), token.getKeyHash());
assertEquals("Test", token.getName());
}
public void testNoArgsConstructor() {
try {
new JettySpringSecurityUserToken();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-parent</artifactId>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-adapters</artifactId>
<name>Spring Security - Adapters</name>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<modules>
<module>catalina</module>
<module>jboss</module>
<module>jetty</module>
<module>resin</module>
</modules>
</project>
+5
View File
@@ -0,0 +1,5 @@
target
.settings
.classpath
.project
.wtpmodules
+26
View File
@@ -0,0 +1,26 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-adapters</artifactId>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-resin</artifactId>
<name>Spring Security - Resin adapter</name>
<dependencies>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>resin</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,152 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.resin;
import com.caucho.http.security.AbstractAuthenticator;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.security.Principal;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Adapter to enable Resin to authenticate via Spring Security.<p>Returns a {@link
* PrincipalSpringSecurityUserToken} to Resin's authentication system, which is subsequently available via
* <code>HttpServletRequest.getUserPrincipal()</code>.</p>
*
* @author Ben Alex
* @version $Id:ResinAcegiAuthenticator.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class ResinAcegiAuthenticator extends AbstractAuthenticator {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(ResinAcegiAuthenticator.class);
//~ Instance fields ================================================================================================
private AuthenticationManager authenticationManager;
private String appContextLocation;
private String key;
//~ Methods ========================================================================================================
public String getAppContextLocation() {
return appContextLocation;
}
public String getKey() {
return key;
}
public void init() throws ServletException {
super.init();
if ((appContextLocation == null) || "".equals(appContextLocation)) {
throw new ServletException("appContextLocation must be defined");
}
if ((key == null) || "".equals(key)) {
throw new ServletException("key must be defined");
}
if (Thread.currentThread().getContextClassLoader().getResource(appContextLocation) == null) {
throw new ServletException("Cannot locate " + appContextLocation);
}
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(appContextLocation);
Map beans = ctx.getBeansOfType(AuthenticationManager.class, true, true);
if (beans.size() == 0) {
throw new ServletException("Bean context must contain at least one bean of type AuthenticationManager");
}
String beanName = (String) beans.keySet().iterator().next();
authenticationManager = (AuthenticationManager) beans.get(beanName);
logger.info("ResinAcegiAuthenticator Started");
}
public boolean isUserInRole(HttpServletRequest request, HttpServletResponse response, ServletContext application,
Principal principal, String role) {
if (!(principal instanceof PrincipalSpringSecurityUserToken)) {
if (logger.isWarnEnabled()) {
logger.warn("Expected passed principal to be of type PrincipalSpringSecurityUserToken");
}
return false;
}
PrincipalSpringSecurityUserToken test = (PrincipalSpringSecurityUserToken) principal;
return test.isUserInRole(role);
}
protected Principal loginImpl(String username, String credentials) {
if (username == null) {
return null;
}
if (credentials == null) {
credentials = "";
}
Authentication request = new UsernamePasswordAuthenticationToken(username, credentials);
Authentication response = null;
try {
response = authenticationManager.authenticate(request);
} catch (AuthenticationException failed) {
if (logger.isDebugEnabled()) {
logger.debug("Authentication request for user: " + username + " failed: " + failed.toString());
}
return null;
}
return new PrincipalSpringSecurityUserToken(this.key, response.getPrincipal().toString(),
response.getCredentials().toString(), response.getAuthorities(), response.getPrincipal());
}
protected Principal loginImpl(HttpServletRequest request, HttpServletResponse response, ServletContext application,
String userName, String password) throws ServletException {
return loginImpl(userName, password);
}
public void setAppContextLocation(String appContextLocation) {
this.appContextLocation = appContextLocation;
}
public void setKey(String key) {
this.key = key;
}
}
@@ -0,0 +1,7 @@
<html>
<body>
Adapter to Resin web container.
<p>
</body>
</html>
@@ -0,0 +1,261 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.adapters.resin;
import junit.framework.TestCase;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.adapters.PrincipalSpringSecurityUserToken;
import java.security.Principal;
import javax.servlet.ServletException;
/**
* Tests {@link ResinAcegiAuthenticator}.
*
* @author Ben Alex
* @version $Id:ResinAcegiAuthenticatorTests.java 2151 2007-09-22 11:54:13Z luke_t $
*/
public class ResinAcegiAuthenticatorTests extends TestCase {
//~ Instance fields ================================================================================================
private final String ADAPTER_KEY = "my_key";
//~ Constructors ===================================================================================================
public ResinAcegiAuthenticatorTests() {
super();
}
public ResinAcegiAuthenticatorTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(ResinAcegiAuthenticatorTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-invalid.xml");
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("Bean context must contain at least one bean of type AuthenticationManager",
expected.getMessage());
}
}
public void testAdapterAbortsIfNoAppContextSpecified()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
adapter.setAppContextLocation("");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("appContextLocation must be defined", expected.getMessage());
}
}
public void testAdapterAbortsIfNoKeySpecified() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("key must be defined", expected.getMessage());
}
adapter.setKey("");
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertEquals("key must be defined", expected.getMessage());
}
}
public void testAdapterAbortsWithIncorrectApplicationContextLocation()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("FILE_DOES_NOT_EXIST");
adapter.setKey(ADAPTER_KEY);
try {
adapter.init();
fail("Should have thrown ServletException");
} catch (ServletException expected) {
assertTrue(expected.getMessage().startsWith("Cannot locate"));
}
}
public void testAdapterStartsUpSuccess() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(true);
}
public void testAuthenticationFailsForIncorrectPassword()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("rod", "kangaroo"));
}
public void testAuthenticationFailsForIncorrectUserName()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("melissa", "koala"));
}
public void testAuthenticationSuccess() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
Principal result = adapter.loginImpl("rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationSuccessUsingAlternateMethod()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
Principal result = adapter.loginImpl(null, null, null, "rod", "koala");
if (!(result instanceof PrincipalSpringSecurityUserToken)) {
fail("Should have returned PrincipalSpringSecurityUserToken");
}
PrincipalSpringSecurityUserToken castResult = (PrincipalSpringSecurityUserToken) result;
assertEquals("rod", castResult.getPrincipal());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_TELLER", castResult.getAuthorities()[1].getAuthority());
assertEquals("ROLE_SUPERVISOR", castResult.getAuthorities()[0].getAuthority());
assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
}
public void testAuthenticationWithNullPasswordHandledGracefully()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl("rod", null));
}
public void testAuthenticationWithNullUserNameHandledGracefully()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertEquals(null, adapter.loginImpl(null, "koala"));
}
public void testGetters() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
assertEquals(ADAPTER_KEY, adapter.getKey());
assertEquals("org/springframework/security/adapters/adaptertest-valid.xml", adapter.getAppContextLocation());
}
public void testHasRoleWithANullPrincipalFails() throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(!adapter.isUserInRole(null, null, null, null, "ROLE_ONE"));
}
public void testHasRoleWithAPrincipalTheAdapterDidNotCreateFails()
throws Exception {
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(!adapter.isUserInRole(null, null, null,
new Principal() {
public String getName() {
return "MockPrincipal";
}
}, "ROLE_ONE"));
}
public void testHasRoleWithPrincipalAcegiUserToken()
throws Exception {
PrincipalSpringSecurityUserToken token = new PrincipalSpringSecurityUserToken("KEY", "Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null);
ResinAcegiAuthenticator adapter = new ResinAcegiAuthenticator();
adapter.setAppContextLocation("org/springframework/security/adapters/adaptertest-valid.xml");
adapter.setKey(ADAPTER_KEY);
adapter.init();
assertTrue(adapter.isUserInRole(null, null, null, token, "ROLE_ONE"));
assertTrue(adapter.isUserInRole(null, null, null, token, "ROLE_ONE"));
assertTrue(!adapter.isUserInRole(null, null, null, token, "ROLE_WE_DO_NOT_HAVE"));
}
}
+32 -15
View File
@@ -3,11 +3,11 @@
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-parent</artifactId>
<version>2.5.0.M1</version>
<version>2.0.2</version>
</parent>
<artifactId>spring-security-cas-client</artifactId>
<name>Spring Security - CAS support</name>
<packaging>jar</packaging>
<packaging>bundle</packaging>
<dependencies>
<dependency>
@@ -16,29 +16,22 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.transaction</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>org.springframework.test</artifactId>
<artifactId>spring-mock</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-client-core</artifactId>
<version>3.1.5</version>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
@@ -46,5 +39,29 @@
<optional>true</optional>
</dependency>
</dependencies>
<properties>
<spring.osgi.export>
org.springframework.security.*;version=${pom.version.osgi}
</spring.osgi.export>
<spring.osgi.import>
org.springframework.security.*;version="[${pom.version.osgi},${pom.version.osgi}]",
org.springframework.beans.*;version="${spring.version.osgi}",
org.springframework.context.*;version="${spring.version.osgi}",
org.springframework.dao.*;version="${spring.version.osgi}";resolution:=optional,
org.springframework.util.*;version="${spring.version.osgi}",
javax.servlet.*;version="[2.4.0, 3.0.0)";resolution:=optional,
net.sf.ehcache.*;version="[1.4.1, 2.0.0)";resolution:=optional,
org.apache.commons.logging.*;version="[1.1.1, 2.0.0)",
org.jasig.cas.client.*;version="[3.1.1, 4.0.0)"
</spring.osgi.import>
</project>
<spring.osgi.private.pkg>
!org.springframework.security.*
</spring.osgi.private.pkg>
<spring.osgi.symbolic.name>org.springframework.security.cas</spring.osgi.symbolic.name>
</properties>
</project>
@@ -18,23 +18,32 @@ package org.springframework.security.providers.cas;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.TicketValidationException;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.SpringSecurityMessageSource;
import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.cas.cache.NullStatelessTicketCache;
import org.springframework.security.ui.cas.CasProcessingFilter;
import org.springframework.security.ui.cas.ServiceProperties;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsChecker;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UserDetailsChecker;
import org.springframework.security.userdetails.checker.AccountStatusUserDetailsChecker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;
@@ -51,6 +60,9 @@ import org.springframework.util.Assert;
* @version $Id$
*/
public class CasAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
//~ Static fields/initializers =====================================================================================
private static final Log logger = LogFactory.getLog(CasAuthenticationProvider.class);
//~ Instance fields ================================================================================================
@@ -64,7 +76,7 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.userDetailsService, "A userDetailsService must be set");
Assert.notNull(this.ticketValidator, "A ticketValidator must be set");
Assert.notNull(this.statelessTicketCache, "A statelessTicketCache must be set");
@@ -128,38 +140,29 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
return result;
}
private final CasAuthenticationToken authenticateNow(final Authentication authentication) throws AuthenticationException {
try {
final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
final UserDetails userDetails = loadUserByAssertion(assertion);
userDetailsChecker.check(userDetails);
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(), userDetails.getAuthorities(), userDetails, assertion);
} catch (final TicketValidationException e) {
throw new BadCredentialsException(e.getMessage(), e);
}
}
/**
* Template method for retrieving the UserDetails based on the assertion. Default is to call configured userDetailsService and pass the username. Deployers
* can override this method and retrieve the user based on any criteria they desire.
*
* @param assertion The CAS Assertion.
* @returns the UserDetails.
*/
protected UserDetails loadUserByAssertion(final Assertion assertion) {
return this.userDetailsService.loadUserByUsername(assertion.getPrincipal().getName());
private CasAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
try {
final Assertion assertion = this.ticketValidator.validate(authentication.getCredentials().toString(), serviceProperties.getService());
final UserDetails userDetails = userDetailsService.loadUserByUsername(assertion.getPrincipal().getName());
userDetailsChecker.check(userDetails);
return new CasAuthenticationToken(this.key, userDetails, authentication.getCredentials(),
userDetails.getAuthorities(), userDetails, assertion);
} catch (final TicketValidationException e) {
// TODO get error message
throw new BadCredentialsException("", e);
}
}
protected UserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsService(final UserDetailsService userDetailsService) {
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public void setServiceProperties(final ServiceProperties serviceProperties) {
this.serviceProperties = serviceProperties;
this.serviceProperties = serviceProperties;
}
protected String getKey() {
@@ -178,19 +181,19 @@ public class CasAuthenticationProvider implements AuthenticationProvider, Initia
return ticketValidator;
}
public void setMessageSource(final MessageSource messageSource) {
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
public void setStatelessTicketCache(final StatelessTicketCache statelessTicketCache) {
public void setStatelessTicketCache(StatelessTicketCache statelessTicketCache) {
this.statelessTicketCache = statelessTicketCache;
}
public void setTicketValidator(final TicketValidator ticketValidator) {
public void setTicketValidator(TicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
}
public boolean supports(final Class<? extends Object> authentication) {
public boolean supports(final Class authentication) {
if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)) {
return true;
} else if (CasAuthenticationToken.class.isAssignableFrom(authentication)) {
@@ -23,8 +23,6 @@ import org.springframework.security.providers.AbstractAuthenticationToken;
import org.springframework.security.userdetails.UserDetails;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* Represents a successful CAS <code>Authentication</code>.
@@ -45,15 +43,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
//~ Constructors ===================================================================================================
/**
* @deprecated
*/
public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final GrantedAuthority[] authorities, final UserDetails userDetails, final Assertion assertion) {
this(key, principal, credentials, Arrays.asList(authorities), userDetails, assertion);
}
/**
/**
* Constructor.
*
* @param key to identify if this object made by a given {@link
@@ -71,7 +61,7 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
* @throws IllegalArgumentException if a <code>null</code> was passed
*/
public CasAuthenticationToken(final String key, final Object principal, final Object credentials,
final List<GrantedAuthority> authorities, final UserDetails userDetails, final Assertion assertion) {
final GrantedAuthority[] authorities, final UserDetails userDetails, final Assertion assertion) {
super(authorities);
if ((key == null) || ("".equals(key)) || (principal == null) || "".equals(principal) || (credentials == null)
@@ -96,9 +86,9 @@ public class CasAuthenticationToken extends AbstractAuthenticationToken implemen
if (obj instanceof CasAuthenticationToken) {
CasAuthenticationToken test = (CasAuthenticationToken) obj;
if (!this.assertion.equals(test.getAssertion())) {
return false;
return false;
}
if (this.getKeyHash() != test.getKeyHash()) {
@@ -33,31 +33,31 @@ import org.springframework.security.providers.cas.StatelessTicketCache;
*/
public final class NullStatelessTicketCache implements StatelessTicketCache {
/**
* @return null since we are not storing any tickets.
*/
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
return null;
}
/**
* @return null since we are not storing any tickets.
*/
public CasAuthenticationToken getByTicketId(final String serviceTicket) {
return null;
}
/**
* This is a no-op since we are not storing tickets.
*/
public void putTicketInCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
public void putTicketInCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
public void removeTicketFromCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
public void removeTicketFromCache(final CasAuthenticationToken token) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
public void removeTicketFromCache(final String serviceTicket) {
// nothing to do
}
/**
* This is a no-op since we are not storing tickets.
*/
public void removeTicketFromCache(final String serviceTicket) {
// nothing to do
}
}
@@ -15,11 +15,6 @@
package org.springframework.security.ui.cas;
import java.io.IOException;
import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
import org.jasig.cas.client.util.CommonUtils;
import org.jasig.cas.client.validation.TicketValidator;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
@@ -29,31 +24,22 @@ import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.FilterChainOrder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Processes a CAS service ticket.
* <p>
* A service ticket consists of an opaque ticket string. It arrives at this filter by the user's browser successfully
* authenticating using CAS, and then receiving a HTTP redirect to a <code>service</code>. The opaque ticket string is
* presented in the <code>ticket</code> request parameter. This filter monitors the <code>service</code> URL so it can
* receive the service ticket and process it. The CAS server knows which <code>service</code> URL to use via the
* {@link ServiceProperties#getService()} method.
* <p>
* Processing the service ticket involves creating a <code>UsernamePasswordAuthenticationToken</code> which
* Processes a CAS service ticket.<p>A service ticket consists of an opaque ticket string. It arrives at this
* filter by the user's browser successfully authenticating using CAS, and then receiving a HTTP redirect to a
* <code>service</code>. The opaque ticket string is presented in the <code>ticket</code> request parameter. This
* filter monitors the <code>service</code> URL so it can receive the service ticket and process it. The CAS server
* knows which <code>service</code> URL to use via the {@link ServiceProperties#getService()} method.</p>
* <p>Processing the service ticket involves creating a <code>UsernamePasswordAuthenticationToken</code> which
* uses {@link #CAS_STATEFUL_IDENTIFIER} for the <code>principal</code> and the opaque ticket string as the
* <code>credentials</code>.
* <p>
* The configured <code>AuthenticationManager</code> is expected to provide a provider that can recognise
* <code>credentials</code>.</p>
* <p>The configured <code>AuthenticationManager</code> is expected to provide a provider that can recognise
* <code>UsernamePasswordAuthenticationToken</code>s containing this special <code>principal</code> name, and process
* them accordingly by validation with the CAS server.
* <p>
* By configuring a shared {@link ProxyGrantingTicketStorage} between the {@link TicketValidator} and the
* CasProcessingFilter one can have the CasProcessingFilter handle the proxying requirements for CAS. In addition, the
* URI endpoint for the proxying would also need to be configured (i.e. the part after protocol, hostname, and port).
* <p>
* By default this filter processes the URL <tt>/j_spring_cas_security_check</tt>.
* them accordingly by validation with the CAS server.</p>
* <p><b>Do not use this class directly.</b> Instead configure <code>web.xml</code> to use the {@link
* org.springframework.security.util.FilterToBeanProxy}.</p>
*
* @author Ben Alex
* @version $Id$
@@ -65,32 +51,16 @@ public class CasProcessingFilter extends AbstractProcessingFilter {
public static final String CAS_STATEFUL_IDENTIFIER = "_cas_stateful_";
/**
* Used to identify a CAS request for a stateless user agent, such as a remoting protocol client (e.g.
* Used to identify a CAS request for a stateless user agent, such as a remoting protocol client (eg
* Hessian, Burlap, SOAP etc). Results in a more aggressive caching strategy being used, as the absence of a
* <code>HttpSession</code> will result in a new authentication attempt on every request.
*/
public static final String CAS_STATELESS_IDENTIFIER = "_cas_stateless_";
/**
* The last portion of the receptor url, i.e. /proxy/receptor
*/
private String proxyReceptorUrl;
/**
* The backing storage to store ProxyGrantingTicket requests.
*/
private ProxyGrantingTicketStorage proxyGrantingTicketStorage;
//~ Constructors ===================================================================================================
public CasProcessingFilter() {
super("/j_spring_cas_security_check");
}
//~ Methods ========================================================================================================
public Authentication attemptAuthentication(final HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
public Authentication attemptAuthentication(final HttpServletRequest request)
throws AuthenticationException {
final String username = CAS_STATEFUL_IDENTIFIER;
String password = request.getParameter("ticket");
@@ -106,30 +76,12 @@ public class CasProcessingFilter extends AbstractProcessingFilter {
}
/**
* Overridden to provide proxying capabilities.
* This filter by default responds to <code>/j_spring_cas_security_check</code>.
*
* @return the default
*/
protected boolean requiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
final String requestUri = request.getRequestURI();
if (CommonUtils.isEmpty(this.proxyReceptorUrl) || !requestUri.endsWith(this.proxyReceptorUrl) || this.proxyGrantingTicketStorage == null) {
return super.requiresAuthentication(request, response);
}
try {
CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage);
return false;
} catch (final IOException e) {
return super.requiresAuthentication(request, response);
}
}
public final void setProxyReceptorUrl(final String proxyReceptorUrl) {
this.proxyReceptorUrl = proxyReceptorUrl;
}
public final void setProxyGrantingTicketStorage(
final ProxyGrantingTicketStorage proxyGrantingTicketStorage) {
this.proxyGrantingTicketStorage = proxyGrantingTicketStorage;
public String getDefaultFilterProcessesUrl() {
return "/j_spring_cas_security_check";
}
public int getOrder() {
@@ -18,7 +18,8 @@ package org.springframework.security.ui.cas;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.jasig.cas.client.util.CommonUtils;
@@ -60,13 +61,13 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint,
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() throws Exception {
Assert.hasLength(this.loginUrl, "loginUrl must be specified");
Assert.notNull(this.serviceProperties, "serviceProperties must be specified");
}
public void commence(final HttpServletRequest servletRequest, final HttpServletResponse servletResponse,
final AuthenticationException authenticationException) throws IOException, ServletException {
public void commence(final ServletRequest servletRequest, final ServletResponse servletResponse,
final AuthenticationException authenticationException) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) servletResponse;
final String urlEncodedService = CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, "ticket", this.encodeServiceUrlWithSessionId);
@@ -98,6 +99,6 @@ public class CasProcessingFilterEntryPoint implements AuthenticationEntryPoint,
}
public void setEncodeServiceUrlWithSessionId(final boolean encodeServiceUrlWithSessionId) {
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId;
}
}
@@ -38,7 +38,7 @@ public class ServiceProperties implements InitializingBean {
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
Assert.hasLength(this.service, "service must be specified.");
Assert.hasLength(this.service, "service must be specified.");
}
/**
@@ -30,7 +30,6 @@ import org.springframework.security.ui.cas.ServiceProperties;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.util.AuthorityUtils;
import java.util.HashMap;
import java.util.Map;
@@ -55,20 +54,20 @@ public class CasAuthenticationProviderTests {
private UserDetails makeUserDetails() {
return new User("user", "password", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
}
private UserDetails makeUserDetailsFromAuthoritiesPopulator() {
return new User("user", "password", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"));
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
}
private ServiceProperties makeServiceProperties() {
final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false);
serviceProperties.setService("http://test.com");
return serviceProperties;
final ServiceProperties serviceProperties = new ServiceProperties();
serviceProperties.setSendRenew(false);
serviceProperties.setService("http://test.com");
return serviceProperties;
}
@Test
@@ -80,12 +79,12 @@ public class CasAuthenticationProviderTests {
StatelessTicketCache cache = new MockStatelessTicketCache();
cap.setStatelessTicketCache(cache);
cap.setServiceProperties(makeServiceProperties());
cap.setTicketValidator(new MockTicketValidator(true));
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, "ST-123");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER,
"ST-123");
token.setDetails("details");
Authentication result = cap.authenticate(token);
@@ -100,8 +99,8 @@ public class CasAuthenticationProviderTests {
CasAuthenticationToken casResult = (CasAuthenticationToken) result;
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
assertEquals("ST-123", casResult.getCredentials());
assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities().get(0));
assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities().get(1));
assertEquals(new GrantedAuthorityImpl("ROLE_A"), casResult.getAuthorities()[0]);
assertEquals(new GrantedAuthorityImpl("ROLE_B"), casResult.getAuthorities()[1]);
assertEquals(cap.getKey().hashCode(), casResult.getKeyHash());
assertEquals("details", casResult.getDetails());
@@ -125,8 +124,8 @@ public class CasAuthenticationProviderTests {
cap.setServiceProperties(makeServiceProperties());
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER, "ST-456");
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER,
"ST-456");
token.setDetails("details");
Authentication result = cap.authenticate(token);
@@ -167,12 +166,12 @@ public class CasAuthenticationProviderTests {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, "");
cap.authenticate(token);
Authentication result = cap.authenticate(token);
}
@Test(expected = BadCredentialsException.class)
public void invalidKeyIsDetected() throws Exception {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationProvider cap = new CasAuthenticationProvider();
cap.setUserDetailsService(new MockAuthoritiesPopulator());
cap.setKey("qwerty");
@@ -184,7 +183,7 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet();
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion);
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), assertion);
cap.authenticate(token);
}
@@ -276,7 +275,7 @@ public class CasAuthenticationProviderTests {
cap.afterPropertiesSet();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
"password", AuthorityUtils.createAuthorityList("ROLE_A"));
"password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
assertEquals(null, cap.authenticate(token));
}
@@ -296,10 +295,10 @@ public class CasAuthenticationProviderTests {
}
private class MockStatelessTicketCache implements StatelessTicketCache {
private Map<String, CasAuthenticationToken> cache = new HashMap<String, CasAuthenticationToken>();
private Map cache = new HashMap();
public CasAuthenticationToken getByTicketId(String serviceTicket) {
return cache.get(serviceTicket);
return (CasAuthenticationToken) cache.get(serviceTicket);
}
public void putTicketInCache(CasAuthenticationToken token) {
@@ -323,11 +322,11 @@ public class CasAuthenticationProviderTests {
}
public Assertion validate(final String ticket, final String service)
throws TicketValidationException {
if (returnTicket) {
return new AssertionImpl("rod");
}
throw new BadCredentialsException("As requested from mock");
}
throws TicketValidationException {
if (returnTicket) {
return new AssertionImpl("rod");
}
throw new BadCredentialsException("As requested from mock");
}
}
}
@@ -15,17 +15,17 @@
package org.springframework.security.providers.cas;
import java.util.List;
import junit.framework.TestCase;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.userdetails.User;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.util.AuthorityUtils;
/**
* Tests {@link CasAuthenticationToken}.
@@ -34,14 +34,29 @@ import org.springframework.security.util.AuthorityUtils;
* @version $Id$
*/
public class CasAuthenticationTokenTests extends TestCase {
private final List<GrantedAuthority> ROLES = AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO");
//~ Constructors ===================================================================================================
public CasAuthenticationTokenTests() {
super();
}
public CasAuthenticationTokenTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CasAuthenticationTokenTests.class);
}
private UserDetails makeUserDetails() {
return makeUserDetails("user");
}
private UserDetails makeUserDetails(final String name) {
return new User(name, "password", true, true, true, true, ROLES);
return new User(name, "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
}
public final void setUp() throws Exception {
@@ -49,39 +64,64 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
try {
new CasAuthenticationToken(null, makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion);
new CasAuthenticationToken(null, makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", null, "Password", ROLES, makeUserDetails(), assertion);
new CasAuthenticationToken("key", null, "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), null, ROLES, makeUserDetails(), assertion);
new CasAuthenticationToken("key", makeUserDetails(), null,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, makeUserDetails(), null);
new CasAuthenticationToken("key", makeUserDetails(), "Password", null, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, null, assertion);
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion);
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
null, assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), null, new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
@@ -89,12 +129,14 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testEqualsWhenEqual() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
assertEquals(token1, token2);
@@ -102,21 +144,24 @@ public class CasAuthenticationTokenTests extends TestCase {
public void testGetters() {
// Build the proxy list returned in the ticket from CAS
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
assertEquals("key".hashCode(), token.getKeyHash());
assertEquals(makeUserDetails(), token.getPrincipal());
assertEquals("Password", token.getCredentials());
assertEquals("ROLE_ONE", token.getAuthorities().get(0).getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities().get(1).getAuthority());
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
assertEquals(assertion, token.getAssertion());
assertEquals(makeUserDetails().getUsername(), token.getUserDetails().getUsername());
}
public void testNoArgConstructorDoesntExist() {
Class clazz = CasAuthenticationToken.class;
try {
CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null);
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
} catch (NoSuchMethodException expected) {
assertTrue(true);
@@ -124,55 +169,65 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testNotEqualsDueToAbstractParentEqualsCheck() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password",
ROLES, makeUserDetails(), assertion);
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToDifferentAuthenticationClass() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password", ROLES);
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToKey() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password",
ROLES, makeUserDetails(), assertion);
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
assertTrue(!token1.equals(token2));
}
public void testNotEqualsDueToAssertion() {
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test");
final Assertion assertion = new AssertionImpl("test");
final Assertion assertion2 = new AssertionImpl("test");
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion2);
assertTrue(!token1.equals(token2));
}
public void testSetAuthenticated() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES,
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
assertTrue(token.isAuthenticated());
token.setAuthenticated(false);
@@ -180,8 +235,9 @@ public class CasAuthenticationTokenTests extends TestCase {
}
public void testToString() {
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",ROLES,
final Assertion assertion = new AssertionImpl("test");
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
makeUserDetails(), assertion);
String result = token.toString();
assertTrue(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1);
@@ -5,28 +5,31 @@ import java.util.List;
import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.AssertionImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.providers.cas.CasAuthenticationToken;
import org.springframework.security.userdetails.User;
import org.springframework.security.util.AuthorityUtils;
/**
*
*
* @author Scott Battaglia
* @version $Id$
* @version $Revision$ $Date$
* @since 2.0
*
*/
public abstract class AbstractStatelessTicketCacheTests {
protected CasAuthenticationToken getToken() {
protected CasAuthenticationToken getToken() {
List<String> proxyList = new ArrayList<String>();
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
User user = new User("rod", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
User user = new User("rod", "password", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
final Assertion assertion = new AssertionImpl("rod");
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion);
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
assertion);
}
}
@@ -30,18 +30,18 @@ import static org.junit.Assert.*;
*/
public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests {
private StatelessTicketCache cache = new NullStatelessTicketCache();
@Test
public void testGetter() {
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("test"));
}
@Test
public void testInsertAndGet() {
final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token);
assertNull(cache.getByTicketId((String) token.getCredentials()));
}
private StatelessTicketCache cache = new NullStatelessTicketCache();
@Test
public void testGetter() {
assertNull(cache.getByTicketId(null));
assertNull(cache.getByTicketId("test"));
}
@Test
public void testInsertAndGet() {
final CasAuthenticationToken token = getToken();
cache.putTicketInCache(token);
assertNull(cache.getByTicketId((String) token.getCredentials()));
}
}
@@ -22,7 +22,6 @@ import org.springframework.security.AuthenticationException;
import org.springframework.security.MockAuthenticationManager;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
@@ -32,11 +31,29 @@ import org.springframework.mock.web.MockHttpServletResponse;
* @version $Id$
*/
public class CasProcessingFilterTests extends TestCase {
//~ Constructors ===================================================================================================
public CasProcessingFilterTests() {
super();
}
public CasProcessingFilterTests(String arg0) {
super(arg0);
}
//~ Methods ========================================================================================================
public static void main(String[] args) {
junit.textui.TestRunner.run(CasProcessingFilterTests.class);
}
public final void setUp() throws Exception {
super.setUp();
}
public void testGetters() {
CasProcessingFilter filter = new CasProcessingFilter();
assertEquals("/j_spring_cas_security_check", filter.getFilterProcessesUrl());
assertEquals("/j_spring_cas_security_check", filter.getDefaultFilterProcessesUrl());
}
public void testNormalOperation() throws Exception {
@@ -49,7 +66,7 @@ public class CasProcessingFilterTests extends TestCase {
filter.setAuthenticationManager(authMgr);
filter.init(null);
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
Authentication result = filter.attemptAuthentication(request);
assertTrue(result != null);
}
@@ -64,7 +81,7 @@ public class CasProcessingFilterTests extends TestCase {
filter.init(null);
try {
filter.attemptAuthentication(request, new MockHttpServletResponse());
filter.attemptAuthentication(request);
fail("Should have thrown AuthenticationException");
} catch (AuthenticationException expected) {
assertTrue(true);
+5
View File
@@ -0,0 +1,5 @@
target
.settings
.classpath
.project
.wtpmodules
+106
View File
@@ -0,0 +1,106 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-parent</artifactId>
<version>2.0.2</version>
</parent>
<packaging>bundle</packaging>
<artifactId>spring-security-core-tiger</artifactId>
<name>Spring Security - Java 5 (Tiger)</name>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-support</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.14</version>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<configuration>
<targetJdk>1.5</targetJdk>
</configuration>
</plugin>
</plugins>
</reporting>
<properties>
<spring.osgi.export>
org.springframework.security.*;version=${pom.version}
</spring.osgi.export>
<spring.osgi.import>
javax.annotation.*;version="[1.0.0, 2.0.0)",
org.springframework.security.*;version="[${pom.version.osgi},${pom.version.osgi}]",
org.springframework.core.*;version="${spring.version.osgi}"
</spring.osgi.import>
<spring.osgi.private.pkg>
!org.springframework.security.*
</spring.osgi.private.pkg>
<spring.osgi.include.res>
src/main/resources
</spring.osgi.include.res>
<spring.osgi.symbolic.name>org.springframework.security.annotation</spring.osgi.symbolic.name>
</properties>
</project>
@@ -0,0 +1,76 @@
/* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* 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.springframework.security.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.intercept.method.AbstractFallbackMethodDefinitionSource;
/**
* Sources method security metadata from major JSR 250 security annotations.
*
* @author Ben Alex
* @version $Id$
* @since 2.0
*/
public class Jsr250MethodDefinitionSource extends AbstractFallbackMethodDefinitionSource {
protected ConfigAttributeDefinition findAttributes(Class clazz) {
return processAnnotations(clazz.getAnnotations());
}
protected ConfigAttributeDefinition findAttributes(Method method, Class targetClass) {
return processAnnotations(AnnotationUtils.getAnnotations(method));
}
public Collection getConfigAttributeDefinitions() {
return null;
}
private ConfigAttributeDefinition processAnnotations(Annotation[] annotations) {
if (annotations == null || annotations.length == 0) {
return null;
}
for (Annotation a: annotations) {
if (a instanceof DenyAll) {
return new ConfigAttributeDefinition(Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE);
}
if (a instanceof PermitAll) {
return new ConfigAttributeDefinition(Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE);
}
if (a instanceof RolesAllowed) {
RolesAllowed ra = (RolesAllowed) a;
List attributes = new ArrayList();
for (String allowed : ra.value()) {
attributes.add(new Jsr250SecurityConfig(allowed));
}
return new ConfigAttributeDefinition(attributes);
}
}
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More