SEC-674: Created new project modules for cas, captcha, acls and taglibs
This commit is contained in:
@@ -41,8 +41,6 @@ public class MockAclManager implements AclManager {
|
||||
this.acls = acls;
|
||||
}
|
||||
|
||||
private MockAclManager() {}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public AclEntry[] getAcls(Object domainInstance, Authentication authentication) {
|
||||
|
||||
@@ -39,8 +39,6 @@ public class MockPortResolver implements PortResolver {
|
||||
this.https = https;
|
||||
}
|
||||
|
||||
private MockPortResolver() {}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public int getServerPort(ServletRequest request) {
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
package org.springframework.security.acls;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests for {@link AclFormattingUtils}.
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
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", "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));
|
||||
|
||||
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", "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");
|
||||
}
|
||||
}
|
||||
|
||||
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'));
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
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), new 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,638 +0,0 @@
|
||||
package org.springframework.security.acls.domain;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
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;
|
||||
import org.springframework.security.acls.AuditableAccessControlEntry;
|
||||
import org.springframework.security.acls.AuditableAcl;
|
||||
import org.springframework.security.acls.ChildrenExistException;
|
||||
import org.springframework.security.acls.MutableAcl;
|
||||
import org.springframework.security.acls.MutableAclService;
|
||||
import org.springframework.security.acls.NotFoundException;
|
||||
import org.springframework.security.acls.OwnershipAcl;
|
||||
import org.springframework.security.acls.Permission;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentity;
|
||||
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.security.providers.TestingAuthenticationToken;
|
||||
import org.springframework.security.util.FieldUtils;
|
||||
|
||||
/**
|
||||
* Tests for {@link AclImpl}.
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
public class AclImplTests extends TestCase {
|
||||
// ~ Methods ========================================================================================================
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
try {
|
||||
Acl acl = new AclImpl(null, new Long(1), strategy, auditLogger);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public void testInsertAceRejectsNullParameters() 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));
|
||||
|
||||
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
|
||||
"johndoe"));
|
||||
try {
|
||||
acl.insertAce(new Long(1), null, new GrantedAuthoritySid("ROLE_IGNORED"), true);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
acl.insertAce(new Long(1), BasePermission.READ, null, true);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testInsertAceAddsElementAtCorrectIndex() 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));
|
||||
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(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
|
||||
service.updateAcl(acl);
|
||||
// Check it was successfully added
|
||||
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(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
|
||||
service.updateAcl(acl);
|
||||
// Check it was added on the last position
|
||||
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(acl.getEntries()[0].getId(), BasePermission.WRITE, new GrantedAuthoritySid("ROLE_TEST3"), false);
|
||||
service.updateAcl(acl);
|
||||
assertEquals(3, acl.getEntries().length);
|
||||
// Check the third entry was added between the two existent ones
|
||||
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"));
|
||||
}
|
||||
|
||||
public void testInsertAceFailsForInexistentElement() 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));
|
||||
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(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
|
||||
service.updateAcl(acl);
|
||||
|
||||
try {
|
||||
acl.insertAce(new Long(5), BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
|
||||
fail("It should have thrown NotFoundException");
|
||||
}
|
||||
catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeleteAceKeepsInitialOrdering() 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));
|
||||
MutableAcl acl = new AclImpl(identity, new Long(1), strategy, auditLogger, null, null, true, new PrincipalSid(
|
||||
"johndoe"));
|
||||
MockAclService service = new MockAclService();
|
||||
|
||||
// Add several permissions
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST1"), true);
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST2"), true);
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST3"), true);
|
||||
service.updateAcl(acl);
|
||||
|
||||
// Delete first permission and check the order of the remaining permissions is kept
|
||||
acl.deleteAce(new Long(1));
|
||||
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(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_TEST4"), true);
|
||||
service.updateAcl(acl);
|
||||
acl.deleteAce(new Long(2));
|
||||
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(new Long(1));
|
||||
acl.deleteAce(new Long(3));
|
||||
assertEquals(0, acl.getEntries().length);
|
||||
}
|
||||
|
||||
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();
|
||||
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(new Long(1));
|
||||
fail("It should have thrown NotFoundException");
|
||||
}
|
||||
catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testIsGrantingRejectsEmptyParameters() throws Exception {
|
||||
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.isGranted(new Permission[] {}, new Sid[] { new PrincipalSid("ben") }, false);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
acl.isGranted(new Permission[] { BasePermission.READ }, new Sid[] {}, false);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testIsGrantingGrantsAccessForAclWithNoParent() throws Exception {
|
||||
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), strategy, auditLogger, null, null, false, new PrincipalSid(
|
||||
"johndoe"));
|
||||
|
||||
// Grant some permissions
|
||||
rootAcl.insertAce(null, BasePermission.READ, new PrincipalSid("ben"), false);
|
||||
rootAcl.insertAce(null, BasePermission.WRITE, new PrincipalSid("scott"), true);
|
||||
rootAcl.insertAce(null, BasePermission.WRITE, new PrincipalSid("rod"), false);
|
||||
rootAcl.insertAce(null, BasePermission.WRITE, new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), true);
|
||||
|
||||
// Check permissions granting
|
||||
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, new Sid[] { new PrincipalSid("scott") }, false);
|
||||
fail("It should have thrown NotFoundException");
|
||||
}
|
||||
catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
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(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);
|
||||
}
|
||||
}
|
||||
|
||||
public void testIsGrantingGrantsAccessForInheritableAcls() 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_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));
|
||||
ObjectIdentity childOid1 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(103));
|
||||
ObjectIdentity childOid2 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(104));
|
||||
|
||||
// Create ACLs
|
||||
MutableAcl grandParentAcl = new AclImpl(grandParentOid, new Long(1), strategy, auditLogger, null, null, false,
|
||||
new PrincipalSid("johndoe"));
|
||||
MutableAcl parentAcl1 = new AclImpl(parentOid1, new Long(2), strategy, auditLogger, null, null, true,
|
||||
new PrincipalSid("johndoe"));
|
||||
MutableAcl parentAcl2 = new AclImpl(parentOid2, new Long(3), strategy, auditLogger, null, null, true,
|
||||
new PrincipalSid("johndoe"));
|
||||
MutableAcl childAcl1 = new AclImpl(childOid1, new Long(4), strategy, auditLogger, null, null, true,
|
||||
new PrincipalSid("johndoe"));
|
||||
MutableAcl childAcl2 = new AclImpl(childOid2, new Long(4), strategy, auditLogger, null, null, false,
|
||||
new PrincipalSid("johndoe"));
|
||||
|
||||
// Create hierarchies
|
||||
childAcl2.setParent(childAcl1);
|
||||
childAcl1.setParent(parentAcl1);
|
||||
parentAcl2.setParent(grandParentAcl);
|
||||
parentAcl1.setParent(grandParentAcl);
|
||||
|
||||
// Add some permissions
|
||||
grandParentAcl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
grandParentAcl.insertAce(null, BasePermission.WRITE, new PrincipalSid("ben"), true);
|
||||
grandParentAcl.insertAce(null, BasePermission.DELETE, new PrincipalSid("ben"), false);
|
||||
grandParentAcl.insertAce(null, BasePermission.DELETE, new PrincipalSid("scott"), true);
|
||||
parentAcl1.insertAce(null, BasePermission.READ, new PrincipalSid("scott"), true);
|
||||
parentAcl1.insertAce(null, BasePermission.DELETE, new PrincipalSid("scott"), false);
|
||||
parentAcl2.insertAce(null, BasePermission.CREATE, new PrincipalSid("ben"), true);
|
||||
childAcl1.insertAce(null, BasePermission.CREATE, new PrincipalSid("scott"), true);
|
||||
|
||||
// Check granting process for parent1
|
||||
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(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(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));
|
||||
|
||||
// Check granting process for child2 (doesn't inherit the permissions from its parent)
|
||||
try {
|
||||
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(new Permission[] { BasePermission.CREATE }, new Sid[] { new PrincipalSid(
|
||||
"johndoe") }, false));
|
||||
fail("It should have thrown NotFoundException");
|
||||
}
|
||||
catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testUpdateAce() 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_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();
|
||||
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
acl.insertAce(null, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
acl.insertAce(null, BasePermission.CREATE, new PrincipalSid("ben"), true);
|
||||
service.updateAcl(acl);
|
||||
|
||||
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(new Long(1), BasePermission.CREATE);
|
||||
acl.updateAce(new Long(2), BasePermission.DELETE);
|
||||
acl.updateAce(new Long(3), BasePermission.READ);
|
||||
|
||||
// Check the change was successfuly made
|
||||
assertEquals(acl.getEntries()[0].getPermission(), BasePermission.CREATE);
|
||||
assertEquals(acl.getEntries()[1].getPermission(), BasePermission.DELETE);
|
||||
assertEquals(acl.getEntries()[2].getPermission(), BasePermission.READ);
|
||||
}
|
||||
|
||||
public void testUpdateAuditing() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken("ben", "ignored", new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_AUDITING"), 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 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();
|
||||
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
acl.insertAce(null, BasePermission.WRITE, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
service.updateAcl(acl);
|
||||
|
||||
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(new Long(1), true, true);
|
||||
((AuditableAcl) acl).updateAuditing(new Long(2), true, true);
|
||||
|
||||
// Check the change was successfuly made
|
||||
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditFailure());
|
||||
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditFailure());
|
||||
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[0]).isAuditSuccess());
|
||||
assertTrue(((AuditableAccessControlEntry) acl.getEntries()[1]).isAuditSuccess());
|
||||
}
|
||||
|
||||
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), strategy, auditLogger, null, null, true, new PrincipalSid(
|
||||
"johndoe"));
|
||||
MutableAcl parentAcl = new AclImpl(identity2, new Long(2), strategy, auditLogger, null, null, true, new PrincipalSid(
|
||||
"johndoe"));
|
||||
MockAclService service = new MockAclService();
|
||||
acl.insertAce(null, BasePermission.READ, new GrantedAuthoritySid("ROLE_USER_READ"), true);
|
||||
acl.insertAce(null, 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().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"));
|
||||
}
|
||||
|
||||
public void testIsSidLoaded() throws Exception {
|
||||
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(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 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 ==================================================================================================
|
||||
|
||||
private class MockAclService implements MutableAclService {
|
||||
public MutableAcl createAcl(ObjectIdentity objectIdentity) throws AlreadyExistsException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void deleteAcl(ObjectIdentity objectIdentity, boolean deleteChildren) throws ChildrenExistException {
|
||||
}
|
||||
|
||||
/*
|
||||
* Mock implementation that populates the aces list with fully initialized AccessControlEntries
|
||||
* @see org.springframework.security.acls.MutableAclService#updateAcl(org.springframework.security.acls.MutableAcl)
|
||||
*/
|
||||
public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException {
|
||||
AccessControlEntry[] oldAces = acl.getEntries();
|
||||
Field acesField = FieldUtils.getField(AclImpl.class, "aces");
|
||||
acesField.setAccessible(true);
|
||||
List newAces;
|
||||
try {
|
||||
newAces = (List) acesField.get(acl);
|
||||
newAces.clear();
|
||||
|
||||
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(),
|
||||
((AuditableAccessControlEntry) ac).isAuditFailure()));
|
||||
}
|
||||
}
|
||||
catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return acl;
|
||||
}
|
||||
|
||||
public ObjectIdentity[] findChildren(ObjectIdentity parentIdentity) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Acl readAclById(ObjectIdentity object) throws NotFoundException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Acl readAclById(ObjectIdentity object, Sid[] sids) throws NotFoundException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Map readAclsById(ObjectIdentity[] objects) throws NotFoundException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Map readAclsById(ObjectIdentity[] objects, Sid[] sids) throws NotFoundException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
-296
@@ -1,296 +0,0 @@
|
||||
package org.springframework.security.acls.domain;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.AccessDeniedException;
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.acls.Acl;
|
||||
import org.springframework.security.acls.MutableAcl;
|
||||
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.PrincipalSid;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
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 ========================================================================================================
|
||||
|
||||
protected void setUp() 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);
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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") });
|
||||
|
||||
// Let's give the principal the ADMINISTRATION permission, without
|
||||
// granting access
|
||||
MutableAcl aclFirstDeny = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||
aclFirstDeny.insertAce(null, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// Add granting access to this principal
|
||||
aclFirstDeny.insertAce(null, 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);
|
||||
}
|
||||
|
||||
// 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(null, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
|
||||
|
||||
// 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 a deny ACE and test again for CHANGE_AUDITING
|
||||
aclFirstAllow.insertAce(null, 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 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");
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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") });
|
||||
|
||||
// Let's give the principal an ADMINISTRATION permission, with granting
|
||||
// access
|
||||
MutableAcl parentAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||
parentAcl.insertAce(null, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
|
||||
MutableAcl childAcl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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(null, 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
package org.springframework.security.acls.domain;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
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.Permission;
|
||||
import org.springframework.security.acls.sid.Sid;
|
||||
|
||||
/**
|
||||
* Test class for {@link ConsoleAuditLogger}.
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
public class AuditLoggerTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private PrintStream console;
|
||||
|
||||
private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void setUp() throws Exception {
|
||||
console = System.out;
|
||||
System.setOut(new PrintStream(bytes));
|
||||
}
|
||||
|
||||
public void tearDown() throws Exception {
|
||||
System.setOut(console);
|
||||
}
|
||||
|
||||
public void testLoggingTests() throws Exception {
|
||||
ConsoleAuditLogger logger = new ConsoleAuditLogger();
|
||||
MockAccessControlEntryImpl auditableAccessControlEntry = new MockAccessControlEntryImpl();
|
||||
|
||||
logger.logIfNeeded(true, auditableAccessControlEntry);
|
||||
Assert.assertTrue(bytes.size() == 0);
|
||||
|
||||
bytes.reset();
|
||||
logger.logIfNeeded(false, auditableAccessControlEntry);
|
||||
Assert.assertTrue(bytes.size() == 0);
|
||||
|
||||
auditableAccessControlEntry.setAuditSuccess(true);
|
||||
bytes.reset();
|
||||
|
||||
logger.logIfNeeded(true, auditableAccessControlEntry);
|
||||
Assert.assertTrue(bytes.toString().length() > 0);
|
||||
Assert.assertTrue(bytes.toString().startsWith("GRANTED 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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
/* 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.acls.domain;
|
||||
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
import org.junit.Test;
|
||||
import org.springframework.security.acls.Permission;
|
||||
|
||||
|
||||
/**
|
||||
* Tests BasePermission and CumulativePermission.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id${date}
|
||||
*/
|
||||
public class PermissionTests {
|
||||
private static final Log LOGGER = LogFactory.getLog(PermissionTests.class);
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void expectedIntegerValues() {
|
||||
assertEquals(1, BasePermission.READ.getMask());
|
||||
assertEquals(16, BasePermission.ADMINISTRATION.getMask());
|
||||
assertEquals(7,
|
||||
new CumulativePermission().set(BasePermission.READ).set(BasePermission.WRITE).set(BasePermission.CREATE)
|
||||
.getMask());
|
||||
assertEquals(17,
|
||||
new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION).getMask());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fromInteger() {
|
||||
Permission permission = BasePermission.buildFromMask(7);
|
||||
System.out.println("7 = " + permission.toString());
|
||||
permission = BasePermission.buildFromMask(4);
|
||||
System.out.println("4 = " + permission.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stringConversion() {
|
||||
System.out.println("R = " + BasePermission.READ.toString());
|
||||
assertEquals("BasePermission[...............................R=1]", BasePermission.READ.toString());
|
||||
|
||||
System.out.println("A = " + BasePermission.ADMINISTRATION.toString());
|
||||
assertEquals("BasePermission[...........................A....=16]", BasePermission.ADMINISTRATION.toString());
|
||||
|
||||
System.out.println("R = " + new CumulativePermission().set(BasePermission.READ).toString());
|
||||
assertEquals("CumulativePermission[...............................R=1]",
|
||||
new CumulativePermission().set(BasePermission.READ).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());
|
||||
assertEquals("CumulativePermission[...........................A...R=17]",
|
||||
new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ).toString());
|
||||
|
||||
System.out.println("R = "
|
||||
+ new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
|
||||
.clear(BasePermission.ADMINISTRATION).toString());
|
||||
assertEquals("CumulativePermission[...............................R=1]",
|
||||
new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
|
||||
.clear(BasePermission.ADMINISTRATION).toString());
|
||||
|
||||
System.out.println("0 = "
|
||||
+ new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
|
||||
.clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString());
|
||||
assertEquals("CumulativePermission[................................=0]",
|
||||
new CumulativePermission().set(BasePermission.ADMINISTRATION).set(BasePermission.READ)
|
||||
.clear(BasePermission.ADMINISTRATION).clear(BasePermission.READ).toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
-294
@@ -1,294 +0,0 @@
|
||||
package org.springframework.security.acls.jdbc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import net.sf.ehcache.Ehcache;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.MockApplicationContext;
|
||||
import org.springframework.security.TestDataSource;
|
||||
import org.springframework.security.acls.Acl;
|
||||
import org.springframework.security.acls.AuditableAccessControlEntry;
|
||||
import org.springframework.security.acls.MutableAcl;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
|
||||
import org.springframework.security.acls.domain.BasePermission;
|
||||
import org.springframework.security.acls.domain.ConsoleAuditLogger;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentity;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
|
||||
import org.springframework.security.acls.sid.PrincipalSid;
|
||||
import org.springframework.security.acls.sid.Sid;
|
||||
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;
|
||||
|
||||
// ~ Methods ========================================================================================================
|
||||
|
||||
@BeforeClass
|
||||
public static void createDatabase() throws Exception {
|
||||
dataSource = new TestDataSource("lookupstrategytest");
|
||||
jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
|
||||
Resource resource = new ClassPathResource("org/springframework/security/acls/jdbc/testData.sql");
|
||||
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
|
||||
jdbcTemplate.execute(sql);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void dropDatabase() throws Exception {
|
||||
dataSource.destroy();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void populateDatabase() {
|
||||
String query = "INSERT INTO acl_sid(ID,PRINCIPAL,SID) VALUES (1,1,'ben');"
|
||||
+ "INSERT INTO acl_class(ID,CLASS) VALUES (2,'org.springframework.security.TargetObject');"
|
||||
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (1,2,100,null,1,1);"
|
||||
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (2,2,101,1,1,1);"
|
||||
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (3,2,102,2,1,1);"
|
||||
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (1,1,0,1,1,1,0,0);"
|
||||
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (2,1,1,1,2,0,0,0);"
|
||||
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (3,2,0,1,8,1,0,0);"
|
||||
+ "INSERT INTO acl_entry(ID,ACL_OBJECT_IDENTITY,ACE_ORDER,SID,MASK,GRANTING,AUDIT_SUCCESS,AUDIT_FAILURE) VALUES (4,3,0,1,8,0,0,0);";
|
||||
jdbcTemplate.execute(query);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void initializeBeans() {
|
||||
EhCacheBasedAclCache cache = new EhCacheBasedAclCache(getCache());
|
||||
AclAuthorizationStrategy authorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_ADMINISTRATOR"), new GrantedAuthorityImpl("ROLE_ADMINISTRATOR"),
|
||||
new GrantedAuthorityImpl("ROLE_ADMINISTRATOR") });
|
||||
strategy = new BasicLookupStrategy(dataSource, cache, authorizationStrategy, new ConsoleAuditLogger());
|
||||
}
|
||||
|
||||
@After
|
||||
public void emptyDatabase() {
|
||||
String query = "DELETE FROM acl_entry;" + "DELETE FROM acl_object_identity WHERE ID = 7;"
|
||||
+ "DELETE FROM acl_object_identity WHERE ID = 6;" + "DELETE FROM acl_object_identity WHERE ID = 5;"
|
||||
+ "DELETE FROM acl_object_identity WHERE ID = 4;" + "DELETE FROM acl_object_identity WHERE ID = 3;"
|
||||
+ "DELETE FROM acl_object_identity WHERE ID = 2;" + "DELETE FROM acl_object_identity WHERE ID = 1;"
|
||||
+ "DELETE FROM acl_class;" + "DELETE FROM acl_sid;";
|
||||
jdbcTemplate.execute(query);
|
||||
}
|
||||
|
||||
private Ehcache getCache() {
|
||||
ApplicationContext ctx = MockApplicationContext.getContext();
|
||||
return (Ehcache) ctx.getBean("eHCacheBackend");
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102));
|
||||
|
||||
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 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(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
|
||||
|
||||
// Let's empty the database to force acls retrieval from cache
|
||||
emptyDatabase();
|
||||
Map map = this.strategy.readAclsById(new ObjectIdentity[] { topParentOid, middleParentOid, childOid }, null);
|
||||
|
||||
checkEntries(topParentOid, middleParentOid, childOid, map);
|
||||
}
|
||||
|
||||
@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 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 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 map)
|
||||
throws Exception {
|
||||
Assert.assertEquals(3, map.size());
|
||||
|
||||
MutableAcl topParent = (MutableAcl) map.get(topParentOid);
|
||||
MutableAcl middleParent = (MutableAcl) map.get(middleParentOid);
|
||||
MutableAcl child = (MutableAcl) map.get(childOid);
|
||||
|
||||
// Check the retrieved versions has IDs
|
||||
Assert.assertNotNull(topParent.getId());
|
||||
Assert.assertNotNull(middleParent.getId());
|
||||
Assert.assertNotNull(child.getId());
|
||||
|
||||
// Check their parents were correctly retrieved
|
||||
Assert.assertNull(topParent.getParentAcl());
|
||||
Assert.assertEquals(topParentOid, middleParent.getParentAcl().getObjectIdentity());
|
||||
Assert.assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
|
||||
|
||||
// Check their ACEs were correctly retrieved
|
||||
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());
|
||||
Assert.assertEquals(middleParentOid, middleParent.getObjectIdentity());
|
||||
Assert.assertEquals(childOid, child.getObjectIdentity());
|
||||
|
||||
// Check each entry
|
||||
Assert.assertTrue(topParent.isEntriesInheriting());
|
||||
Assert.assertEquals(topParent.getId(), new Long(1));
|
||||
Assert.assertEquals(topParent.getOwner(), new PrincipalSid("ben"));
|
||||
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()[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()[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()[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(((AuditableAccessControlEntry) 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 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 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());
|
||||
Assert.assertNotNull(map.get(middleParentOid));
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test created from SEC-590.
|
||||
*/
|
||||
/* @Test
|
||||
public void testReadAllObjectIdentitiesWhenLastElementIsAlreadyCached() 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_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (5,2,105,4,1,1);"
|
||||
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (6,2,106,4,1,1);"
|
||||
+ "INSERT INTO acl_object_identity(ID,OBJECT_ID_CLASS,OBJECT_ID_IDENTITY,PARENT_OBJECT,OWNER_SID,ENTRIES_INHERITING) VALUES (7,2,107,5,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 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 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
|
||||
Permission[] checkPermission = new Permission[] { BasePermission.READ };
|
||||
Sid[] sids = new Sid[] { new PrincipalSid("ben") };
|
||||
ObjectIdentity[] childOids = new ObjectIdentity[] { childOid };
|
||||
|
||||
((BasicLookupStrategy) this.strategy).setBatchSize(6);
|
||||
Map foundAcls = strategy.readAclsById(childOids, sids);
|
||||
|
||||
Acl foundChildAcl = (Acl) foundAcls.get(childOid);
|
||||
Assert.assertNotNull(foundChildAcl);
|
||||
Assert.assertTrue(foundChildAcl.isGranted(checkPermission, sids, false));
|
||||
|
||||
// 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
|
||||
ObjectIdentity[] allOids = new ObjectIdentity[] { grandParentOid, parent1Oid, parent2Oid, childOid };
|
||||
try {
|
||||
foundAcls = strategy.readAclsById(allOids, sids);
|
||||
Assert.assertTrue(true);
|
||||
} catch (NotFoundException notExpected) {
|
||||
Assert.fail("It shouldn't have thrown NotFoundException");
|
||||
}
|
||||
|
||||
Acl foundParent2Acl = (Acl) foundAcls.get(parent2Oid);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
/* 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.acls.jdbc;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
|
||||
/**
|
||||
* Seeds the database for {@link JdbcAclServiceTests}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class DatabaseSeeder {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public DatabaseSeeder(DataSource dataSource, Resource resource)
|
||||
throws IOException {
|
||||
Assert.notNull(dataSource, "dataSource required");
|
||||
Assert.notNull(resource, "resource required");
|
||||
|
||||
JdbcTemplate template = new JdbcTemplate(dataSource);
|
||||
String sql = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
|
||||
template.execute(sql);
|
||||
}
|
||||
}
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
package org.springframework.security.acls.jdbc;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
import net.sf.ehcache.Cache;
|
||||
import net.sf.ehcache.Ehcache;
|
||||
|
||||
import org.springframework.context.support.AbstractXmlApplicationContext;
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.MockApplicationContext;
|
||||
import org.springframework.security.acls.MutableAcl;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategy;
|
||||
import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl;
|
||||
import org.springframework.security.acls.domain.AclImpl;
|
||||
import org.springframework.security.acls.domain.ConsoleAuditLogger;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentity;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
/**
|
||||
* Tests {@link EhCacheBasedAclCache}
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
public class EhCacheBasedAclCacheTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
AbstractXmlApplicationContext ctx;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
private Ehcache getCache() {
|
||||
this.ctx = (AbstractXmlApplicationContext) MockApplicationContext.getContext();
|
||||
|
||||
return (Ehcache) ctx.getBean("eHCacheBackend");
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
super.tearDown();
|
||||
SecurityContextHolder.clearContext();
|
||||
if (ctx != null) {
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void testConstructorRejectsNullParameters() throws Exception {
|
||||
try {
|
||||
AclCache aclCache = new EhCacheBasedAclCache(null);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testMethodsRejectNullParameters() throws Exception {
|
||||
Ehcache cache = new MockEhcache();
|
||||
EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache);
|
||||
|
||||
try {
|
||||
Serializable id = null;
|
||||
myCache.evictFromCache(id);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
ObjectIdentity obj = null;
|
||||
myCache.evictFromCache(obj);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Serializable id = null;
|
||||
myCache.getFromCache(id);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
ObjectIdentity obj = null;
|
||||
myCache.getFromCache(obj);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
MutableAcl acl = null;
|
||||
myCache.putInCache(acl);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCacheOperationsAclWithoutParent() throws Exception {
|
||||
Ehcache cache = getCache();
|
||||
EhCacheBasedAclCache myCache = new EhCacheBasedAclCache(cache);
|
||||
|
||||
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") });
|
||||
MutableAcl acl = new AclImpl(identity, new Long(1), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||
|
||||
myCache.putInCache(acl);
|
||||
Assert.assertEquals(cache.getSize(), 2);
|
||||
|
||||
// Check we can get from cache the same objects we put in
|
||||
Assert.assertEquals(myCache.getFromCache(new Long(1)), acl);
|
||||
Assert.assertEquals(myCache.getFromCache(identity), acl);
|
||||
|
||||
// Put another object in cache
|
||||
ObjectIdentity identity2 = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
|
||||
MutableAcl acl2 = new AclImpl(identity2, new Long(2), aclAuthorizationStrategy, new ConsoleAuditLogger());
|
||||
|
||||
myCache.putInCache(acl2);
|
||||
Assert.assertEquals(cache.getSize(), 4);
|
||||
|
||||
// Try to evict an entry that doesn't exist
|
||||
myCache.evictFromCache(new Long(3));
|
||||
myCache.evictFromCache(new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(102)));
|
||||
Assert.assertEquals(cache.getSize(), 4);
|
||||
|
||||
myCache.evictFromCache(new Long(1));
|
||||
Assert.assertEquals(cache.getSize(), 2);
|
||||
|
||||
// Check the second object inserted
|
||||
Assert.assertEquals(myCache.getFromCache(new Long(2)), acl2);
|
||||
Assert.assertEquals(myCache.getFromCache(identity2), acl2);
|
||||
|
||||
myCache.evictFromCache(identity2);
|
||||
Assert.assertEquals(cache.getSize(), 0);
|
||||
}
|
||||
|
||||
public void testCacheOperationsAclWithParent() 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);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
ObjectIdentity identity = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
|
||||
ObjectIdentity identityParent = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(101));
|
||||
AclAuthorizationStrategy aclAuthorizationStrategy = new AclAuthorizationStrategyImpl(new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_OWNERSHIP"), new GrantedAuthorityImpl("ROLE_AUDITING"),
|
||||
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);
|
||||
|
||||
myCache.putInCache(acl);
|
||||
Assert.assertEquals(cache.getSize(), 4);
|
||||
|
||||
// Check we can get from cache the same objects we put in
|
||||
Assert.assertEquals(myCache.getFromCache(new Long(1)), acl);
|
||||
Assert.assertEquals(myCache.getFromCache(identity), acl);
|
||||
Assert.assertEquals(myCache.getFromCache(new Long(2)), parentAcl);
|
||||
Assert.assertEquals(myCache.getFromCache(identityParent), parentAcl);
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockEhcache extends Cache {
|
||||
public MockEhcache() {
|
||||
super("cache", 0, true, true, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
/* 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.acls.jdbc;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
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.AlreadyExistsException;
|
||||
import org.springframework.security.acls.ChildrenExistException;
|
||||
import org.springframework.security.acls.MutableAcl;
|
||||
import org.springframework.security.acls.NotFoundException;
|
||||
import org.springframework.security.acls.Permission;
|
||||
import org.springframework.security.acls.domain.AclImpl;
|
||||
import org.springframework.security.acls.domain.BasePermission;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentity;
|
||||
import org.springframework.security.acls.objectidentity.ObjectIdentityImpl;
|
||||
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.AbstractTransactionalDataSourceSpringContextTests;
|
||||
|
||||
|
||||
/**
|
||||
* Integration tests the ACL system using an in-memory database.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @author Andrei Stefan
|
||||
* @version $Id:JdbcAclServiceTests.java 1754 2006-11-17 02:01:21Z benalex $
|
||||
*/
|
||||
public class JdbcAclServiceTests extends AbstractTransactionalDataSourceSpringContextTests {
|
||||
//~ Constant fields ================================================================================================
|
||||
|
||||
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 JdbcMutableAclService jdbcMutableAclService;
|
||||
|
||||
private AclCache aclCache;
|
||||
|
||||
private LookupStrategy lookupStrategy;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected String[] getConfigLocations() {
|
||||
return new String[] {"classpath:org/springframework/security/acls/jdbc/applicationContext-test.xml"};
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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 inheritence hierarchy
|
||||
middleParent.setParent(topParent);
|
||||
child.setParent(middleParent);
|
||||
|
||||
// Now let's add a couple of permissions
|
||||
topParent.insertAce(null, BasePermission.READ, new PrincipalSid(auth), true);
|
||||
topParent.insertAce(null, BasePermission.WRITE, new PrincipalSid(auth), false);
|
||||
middleParent.insertAce(null, BasePermission.DELETE, new PrincipalSid(auth), true);
|
||||
child.insertAce(null, BasePermission.DELETE, new PrincipalSid(auth), false);
|
||||
|
||||
// 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 map = jdbcMutableAclService.readAclsById(new ObjectIdentity[] {topParentOid, middleParentOid, childOid});
|
||||
assertEquals(3, map.size());
|
||||
|
||||
// Replace our current objects with their retrieved versions
|
||||
topParent = (MutableAcl) map.get(topParentOid);
|
||||
middleParent = (MutableAcl) map.get(middleParentOid);
|
||||
child = (MutableAcl) map.get(childOid);
|
||||
|
||||
// Check the retrieved versions has IDs
|
||||
assertNotNull(topParent.getId());
|
||||
assertNotNull(middleParent.getId());
|
||||
assertNotNull(child.getId());
|
||||
|
||||
// Check their parents were correctly persisted
|
||||
assertNull(topParent.getParentAcl());
|
||||
assertEquals(topParentOid, middleParent.getParentAcl().getObjectIdentity());
|
||||
assertEquals(middleParentOid, child.getParentAcl().getObjectIdentity());
|
||||
|
||||
// Check their ACEs were correctly persisted
|
||||
assertEquals(2, topParent.getEntries().length);
|
||||
assertEquals(1, middleParent.getEntries().length);
|
||||
assertEquals(1, child.getEntries().length);
|
||||
|
||||
// Check the retrieved rights are correct
|
||||
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(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(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);
|
||||
jdbcMutableAclService.updateAcl(child);
|
||||
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
|
||||
assertFalse(child.isEntriesInheriting());
|
||||
|
||||
// Check the child permissions no longer inherit
|
||||
assertFalse(child.isGranted(new Permission[] {BasePermission.DELETE}, new Sid[] {new PrincipalSid(auth)}, true));
|
||||
|
||||
try {
|
||||
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(new Permission[] {BasePermission.WRITE}, new Sid[] {new PrincipalSid(auth)}, true);
|
||||
fail("Should have thrown NotFoundException");
|
||||
} catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
// Let's add an identical permission to the child, but it'll appear AFTER the current permission, so has no impact
|
||||
child.insertAce(null, BasePermission.DELETE, new PrincipalSid(auth), true);
|
||||
|
||||
// Let's also add another permission to the child
|
||||
child.insertAce(null, BasePermission.CREATE, new PrincipalSid(auth), true);
|
||||
|
||||
// Save the changed child
|
||||
jdbcMutableAclService.updateAcl(child);
|
||||
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
|
||||
assertEquals(3, child.getEntries().length);
|
||||
|
||||
// Output permissions
|
||||
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(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()[0];
|
||||
assertEquals(BasePermission.DELETE.getMask(), entry.getPermission().getMask());
|
||||
assertEquals(new PrincipalSid(auth), entry.getSid());
|
||||
assertFalse(entry.isGranting());
|
||||
assertNotNull(entry.getId());
|
||||
|
||||
// Now delete that first ACE
|
||||
child.deleteAce(entry.getId());
|
||||
|
||||
// Save and check it worked
|
||||
child = jdbcMutableAclService.updateAcl(child);
|
||||
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
|
||||
*/
|
||||
/* public void testDeleteAclAlsoDeletesChildren() throws Exception {
|
||||
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));
|
||||
|
||||
// Delete the mid-parent and test if the child was deleted, as well
|
||||
jdbcMutableAclService.deleteAcl(middleParentOid, true);
|
||||
|
||||
try {
|
||||
Acl acl = jdbcMutableAclService.readAclById(middleParentOid);
|
||||
fail("It should have thrown NotFoundException");
|
||||
}
|
||||
catch (NotFoundException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
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);
|
||||
}*/
|
||||
|
||||
public void testConstructorRejectsNullParameters() throws Exception {
|
||||
try {
|
||||
JdbcAclService service = new JdbcMutableAclService(null, lookupStrategy, aclCache);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
JdbcAclService service = new JdbcMutableAclService(this.getJdbcTemplate().getDataSource(), null, aclCache);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
JdbcAclService service = new JdbcMutableAclService(this.getJdbcTemplate().getDataSource(), lookupStrategy, null);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCreateAclRejectsNullParameter() throws Exception {
|
||||
try {
|
||||
jdbcMutableAclService.createAcl(null);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCreateAclForADuplicateDomainObject() throws Exception {
|
||||
ObjectIdentity duplicateOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
|
||||
|
||||
// Try to add the same object second time
|
||||
try {
|
||||
jdbcMutableAclService.createAcl(duplicateOid);
|
||||
fail("It should have thrown AlreadyExistsException");
|
||||
}
|
||||
catch (AlreadyExistsException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeleteAclRejectsNullParameters() throws Exception {
|
||||
try {
|
||||
jdbcMutableAclService.deleteAcl(null, true);
|
||||
fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeleteAclWithChildrenThrowsException() throws Exception {
|
||||
try {
|
||||
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(100));
|
||||
jdbcMutableAclService.deleteAcl(topParentOid, false);
|
||||
fail("It should have thrown ChildrenExistException");
|
||||
}
|
||||
catch (ChildrenExistException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testDeleteAllAclsRemovesAclClassRecord() throws Exception {
|
||||
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));
|
||||
|
||||
// Remove all acls associated with a certain class type
|
||||
jdbcMutableAclService.deleteAcl(topParentOid, true);
|
||||
|
||||
// Check the acl_class table is empty
|
||||
assertEquals(0, getJdbcTemplate().queryForList(SELECT_ALL_CLASSES, new Object[] {"org.springframework.security.TargetObject"} ).size());
|
||||
}
|
||||
|
||||
public void testDeleteAclRemovesRowsFromDatabase() throws Exception {
|
||||
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));
|
||||
|
||||
// Remove the child and check all related database rows were removed accordingly
|
||||
jdbcMutableAclService.deleteAcl(childOid, false);
|
||||
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
|
||||
*/
|
||||
/* public void testClearChildrenFromCacheWhenParentIsUpdated() throws Exception {
|
||||
Authentication auth = new TestingAuthenticationToken("ben", "ignored",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADMINISTRATOR")});
|
||||
auth.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
ObjectIdentity parentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(104));
|
||||
ObjectIdentity childOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(105));
|
||||
|
||||
MutableAcl parent = jdbcMutableAclService.createAcl(parentOid);
|
||||
MutableAcl child = jdbcMutableAclService.createAcl(childOid);
|
||||
|
||||
child.setParent(parent);
|
||||
jdbcMutableAclService.updateAcl(child);
|
||||
|
||||
parent = (AclImpl) jdbcMutableAclService.readAclById(parentOid);
|
||||
parent.insertAce(null, BasePermission.READ, new PrincipalSid("ben"), true);
|
||||
jdbcMutableAclService.updateAcl(parent);
|
||||
|
||||
parent = (AclImpl) jdbcMutableAclService.readAclById(parentOid);
|
||||
parent.insertAce(null, BasePermission.READ, new PrincipalSid("scott"), true);
|
||||
jdbcMutableAclService.updateAcl(parent);
|
||||
|
||||
child = (MutableAcl) jdbcMutableAclService.readAclById(childOid);
|
||||
parent = (MutableAcl) child.getParentAcl();
|
||||
|
||||
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")});
|
||||
auth.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
ObjectIdentity topParentOid = new ObjectIdentityImpl("org.springframework.security.TargetObject", new Long(110));
|
||||
MutableAcl topParent = jdbcMutableAclService.createAcl(topParentOid);
|
||||
|
||||
// Add an ACE permission entry
|
||||
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().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}, new Sid[] {new PrincipalSid(auth)}, true));
|
||||
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
*/
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package org.springframework.security.acls.objectidentity;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests for {@link ObjectIdentityRetrievalStrategyImpl}
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
public class ObjectIdentityRetrievalStrategyImplTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void testObjectIdentityCreation() throws Exception {
|
||||
MockIdDomainObject domain = new MockIdDomainObject();
|
||||
domain.setId(new Integer(1));
|
||||
|
||||
ObjectIdentityRetrievalStrategy retStrategy = new ObjectIdentityRetrievalStrategyImpl();
|
||||
ObjectIdentity identity = retStrategy.getObjectIdentity(domain);
|
||||
|
||||
assertNotNull(identity);
|
||||
assertEquals(identity, new ObjectIdentityImpl(domain));
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockIdDomainObject {
|
||||
private Object id;
|
||||
|
||||
public Object getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Object id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
package org.springframework.security.acls.objectidentity;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.acls.IdentityUnavailableException;
|
||||
|
||||
/**
|
||||
* Tests for {@link ObjectIdentityImpl}.
|
||||
*
|
||||
* @author Andrei Stefan
|
||||
*/
|
||||
public class ObjectIdentityTests extends TestCase {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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 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);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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");
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
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(
|
||||
"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());
|
||||
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());
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockIdDomainObject {
|
||||
private Object id;
|
||||
|
||||
public Object getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Object id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
|
||||
private class MockOtherIdDomainObject {
|
||||
private Object id;
|
||||
|
||||
public Object getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Object id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package org.springframework.security.acls.sid;
|
||||
|
||||
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 {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void testSidsRetrieval() throws Exception {
|
||||
Authentication authentication = new TestingAuthenticationToken("scott", "password", new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_1"), new GrantedAuthorityImpl("ROLE_2"), new GrantedAuthorityImpl("ROLE_3") });
|
||||
SidRetrievalStrategy retrStrategy = new SidRetrievalStrategyImpl();
|
||||
Sid[] sids = retrStrategy.getSids(authentication);
|
||||
|
||||
assertNotNull(sids);
|
||||
assertEquals(4, sids.length);
|
||||
assertNotNull(sids[0]);
|
||||
assertTrue(sids[0] instanceof PrincipalSid);
|
||||
|
||||
for (int i = 1; i < sids.length; i++) {
|
||||
assertTrue(sids[i] instanceof GrantedAuthoritySid);
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
package org.springframework.security.acls.sid;
|
||||
|
||||
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.acls.sid.GrantedAuthoritySid;
|
||||
import org.springframework.security.acls.sid.PrincipalSid;
|
||||
import org.springframework.security.acls.sid.Sid;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
public class SidTests extends TestCase {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void testPrincipalSidConstructorsRequiredFields() throws Exception {
|
||||
// Check one String-argument constructor
|
||||
try {
|
||||
String string = null;
|
||||
Sid principalSid = new PrincipalSid(string);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Sid principalSid = new PrincipalSid("");
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Sid principalSid = new PrincipalSid("johndoe");
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
catch (IllegalArgumentException notExpected) {
|
||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||
}
|
||||
|
||||
// Check one Authentication-argument constructor
|
||||
try {
|
||||
Authentication authentication = null;
|
||||
Sid principalSid = new PrincipalSid(authentication);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Authentication authentication = new TestingAuthenticationToken(null, "password", null);
|
||||
Sid principalSid = new PrincipalSid(authentication);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
|
||||
Sid principalSid = new PrincipalSid(authentication);
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
catch (IllegalArgumentException notExpected) {
|
||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGrantedAuthoritySidConstructorsRequiredFields() throws Exception {
|
||||
// Check one String-argument constructor
|
||||
try {
|
||||
String string = null;
|
||||
Sid gaSid = new GrantedAuthoritySid(string);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Sid gaSid = new GrantedAuthoritySid("");
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
Sid gaSid = new GrantedAuthoritySid("ROLE_TEST");
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
catch (IllegalArgumentException notExpected) {
|
||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||
}
|
||||
|
||||
// Check one GrantedAuthority-argument constructor
|
||||
try {
|
||||
GrantedAuthority ga = null;
|
||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
GrantedAuthority ga = new GrantedAuthorityImpl(null);
|
||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
||||
Assert.fail("It should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
||||
Assert.assertTrue(true);
|
||||
}
|
||||
catch (IllegalArgumentException notExpected) {
|
||||
Assert.fail("It shouldn't have thrown IllegalArgumentException");
|
||||
}
|
||||
}
|
||||
|
||||
public void testPrincipalSidEquals() throws Exception {
|
||||
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, 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")));
|
||||
}
|
||||
|
||||
public void testGrantedAuthoritySidEquals() throws Exception {
|
||||
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
||||
|
||||
Assert.assertFalse(gaSid.equals(null));
|
||||
Assert.assertFalse(gaSid.equals("DIFFERENT_TYPE_OBJECT"));
|
||||
Assert.assertTrue(gaSid.equals(gaSid));
|
||||
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid(ga)));
|
||||
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid(new GrantedAuthorityImpl("ROLE_TEST"))));
|
||||
Assert.assertFalse(gaSid.equals(new GrantedAuthoritySid(new GrantedAuthorityImpl("ROLE_NOT_EQUAL"))));
|
||||
Assert.assertTrue(gaSid.equals(new GrantedAuthoritySid("ROLE_TEST")));
|
||||
Assert.assertFalse(gaSid.equals(new GrantedAuthoritySid("ROLE_NOT_EQUAL")));
|
||||
}
|
||||
|
||||
public void testPrincipalSidHashCode() throws Exception {
|
||||
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",
|
||||
null)).hashCode());
|
||||
}
|
||||
|
||||
public void testGrantedAuthoritySidHashCode() throws Exception {
|
||||
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
||||
Sid gaSid = new GrantedAuthoritySid(ga);
|
||||
|
||||
Assert.assertTrue(gaSid.hashCode() == new String("ROLE_TEST").hashCode());
|
||||
Assert.assertTrue(gaSid.hashCode() == new GrantedAuthoritySid("ROLE_TEST").hashCode());
|
||||
Assert.assertTrue(gaSid.hashCode() != new GrantedAuthoritySid("ROLE_TEST_2").hashCode());
|
||||
Assert.assertTrue(gaSid.hashCode() != new GrantedAuthoritySid(new GrantedAuthorityImpl("ROLE_TEST_2")).hashCode());
|
||||
}
|
||||
|
||||
public void testGetters() throws Exception {
|
||||
Authentication authentication = new TestingAuthenticationToken("johndoe", "password", null);
|
||||
PrincipalSid principalSid = new PrincipalSid(authentication);
|
||||
GrantedAuthority ga = new GrantedAuthorityImpl("ROLE_TEST");
|
||||
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
|
||||
|
||||
Assert.assertTrue("johndoe".equals(principalSid.getPrincipal()));
|
||||
Assert.assertFalse("scott".equals(principalSid.getPrincipal()));
|
||||
|
||||
Assert.assertTrue("ROLE_TEST".equals(gaSid.getGrantedAuthority()));
|
||||
Assert.assertFalse("ROLE_TEST2".equals(gaSid.getGrantedAuthority()));
|
||||
}
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author $author$
|
||||
* @version $Revision: 2142 $
|
||||
*/
|
||||
public class AlwaysTestAfterMaxRequestsCaptchaChannelProcessorTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
AlwaysTestAfterMaxRequestsCaptchaChannelProcessor alwaysTestAfterMaxRequestsCaptchaChannelProcessor;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
alwaysTestAfterMaxRequestsCaptchaChannelProcessor = new AlwaysTestAfterMaxRequestsCaptchaChannelProcessor();
|
||||
}
|
||||
|
||||
public void testIsContextValidConcerningHumanity()
|
||||
throws Exception {
|
||||
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThreshold(1);
|
||||
|
||||
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
|
||||
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
|
||||
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThreshold(-1);
|
||||
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
|
||||
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThreshold(3);
|
||||
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
|
||||
public void testNewContext() {
|
||||
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
|
||||
|
||||
assertFalse(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
alwaysTestAfterMaxRequestsCaptchaChannelProcessor.setThreshold(1);
|
||||
assertTrue(alwaysTestAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
import org.springframework.security.captcha.AlwaysTestAfterTimeInMillisCaptchaChannelProcessor;
|
||||
|
||||
|
||||
/**
|
||||
* WARNING! This test class make some assumptions concerning the compute speed! For example the two following
|
||||
* instructions should be computed in the same millis or the test is not valid.<pre><code>context.setHuman();
|
||||
* assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
* </code></pre>This should be the case for most environements unless
|
||||
* <ul>
|
||||
* <li>you run it on a good old TRS-80</li>
|
||||
* <li>you start M$office during this test ;)</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class AlwaysTestAfterTimeInMillisCaptchaChannelProcessorTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
AlwaysTestAfterTimeInMillisCaptchaChannelProcessor alwaysTestAfterTimeInMillisCaptchaChannelProcessor;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
alwaysTestAfterTimeInMillisCaptchaChannelProcessor = new AlwaysTestAfterTimeInMillisCaptchaChannelProcessor();
|
||||
}
|
||||
|
||||
public void testEqualsThresold() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
|
||||
//the two following instructions should be computed or the test is not valid (never fails). This should be the case
|
||||
// for most environements unless if you run it on a good old TRS-80 (thanks mom).
|
||||
context.setHuman();
|
||||
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
/* Commented out as it makes assumptions about the speed of the build server and fails intermittently on
|
||||
build.springframework.org - L.T.
|
||||
|
||||
public void testIsContextValidConcerningHumanity()
|
||||
throws Exception {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
alwaysTestAfterTimeInMillisCaptchaChannelProcessor.setThreshold(100);
|
||||
context.setHuman();
|
||||
|
||||
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < alwaysTestAfterTimeInMillisCaptchaChannelProcessor
|
||||
.getThreshold()) {
|
||||
assertTrue(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.incrementHumanRestrictedRessoucesRequestsCount();
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
while ((System.currentTimeMillis() - now) < 1) {}
|
||||
|
||||
;
|
||||
}
|
||||
|
||||
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
*/
|
||||
public void testNewContext() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
|
||||
//alwaysTestAfterTimeInMillisCaptchaChannelProcessor.setThreshold(10);
|
||||
assertFalse(alwaysTestAfterTimeInMillisCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author $author$
|
||||
* @version $Revision: 2142 $
|
||||
*/
|
||||
public class AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessorTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor = new AlwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor();
|
||||
}
|
||||
|
||||
public void testEqualsThresold() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThreshold(100);
|
||||
|
||||
context.setHuman();
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
/*
|
||||
while ((System.currentTimeMillis() - now) <= 100) {
|
||||
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
|
||||
context.incrementHumanRestrictedRessoucesRequestsCount();
|
||||
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
|
||||
context));
|
||||
|
||||
context.setHuman();
|
||||
context.incrementHumanRestrictedRessoucesRequestsCount();
|
||||
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
|
||||
context));
|
||||
|
||||
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThreshold(0);
|
||||
context.setHuman();
|
||||
context.incrementHumanRestrictedRessoucesRequestsCount();
|
||||
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
|
||||
context));
|
||||
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThreshold(0);
|
||||
*/
|
||||
}
|
||||
/*
|
||||
public void testIsContextValidConcerningHumanity()
|
||||
throws Exception {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.setThreshold(10);
|
||||
context.setHuman();
|
||||
|
||||
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (10 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.getThreshold())) {
|
||||
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
|
||||
public void testNewContext() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
assertFalse(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
|
||||
context));
|
||||
|
||||
context.setHuman();
|
||||
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor.isContextValidConcerningHumanity(
|
||||
context));
|
||||
}
|
||||
|
||||
public void testShouldPassAbove() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
|
||||
context.setHuman();
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (100 * alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.getThreshold())) {
|
||||
System.out.println((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()));
|
||||
|
||||
context.incrementHumanRestrictedRessoucesRequestsCount();
|
||||
i++;
|
||||
|
||||
while ((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()) < (alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.getThreshold() * i)) {}
|
||||
|
||||
System.out.println((System.currentTimeMillis() - context.getLastPassedCaptchaDateInMillis()));
|
||||
|
||||
assertTrue(alwaysTestBelowAverageTimeInMillisBetweenRequestsChannelProcessor
|
||||
.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.ConfigAttributeDefinition;
|
||||
import org.springframework.security.MockFilterChain;
|
||||
import org.springframework.security.SecurityConfig;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.intercept.web.FilterInvocation;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.captcha.CaptchaChannelProcessorTemplate}
|
||||
*
|
||||
* @author marc antoine Garrigue
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CaptchaChannelProcessorTemplateTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
private MockHttpServletResponse decideWithNewResponse(ConfigAttributeDefinition cad,
|
||||
CaptchaChannelProcessorTemplate processor, MockHttpServletRequest request)
|
||||
throws IOException, ServletException {
|
||||
MockHttpServletResponse response;
|
||||
MockFilterChain chain;
|
||||
FilterInvocation fi;
|
||||
response = new MockHttpServletResponse();
|
||||
chain = new MockFilterChain();
|
||||
fi = new FilterInvocation(request, response, chain);
|
||||
processor.decide(fi, cad);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
public void setUp() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testContextRedirect() throws Exception {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setKeyword("X");
|
||||
|
||||
ConfigAttributeDefinition cad = new ConfigAttributeDefinition("Y");
|
||||
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
CaptchaEntryPoint epoint = new CaptchaEntryPoint();
|
||||
epoint.setCaptchaFormUrl("/jcaptcha.do");
|
||||
epoint.setIncludeOriginalRequest(false);
|
||||
|
||||
processor.setEntryPoint(epoint);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/demo");
|
||||
request.setServletPath("/restricted");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8000);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
|
||||
processor.decide(fi, cad);
|
||||
assertEquals(null, response.getRedirectedUrl());
|
||||
processor.setKeyword("Y");
|
||||
response = decideWithNewResponse(cad, processor, request);
|
||||
assertEquals("http://localhost:8000/demo/jcaptcha.do", response.getRedirectedUrl());
|
||||
context.setHuman();
|
||||
response = decideWithNewResponse(cad, processor, request);
|
||||
assertEquals(null, response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setEntryPoint(new CaptchaEntryPoint());
|
||||
processor.setKeyword("X");
|
||||
processor.afterPropertiesSet();
|
||||
|
||||
try {
|
||||
processor.decide(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
assertEquals(null, processor.getKeyword());
|
||||
processor.setKeyword("X");
|
||||
assertEquals("X", processor.getKeyword());
|
||||
|
||||
assertEquals(0, processor.getThreshold());
|
||||
processor.setThreshold(1);
|
||||
assertEquals(1, processor.getThreshold());
|
||||
|
||||
assertTrue(processor.getEntryPoint() == null);
|
||||
processor.setEntryPoint(new CaptchaEntryPoint());
|
||||
assertTrue(processor.getEntryPoint() != null);
|
||||
}
|
||||
|
||||
public void testIncrementRequestCount() throws Exception {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setKeyword("X");
|
||||
|
||||
ConfigAttributeDefinition cad = new ConfigAttributeDefinition("X");
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
CaptchaEntryPoint epoint = new CaptchaEntryPoint();
|
||||
epoint.setCaptchaFormUrl("/jcaptcha.do");
|
||||
processor.setEntryPoint(epoint);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/demo");
|
||||
request.setServletPath("/restricted");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8000);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
|
||||
processor.decide(fi, cad);
|
||||
assertEquals(0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
context.setHuman();
|
||||
decideWithNewResponse(cad, processor, request);
|
||||
assertEquals(1, context.getHumanRestrictedResourcesRequestsCount());
|
||||
decideWithNewResponse(cad, processor, request);
|
||||
assertEquals(2, context.getHumanRestrictedResourcesRequestsCount());
|
||||
processor.setKeyword("Y");
|
||||
decideWithNewResponse(cad, processor, request);
|
||||
assertEquals(2, context.getHumanRestrictedResourcesRequestsCount());
|
||||
context = new CaptchaSecurityContextImpl();
|
||||
decideWithNewResponse(cad, processor, request);
|
||||
assertEquals(0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
}
|
||||
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("entryPoint required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testMissingKeyword() throws Exception {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setKeyword(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
|
||||
processor.setKeyword("");
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
|
||||
public void testSupports() {
|
||||
CaptchaChannelProcessorTemplate processor = new TestHumanityCaptchaChannelProcessor();
|
||||
processor.setKeyword("X");
|
||||
assertTrue(processor.supports(new SecurityConfig(processor.getKeyword())));
|
||||
|
||||
assertTrue(processor.supports(new SecurityConfig("X")));
|
||||
|
||||
assertFalse(processor.supports(null));
|
||||
|
||||
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class TestHumanityCaptchaChannelProcessor extends CaptchaChannelProcessorTemplate {
|
||||
boolean isContextValidConcerningHumanity(CaptchaSecurityContext context) {
|
||||
return context.isHuman();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,396 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.MockPortResolver;
|
||||
|
||||
import org.springframework.security.util.PortMapperImpl;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CaptchaEntryPoint}.
|
||||
*
|
||||
* @author marc antoine Garrigue
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CaptchaEntryPointTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(CaptchaEntryPointTests.class);
|
||||
}
|
||||
|
||||
// ~ Methods
|
||||
// ================================================================
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testDetectsMissingCaptchaFormUrl() throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("captchaFormUrl must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("xxx");
|
||||
ep.setPortMapper(null);
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("portMapper must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("xxx");
|
||||
ep.setPortResolver(null);
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("portResolver must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertEquals("/hello", ep.getCaptchaFormUrl());
|
||||
assertTrue(ep.getPortMapper() != null);
|
||||
assertTrue(ep.getPortResolver() != null);
|
||||
|
||||
assertEquals("original_requestUrl", ep.getOriginalRequestUrlParameterName());
|
||||
ep.setOriginalRequestUrlParameterName("Z");
|
||||
assertEquals("Z", ep.getOriginalRequestUrlParameterName());
|
||||
|
||||
assertEquals(true, ep.isIncludeOriginalRequest());
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
assertEquals(false, ep.isIncludeOriginalRequest());
|
||||
|
||||
assertEquals(false, ep.isOutsideWebApp());
|
||||
ep.setOutsideWebApp(true);
|
||||
assertEquals(true, ep.isOutsideWebApp());
|
||||
|
||||
ep.setForceHttps(false);
|
||||
assertFalse(ep.getForceHttps());
|
||||
ep.setForceHttps(true);
|
||||
assertTrue(ep.getForceHttps());
|
||||
}
|
||||
|
||||
public void testHttpsOperationFromOriginalHttpUrl()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
|
||||
request.setServerPort(8080);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
|
||||
// Now test an unusual custom HTTP:HTTPS is handled properly
|
||||
request.setServerPort(8888);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map map = new HashMap();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(portMapper);
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:9999/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testHttpsOperationFromOriginalHttpsUrl()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
|
||||
request.setServerPort(8443);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWhenHttpsRequestsButHttpsPortUnknown()
|
||||
throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setForceHttps(true);
|
||||
ep.setIncludeOriginalRequest(false);
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(8888); // NB: Port we can't resolve
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.commence(request, response);
|
||||
|
||||
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to
|
||||
// HTTP port mapping
|
||||
assertEquals("http://www.example.com:8888/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWithOriginalRequestIncludes()
|
||||
throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("/hello");
|
||||
|
||||
PortMapperImpl mapper = new PortMapperImpl();
|
||||
mapper.getTranslatedPortMappings().put(new Integer(8888), new Integer(1234));
|
||||
ep.setPortMapper(mapper);
|
||||
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setIncludeOriginalRequest(true);
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("post");
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
|
||||
// request.setContextPath("/bigWebApp");
|
||||
// TODO correct this when the getRequestUrl from mock works...
|
||||
request.setServerPort(8888); // NB: Port we can't resolve
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test the query params
|
||||
request.addParameter("name", "value");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test the multiple query params
|
||||
ep.setIncludeOriginalParameters(true);
|
||||
|
||||
request.addParameter("name", "value");
|
||||
request.addParameter("name1", "value2");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com:8888/hello?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test add parameter to captcha form url??
|
||||
ep.setCaptchaFormUrl("/hello?toto=titi");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com:8888/hello?toto=titi&original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// with forcing!!!
|
||||
ep.setForceHttps(true);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:1234/hello?toto=titi&original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWithOutsideWebApp() throws Exception {
|
||||
CaptchaEntryPoint ep = new CaptchaEntryPoint();
|
||||
ep.setCaptchaFormUrl("https://www.jcaptcha.net/dotest/");
|
||||
|
||||
PortMapperImpl mapper = new PortMapperImpl();
|
||||
mapper.getTranslatedPortMappings().put(new Integer(8888), new Integer(1234));
|
||||
ep.setPortMapper(mapper);
|
||||
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setIncludeOriginalRequest(true);
|
||||
ep.setOutsideWebApp(true);
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setMethod("post");
|
||||
|
||||
// request.setContextPath("/bigWebApp");
|
||||
// TODO correct this when the getRequestUrl from mock works...
|
||||
request.setServerPort(8888); // NB: Port we can't resolve
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test the query params
|
||||
request.addParameter("name", "value");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test the multiple query params
|
||||
ep.setIncludeOriginalParameters(true);
|
||||
request.addParameter("name", "value");
|
||||
request.addParameter("name1", "value2");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.jcaptcha.net/dotest/?original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// test add parameter to captcha form url??
|
||||
ep.setCaptchaFormUrl("https://www.jcaptcha.net/dotest/?toto=titi");
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// with forcing!!!
|
||||
ep.setForceHttps(true);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.jcaptcha.net/dotest/?toto=titi&original_requestUrl="
|
||||
+ URLEncoder.encode("http://www.example.com:8888/some_path", "UTF-8") + "&original_request_method=post"
|
||||
+ "&original_request_parameters=" + URLEncoder.encode("name__value;;name1__value2", "UTF-8"),
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import org.springframework.security.context.SecurityContextImplTests;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CaptchaSecurityContextImpl}.
|
||||
*
|
||||
* @author marc antoine Garrigue
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CaptchaSecurityContextImplTests extends SecurityContextImplTests {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void testDefaultValues() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
assertEquals("should not be human", false, context.isHuman());
|
||||
assertEquals("should be 0", 0, context.getLastPassedCaptchaDateInMillis());
|
||||
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
}
|
||||
|
||||
public void testEquals() {
|
||||
CaptchaSecurityContext context1 = new CaptchaSecurityContextImpl();
|
||||
CaptchaSecurityContext context2 = new CaptchaSecurityContextImpl();
|
||||
|
||||
assertEquals(context1, context2);
|
||||
|
||||
assertFalse(context1.isHuman());
|
||||
context1.setHuman();
|
||||
assertNotSame(context1, context2);
|
||||
|
||||
// Get fresh copy
|
||||
context1 = new CaptchaSecurityContextImpl();
|
||||
assertEquals(context1, context2);
|
||||
|
||||
context1.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertNotSame(context1, context2);
|
||||
}
|
||||
|
||||
public void testHashcode() {
|
||||
CaptchaSecurityContext context1 = new CaptchaSecurityContextImpl();
|
||||
CaptchaSecurityContext context2 = new CaptchaSecurityContextImpl();
|
||||
|
||||
assertEquals(context1.hashCode(), context2.hashCode());
|
||||
|
||||
assertFalse(context1.isHuman());
|
||||
context1.setHuman();
|
||||
assertTrue(context1.hashCode() != context2.hashCode());
|
||||
|
||||
// Get fresh copy
|
||||
context1 = new CaptchaSecurityContextImpl();
|
||||
assertEquals(context1.hashCode(), context2.hashCode());
|
||||
|
||||
context1.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertTrue(context1 != context2);
|
||||
}
|
||||
|
||||
public void testIncrementRequests() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
context.setHuman();
|
||||
assertEquals("should be human", true, context.isHuman());
|
||||
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertEquals("should be 1", 1, context.getHumanRestrictedResourcesRequestsCount());
|
||||
}
|
||||
|
||||
public void testResetHuman() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
context.setHuman();
|
||||
assertEquals("should be human", true, context.isHuman());
|
||||
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertEquals("should be 1", 1, context.getHumanRestrictedResourcesRequestsCount());
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
context.setHuman();
|
||||
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
assertTrue("should be more than 0", (context.getLastPassedCaptchaDateInMillis() - now) >= 0);
|
||||
assertTrue("should be less than 0,1 seconde", (context.getLastPassedCaptchaDateInMillis() - now) < 100);
|
||||
}
|
||||
|
||||
public void testSetHuman() {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
long now = System.currentTimeMillis();
|
||||
context.setHuman();
|
||||
assertEquals("should be human", true, context.isHuman());
|
||||
assertTrue("should be more than 0", (context.getLastPassedCaptchaDateInMillis() - now) >= 0);
|
||||
assertTrue("should be less than 0,1 seconde", (context.getLastPassedCaptchaDateInMillis() - now) < 100);
|
||||
assertEquals("should be 0", 0, context.getHumanRestrictedResourcesRequestsCount());
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.util.MockFilterChain;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CaptchaValidationProcessingFilter}.
|
||||
*
|
||||
* @author marc antoine Garrigue
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CaptchaValidationProcessingFilterTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
/*
|
||||
*/
|
||||
public void testAfterPropertiesSet() throws Exception {
|
||||
CaptchaValidationProcessingFilter filter = new CaptchaValidationProcessingFilter();
|
||||
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("should have thrown an invalid argument exception");
|
||||
} catch (Exception e) {
|
||||
assertTrue("should be an InvalidArgumentException",
|
||||
IllegalArgumentException.class.isAssignableFrom(e.getClass()));
|
||||
}
|
||||
|
||||
filter.setCaptchaService(new MockCaptchaServiceProxy());
|
||||
filter.afterPropertiesSet();
|
||||
filter.setCaptchaValidationParameter(null);
|
||||
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("should have thrown an invalid argument exception");
|
||||
} catch (Exception e) {
|
||||
assertTrue("should be an InvalidArgumentException",
|
||||
IllegalArgumentException.class.isAssignableFrom(e.getClass()));
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.security.captcha.CaptchaValidationProcessingFilter.doFilter(ServletRequest,
|
||||
* ServletResponse, FilterChain)'
|
||||
*/
|
||||
public void testDoFilterWithRequestParameter() throws Exception {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
CaptchaValidationProcessingFilter filter = new CaptchaValidationProcessingFilter();
|
||||
request.addParameter(filter.getCaptchaValidationParameter(), "");
|
||||
|
||||
MockCaptchaServiceProxy service = new MockCaptchaServiceProxy();
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
filter.setCaptchaService(service);
|
||||
filter.doFilter(request, null, chain);
|
||||
assertTrue("should have been called", service.hasBeenCalled);
|
||||
assertFalse("context should not have been updated", context.isHuman());
|
||||
|
||||
// test with valid
|
||||
service.valid = true;
|
||||
filter.doFilter(request, null, chain);
|
||||
assertTrue("should have been called", service.hasBeenCalled);
|
||||
assertTrue("context should have been updated", context.isHuman());
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for
|
||||
* 'org.springframework.security.captcha.CaptchaValidationProcessingFilter.doFilter(ServletRequest,
|
||||
* ServletResponse, FilterChain)'
|
||||
*/
|
||||
public void testDoFilterWithoutRequestParameter() throws Exception {
|
||||
CaptchaSecurityContext context = new CaptchaSecurityContextImpl();
|
||||
SecurityContextHolder.setContext(context);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
CaptchaValidationProcessingFilter filter = new CaptchaValidationProcessingFilter();
|
||||
MockCaptchaServiceProxy service = new MockCaptchaServiceProxy();
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
filter.setCaptchaService(service);
|
||||
filter.doFilter(request, null, chain);
|
||||
assertFalse("proxy should not have been called", service.hasBeenCalled);
|
||||
assertFalse("context should not have been updated", context.isHuman());
|
||||
|
||||
// test with valid
|
||||
service.valid = true;
|
||||
filter.doFilter(request, null, chain);
|
||||
assertFalse("proxy should not have been called", service.hasBeenCalled);
|
||||
assertFalse("context should not have been updated", context.isHuman());
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author marc antoine Garrigue
|
||||
* @version $Id$
|
||||
*/
|
||||
public class MockCaptchaServiceProxy implements CaptchaServiceProxy {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
public boolean hasBeenCalled = false;
|
||||
public boolean valid = false;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public boolean validateReponseForId(String id, Object response) {
|
||||
hasBeenCalled = true;
|
||||
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
/* 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.captcha;
|
||||
|
||||
import junit.framework.*;
|
||||
|
||||
import org.springframework.security.captcha.TestOnceAfterMaxRequestsCaptchaChannelProcessor;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author $author$
|
||||
* @version $Revision: 2142 $
|
||||
*/
|
||||
public class TestOnceAfterMaxRequestsCaptchaChannelProcessorTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
TestOnceAfterMaxRequestsCaptchaChannelProcessor testOnceAfterMaxRequestsCaptchaChannelProcessor;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
testOnceAfterMaxRequestsCaptchaChannelProcessor = new TestOnceAfterMaxRequestsCaptchaChannelProcessor();
|
||||
}
|
||||
|
||||
public void testIsContextValidConcerningHumanity()
|
||||
throws Exception {
|
||||
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThreshold(1);
|
||||
|
||||
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
|
||||
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
|
||||
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThreshold(-1);
|
||||
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
|
||||
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThreshold(3);
|
||||
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.incrementHumanRestrictedResourcesRequestsCount();
|
||||
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
context.setHuman();
|
||||
|
||||
for (int i = 0; i < (2 * testOnceAfterMaxRequestsCaptchaChannelProcessor.getThreshold()); i++) {
|
||||
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
|
||||
public void testNewContext() {
|
||||
CaptchaSecurityContextImpl context = new CaptchaSecurityContextImpl();
|
||||
|
||||
assertFalse(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
testOnceAfterMaxRequestsCaptchaChannelProcessor.setThreshold(1);
|
||||
assertTrue(testOnceAfterMaxRequestsCaptchaChannelProcessor.isContextValidConcerningHumanity(context));
|
||||
}
|
||||
}
|
||||
@@ -41,14 +41,6 @@ public class SecurityContextImplTests extends TestCase {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(SecurityContextImplTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testEmptyObjectsAreEquals() {
|
||||
SecurityContextImpl obj1 = new SecurityContextImpl();
|
||||
SecurityContextImpl obj2 = new SecurityContextImpl();
|
||||
|
||||
+2
-4
@@ -64,8 +64,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testCallbackIsInvokedWhenPermissionGranted()
|
||||
throws Exception {
|
||||
public void testCallbackIsInvokedWhenPermissionGranted() throws Exception {
|
||||
AspectJSecurityInterceptor si = new AspectJSecurityInterceptor();
|
||||
si.setApplicationEventPublisher(MockApplicationContext.getContext());
|
||||
si.setAccessDecisionManager(new MockAccessDecisionManager());
|
||||
@@ -96,8 +95,7 @@ public class AspectJSecurityInterceptorTests extends TestCase {
|
||||
assertEquals("object proceeded", result);
|
||||
}
|
||||
|
||||
public void testCallbackIsNotInvokedWhenPermissionDenied()
|
||||
throws Exception {
|
||||
public void testCallbackIsNotInvokedWhenPermissionDenied() throws Exception {
|
||||
AspectJSecurityInterceptor si = new AspectJSecurityInterceptor();
|
||||
si.setApplicationEventPublisher(MockApplicationContext.getContext());
|
||||
si.setAccessDecisionManager(new MockAccessDecisionManager());
|
||||
|
||||
-358
@@ -1,358 +0,0 @@
|
||||
/* 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.providers.cas;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.AuthenticationException;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.providers.cas.ticketvalidator.AbstractTicketValidator;
|
||||
|
||||
import org.springframework.security.ui.cas.CasProcessingFilter;
|
||||
|
||||
import org.springframework.security.userdetails.User;
|
||||
import org.springframework.security.userdetails.UserDetails;
|
||||
import org.springframework.security.userdetails.UserDetailsService;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CasAuthenticationProvider}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CasAuthenticationProviderTests {
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
private UserDetails makeUserDetails() {
|
||||
return new User("user", "password", true, true, true, true,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
}
|
||||
|
||||
private UserDetails makeUserDetailsFromAuthoritiesPopulator() {
|
||||
return new User("user", "password", true, true, true, true,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A"), new GrantedAuthorityImpl("ROLE_B")});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statefulAuthenticationIsSuccessful() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider(true));
|
||||
cap.setKey("qwerty");
|
||||
|
||||
StatelessTicketCache cache = new MockStatelessTicketCache();
|
||||
cap.setStatelessTicketCache(cache);
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER,
|
||||
"ST-123");
|
||||
token.setDetails("details");
|
||||
|
||||
Authentication result = cap.authenticate(token);
|
||||
|
||||
// Confirm ST-123 was NOT added to the cache
|
||||
assertTrue(cache.getByTicketId("ST-456") == null);
|
||||
|
||||
if (!(result instanceof CasAuthenticationToken)) {
|
||||
fail("Should have returned a CasAuthenticationToken");
|
||||
}
|
||||
|
||||
CasAuthenticationToken casResult = (CasAuthenticationToken) result;
|
||||
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), casResult.getPrincipal());
|
||||
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt",
|
||||
casResult.getProxyGrantingTicketIou());
|
||||
assertEquals("https://localhost/portal/j_spring_cas_security_check", casResult.getProxyList().get(0));
|
||||
assertEquals("ST-123", casResult.getCredentials());
|
||||
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());
|
||||
|
||||
// Now confirm the CasAuthenticationToken is automatically re-accepted.
|
||||
// To ensure TicketValidator not called again, set it to deliver an exception...
|
||||
cap.setTicketValidator(new MockTicketValidator(false));
|
||||
|
||||
Authentication laterResult = cap.authenticate(result);
|
||||
assertEquals(result, laterResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statelessAuthenticationIsSuccessful() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider(true));
|
||||
cap.setKey("qwerty");
|
||||
|
||||
StatelessTicketCache cache = new MockStatelessTicketCache();
|
||||
cap.setStatelessTicketCache(cache);
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATELESS_IDENTIFIER,
|
||||
"ST-456");
|
||||
token.setDetails("details");
|
||||
|
||||
Authentication result = cap.authenticate(token);
|
||||
|
||||
// Confirm ST-456 was added to the cache
|
||||
assertTrue(cache.getByTicketId("ST-456") != null);
|
||||
|
||||
if (!(result instanceof CasAuthenticationToken)) {
|
||||
fail("Should have returned a CasAuthenticationToken");
|
||||
}
|
||||
|
||||
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), result.getPrincipal());
|
||||
assertEquals("ST-456", result.getCredentials());
|
||||
assertEquals("details", result.getDetails());
|
||||
|
||||
// Now try to authenticate again. To ensure TicketValidator not
|
||||
// called again, set it to deliver an exception...
|
||||
cap.setTicketValidator(new MockTicketValidator(false));
|
||||
|
||||
// Previously created UsernamePasswordAuthenticationToken is OK
|
||||
Authentication newResult = cap.authenticate(token);
|
||||
assertEquals(makeUserDetailsFromAuthoritiesPopulator(), newResult.getPrincipal());
|
||||
assertEquals("ST-456", newResult.getCredentials());
|
||||
}
|
||||
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void missingTicketIdIsDetected() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider(true));
|
||||
cap.setKey("qwerty");
|
||||
|
||||
StatelessTicketCache cache = new MockStatelessTicketCache();
|
||||
cap.setStatelessTicketCache(cache);
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
UsernamePasswordAuthenticationToken token =
|
||||
new UsernamePasswordAuthenticationToken(CasProcessingFilter.CAS_STATEFUL_IDENTIFIER, "");
|
||||
|
||||
Authentication result = cap.authenticate(token);
|
||||
}
|
||||
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void invalidKeyIsDetected() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider(true));
|
||||
cap.setKey("qwerty");
|
||||
|
||||
StatelessTicketCache cache = new MockStatelessTicketCache();
|
||||
cap.setStatelessTicketCache(cache);
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("XX")}, makeUserDetails(), new Vector(), "IOU-xxx");
|
||||
|
||||
cap.authenticate(token);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingAuthoritiesPopulator() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingKey() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingProxyDecider() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingStatelessTicketCache() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
// set this explicitly to null to test failure
|
||||
cap.setStatelessTicketCache(null);
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setKey("qwerty");
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingTicketValidator() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider(true));
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void gettersAndSettersMatch() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
assertTrue(cap.getUserDetailsService() != null);
|
||||
assertTrue(cap.getCasProxyDecider() != null);
|
||||
assertEquals("qwerty", cap.getKey());
|
||||
assertTrue(cap.getStatelessTicketCache() != null);
|
||||
assertTrue(cap.getTicketValidator() != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoresClassesItDoesNotSupport() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
|
||||
assertFalse(cap.supports(TestingAuthenticationToken.class));
|
||||
|
||||
// Try it anyway
|
||||
assertEquals(null, cap.authenticate(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoresUsernamePasswordAuthenticationTokensWithoutCasIdentifiersAsPrincipal() throws Exception {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
cap.setUserDetailsService(new MockAuthoritiesPopulator());
|
||||
cap.setCasProxyDecider(new MockProxyDecider());
|
||||
cap.setKey("qwerty");
|
||||
cap.setStatelessTicketCache(new MockStatelessTicketCache());
|
||||
cap.setTicketValidator(new MockTicketValidator(true));
|
||||
cap.afterPropertiesSet();
|
||||
|
||||
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user",
|
||||
"password", new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_A")});
|
||||
assertEquals(null, cap.authenticate(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsRequiredTokens() {
|
||||
CasAuthenticationProvider cap = new CasAuthenticationProvider();
|
||||
assertTrue(cap.supports(UsernamePasswordAuthenticationToken.class));
|
||||
assertTrue(cap.supports(CasAuthenticationToken.class));
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockAuthoritiesPopulator implements UserDetailsService {
|
||||
public UserDetails loadUserByUsername(String casUserId) throws AuthenticationException {
|
||||
return makeUserDetailsFromAuthoritiesPopulator();
|
||||
}
|
||||
}
|
||||
|
||||
private class MockProxyDecider implements CasProxyDecider {
|
||||
private boolean acceptProxy;
|
||||
|
||||
public MockProxyDecider(boolean acceptProxy) {
|
||||
this.acceptProxy = acceptProxy;
|
||||
}
|
||||
|
||||
private MockProxyDecider() {
|
||||
super();
|
||||
}
|
||||
|
||||
public void confirmProxyListTrusted(List proxyList)
|
||||
throws ProxyUntrustedException {
|
||||
if (acceptProxy) {
|
||||
return;
|
||||
} else {
|
||||
throw new ProxyUntrustedException("As requested from mock");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class MockStatelessTicketCache implements StatelessTicketCache {
|
||||
private Map cache = new HashMap();
|
||||
|
||||
public CasAuthenticationToken getByTicketId(String serviceTicket) {
|
||||
return (CasAuthenticationToken) cache.get(serviceTicket);
|
||||
}
|
||||
|
||||
public void putTicketInCache(CasAuthenticationToken token) {
|
||||
cache.put(token.getCredentials().toString(), token);
|
||||
}
|
||||
|
||||
public void removeTicketFromCache(CasAuthenticationToken token) {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
|
||||
public void removeTicketFromCache(String serviceTicket) {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
private class MockTicketValidator extends AbstractTicketValidator {
|
||||
private boolean returnTicket;
|
||||
|
||||
public MockTicketValidator(boolean returnTicket) {
|
||||
this.returnTicket = returnTicket;
|
||||
}
|
||||
|
||||
public TicketResponse confirmTicketValid(String serviceTicket)
|
||||
throws AuthenticationException {
|
||||
if (returnTicket) {
|
||||
List list = new Vector();
|
||||
list.add("https://localhost/portal/j_spring_cas_security_check");
|
||||
|
||||
return new TicketResponse("rod", list, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
}
|
||||
|
||||
throw new BadCredentialsException("As requested from mock");
|
||||
}
|
||||
}
|
||||
}
|
||||
-292
@@ -1,292 +0,0 @@
|
||||
/* 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.providers.cas;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
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 java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CasAuthenticationToken}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CasAuthenticationTokenTests extends TestCase {
|
||||
//~ 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,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testConstructorRejectsNulls() {
|
||||
try {
|
||||
new CasAuthenticationToken(null, makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", null, "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", makeUserDetails(), null,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", makeUserDetails(), "Password", null, makeUserDetails(), new Vector(),
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), null, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
null, new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), null);
|
||||
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(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testEqualsWhenEqual() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
List proxyList2 = new Vector();
|
||||
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
assertEquals(token1, token2);
|
||||
}
|
||||
|
||||
public void testGetters() {
|
||||
// Build the proxy list returned in the ticket from CAS
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
assertEquals("key".hashCode(), token.getKeyHash());
|
||||
assertEquals(makeUserDetails(), token.getPrincipal());
|
||||
assertEquals("Password", token.getCredentials());
|
||||
assertEquals("ROLE_ONE", token.getAuthorities()[0].getAuthority());
|
||||
assertEquals("ROLE_TWO", token.getAuthorities()[1].getAuthority());
|
||||
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt", token.getProxyGrantingTicketIou());
|
||||
assertEquals(proxyList, token.getProxyList());
|
||||
assertEquals(makeUserDetails().getUsername(), token.getUserDetails().getUsername());
|
||||
}
|
||||
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
Class clazz = CasAuthenticationToken.class;
|
||||
|
||||
try {
|
||||
clazz.getDeclaredConstructor((Class[]) null);
|
||||
fail("Should have thrown NoSuchMethodException");
|
||||
} catch (NoSuchMethodException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testNotEqualsDueToAbstractParentEqualsCheck() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
List proxyList2 = new Vector();
|
||||
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
assertTrue(!token1.equals(token2));
|
||||
}
|
||||
|
||||
public void testNotEqualsDueToDifferentAuthenticationClass() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken("Test", "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
|
||||
assertTrue(!token1.equals(token2));
|
||||
}
|
||||
|
||||
public void testNotEqualsDueToKey() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
List proxyList2 = new Vector();
|
||||
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
assertTrue(!token1.equals(token2));
|
||||
}
|
||||
|
||||
public void testNotEqualsDueToProxyGrantingTicket() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
List proxyList2 = new Vector();
|
||||
proxyList2.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList2, "PGTIOU-SOME_OTHER_VALUE");
|
||||
|
||||
assertTrue(!token1.equals(token2));
|
||||
}
|
||||
|
||||
public void testNotEqualsDueToProxyList() {
|
||||
List proxyList1 = new Vector();
|
||||
proxyList1.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList1, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
List proxyList2 = new Vector();
|
||||
proxyList2.add("https://localhost/SOME_OTHER_PORTAL/j_spring_cas_security_check");
|
||||
|
||||
CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), proxyList2, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
|
||||
assertTrue(!token1.equals(token2));
|
||||
}
|
||||
|
||||
public void testSetAuthenticated() {
|
||||
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
assertTrue(token.isAuthenticated());
|
||||
token.setAuthenticated(false);
|
||||
assertTrue(!token.isAuthenticated());
|
||||
}
|
||||
|
||||
public void testToString() {
|
||||
CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")},
|
||||
makeUserDetails(), new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
String result = token.toString();
|
||||
assertTrue(result.lastIndexOf("Proxy List:") != -1);
|
||||
assertTrue(result.lastIndexOf("Proxy-Granting Ticket IOU:") != -1);
|
||||
assertTrue(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1);
|
||||
}
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
/* 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.providers.cas;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link TicketResponse}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class TicketResponseTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public TicketResponseTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TicketResponseTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(TicketResponseTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testConstructorAcceptsNullProxyGrantingTicketIOU() {
|
||||
TicketResponse ticket = new TicketResponse("rod", new Vector(), null);
|
||||
assertEquals("", ticket.getProxyGrantingTicketIou());
|
||||
}
|
||||
|
||||
public void testConstructorAcceptsNullProxyList() {
|
||||
TicketResponse ticket = new TicketResponse("rod", null,
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
assertEquals(new Vector(), ticket.getProxyList());
|
||||
}
|
||||
|
||||
public void testConstructorRejectsNullUser() {
|
||||
try {
|
||||
new TicketResponse(null, new Vector(), "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetters() {
|
||||
// Build the proxy list returned in the ticket from CAS
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
TicketResponse ticket = new TicketResponse("rod", proxyList,
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
assertEquals("rod", ticket.getUser());
|
||||
assertEquals(proxyList, ticket.getProxyList());
|
||||
assertEquals("PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt", ticket.getProxyGrantingTicketIou());
|
||||
}
|
||||
|
||||
public void testNoArgConstructorDoesntExist() {
|
||||
Class clazz = TicketResponse.class;
|
||||
|
||||
try {
|
||||
clazz.getDeclaredConstructor((Class[]) null);
|
||||
fail("Should have thrown NoSuchMethodException");
|
||||
} catch (NoSuchMethodException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testToString() {
|
||||
TicketResponse ticket = new TicketResponse("rod", null,
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
String result = ticket.toString();
|
||||
assertTrue(result.lastIndexOf("Proxy List:") != -1);
|
||||
assertTrue(result.lastIndexOf("Proxy-Granting Ticket IOU:") != -1);
|
||||
assertTrue(result.lastIndexOf("User:") != -1);
|
||||
}
|
||||
}
|
||||
-108
@@ -1,108 +0,0 @@
|
||||
/* 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.providers.cas.cache;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import net.sf.ehcache.Ehcache;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.MockApplicationContext;
|
||||
|
||||
import org.springframework.security.providers.cas.CasAuthenticationToken;
|
||||
|
||||
import org.springframework.security.userdetails.User;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link EhCacheBasedTicketCache}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class EhCacheBasedTicketCacheTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public EhCacheBasedTicketCacheTests() {
|
||||
}
|
||||
|
||||
public EhCacheBasedTicketCacheTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
private Ehcache getCache() {
|
||||
ApplicationContext ctx = MockApplicationContext.getContext();
|
||||
|
||||
return (Ehcache) ctx.getBean("eHCacheBackend");
|
||||
}
|
||||
|
||||
private CasAuthenticationToken getToken() {
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
User user = new User("rod", "password", true, true, true, true,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
|
||||
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
|
||||
proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testCacheOperation() throws Exception {
|
||||
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
|
||||
cache.setCache(getCache());
|
||||
cache.afterPropertiesSet();
|
||||
|
||||
// Check it gets stored in the cache
|
||||
cache.putTicketInCache(getToken());
|
||||
assertEquals(getToken(), cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
|
||||
|
||||
// Check it gets removed from the cache
|
||||
cache.removeTicketFromCache(getToken());
|
||||
assertNull(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ"));
|
||||
|
||||
// Check it doesn't return values for null or unknown service tickets
|
||||
assertNull(cache.getByTicketId(null));
|
||||
assertNull(cache.getByTicketId("UNKNOWN_SERVICE_TICKET"));
|
||||
}
|
||||
|
||||
public void testStartupDetectsMissingCache() throws Exception {
|
||||
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
|
||||
|
||||
try {
|
||||
cache.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
Ehcache myCache = getCache();
|
||||
cache.setCache(myCache);
|
||||
assertEquals(myCache, cache.getCache());
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
/* 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.providers.cas.cache;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
import org.springframework.security.providers.cas.CasAuthenticationToken;
|
||||
import org.springframework.security.providers.cas.StatelessTicketCache;
|
||||
import org.springframework.security.userdetails.User;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Test cases for the @link {@link NullStatelessTicketCache}
|
||||
*
|
||||
* @author Scott Battaglia
|
||||
* @version $Id$
|
||||
*
|
||||
*/
|
||||
public class NullStatelessTicketCacheTests extends TestCase {
|
||||
|
||||
private StatelessTicketCache cache = new NullStatelessTicketCache();
|
||||
|
||||
public void testGetter() {
|
||||
assertNull(cache.getByTicketId(null));
|
||||
assertNull(cache.getByTicketId("test"));
|
||||
}
|
||||
|
||||
public void testInsertAndGet() {
|
||||
final CasAuthenticationToken token = getToken();
|
||||
cache.putTicketInCache(token);
|
||||
assertNull(cache.getByTicketId((String) token.getCredentials()));
|
||||
}
|
||||
|
||||
private 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,
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")});
|
||||
|
||||
return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl("ROLE_TWO")}, user,
|
||||
proxyList, "PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
}
|
||||
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
/* 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.providers.cas.proxy;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AcceptAnyCasProxy}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AcceptAnyCasProxyTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public AcceptAnyCasProxyTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public AcceptAnyCasProxyTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(AcceptAnyCasProxyTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testDoesNotAcceptNull() {
|
||||
AcceptAnyCasProxy proxyDecider = new AcceptAnyCasProxy();
|
||||
|
||||
try {
|
||||
proxyDecider.confirmProxyListTrusted(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("proxyList cannot be null", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testNormalOperation() {
|
||||
AcceptAnyCasProxy proxyDecider = new AcceptAnyCasProxy();
|
||||
proxyDecider.confirmProxyListTrusted(new Vector());
|
||||
assertTrue(true); // as no Exception thrown
|
||||
}
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
/* 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.providers.cas.proxy;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.providers.cas.ProxyUntrustedException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link NamedCasProxyDecider}.
|
||||
*/
|
||||
public class NamedCasProxyDeciderTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public NamedCasProxyDeciderTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public NamedCasProxyDeciderTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(NamedCasProxyDeciderTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testAcceptsIfNearestProxyIsAuthorized()
|
||||
throws Exception {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
// Build the ticket returned from CAS
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
|
||||
// Build the list of valid nearest proxies
|
||||
List validProxies = new Vector();
|
||||
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
|
||||
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
proxyDecider.setValidProxies(validProxies);
|
||||
proxyDecider.afterPropertiesSet();
|
||||
|
||||
proxyDecider.confirmProxyListTrusted(proxyList);
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
public void testAcceptsIfNoProxiesInTicket() {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
List proxyList = new Vector(); // no proxies in list
|
||||
|
||||
proxyDecider.confirmProxyListTrusted(proxyList);
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
public void testDetectsMissingValidProxiesList() throws Exception {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
try {
|
||||
proxyDecider.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("A validProxies list must be set", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDoesNotAcceptNull() {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
try {
|
||||
proxyDecider.confirmProxyListTrusted(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("proxyList cannot be null", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
// Build the list of valid nearest proxies
|
||||
List validProxies = new Vector();
|
||||
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
|
||||
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
proxyDecider.setValidProxies(validProxies);
|
||||
|
||||
assertEquals(validProxies, proxyDecider.getValidProxies());
|
||||
}
|
||||
|
||||
public void testRejectsIfNearestProxyIsNotAuthorized()
|
||||
throws Exception {
|
||||
NamedCasProxyDecider proxyDecider = new NamedCasProxyDecider();
|
||||
|
||||
// Build the ticket returned from CAS
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/untrustedWebApp/j_spring_cas_security_check");
|
||||
|
||||
// Build the list of valid nearest proxies
|
||||
List validProxies = new Vector();
|
||||
validProxies.add("https://localhost/portal/j_spring_cas_security_check");
|
||||
validProxies.add("https://localhost/newPortal/j_spring_cas_security_check");
|
||||
proxyDecider.setValidProxies(validProxies);
|
||||
proxyDecider.afterPropertiesSet();
|
||||
|
||||
try {
|
||||
proxyDecider.confirmProxyListTrusted(proxyList);
|
||||
fail("Should have thrown ProxyUntrustedException");
|
||||
} catch (ProxyUntrustedException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
-84
@@ -1,84 +0,0 @@
|
||||
/* 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.providers.cas.proxy;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.providers.cas.ProxyUntrustedException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link RejectProxyTickets}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class RejectProxyTicketsTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public RejectProxyTicketsTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public RejectProxyTicketsTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(RejectProxyTicketsTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testAcceptsIfNoProxiesInTicket() {
|
||||
RejectProxyTickets proxyDecider = new RejectProxyTickets();
|
||||
List proxyList = new Vector(); // no proxies in list
|
||||
|
||||
proxyDecider.confirmProxyListTrusted(proxyList);
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
public void testDoesNotAcceptNull() {
|
||||
RejectProxyTickets proxyDecider = new RejectProxyTickets();
|
||||
|
||||
try {
|
||||
proxyDecider.confirmProxyListTrusted(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("proxyList cannot be null", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testRejectsIfAnyProxyInList() {
|
||||
RejectProxyTickets proxyDecider = new RejectProxyTickets();
|
||||
List proxyList = new Vector();
|
||||
proxyList.add("https://localhost/webApp/j_spring_cas_security_check");
|
||||
|
||||
try {
|
||||
proxyDecider.confirmProxyListTrusted(proxyList);
|
||||
fail("Should have thrown ProxyUntrustedException");
|
||||
} catch (ProxyUntrustedException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
/* 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.providers.cas.ticketvalidator;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.AuthenticationException;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
|
||||
import org.springframework.security.providers.cas.TicketResponse;
|
||||
|
||||
import org.springframework.security.ui.cas.ServiceProperties;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AbstractTicketValidator}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AbstractTicketValidatorTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public AbstractTicketValidatorTests() {
|
||||
}
|
||||
|
||||
public AbstractTicketValidatorTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public void testDetectsMissingCasValidate() throws Exception {
|
||||
AbstractTicketValidator tv = new MockAbstractTicketValidator();
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
|
||||
try {
|
||||
tv.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("A casValidate URL must be set", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingServiceProperties() throws Exception {
|
||||
AbstractTicketValidator tv = new MockAbstractTicketValidator();
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
|
||||
try {
|
||||
tv.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("serviceProperties must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetters() throws Exception {
|
||||
AbstractTicketValidator tv = new MockAbstractTicketValidator();
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
assertEquals("https://company.com/cas/proxyvalidate", tv.getCasValidate());
|
||||
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
assertTrue(tv.getServiceProperties() != null);
|
||||
|
||||
tv.afterPropertiesSet();
|
||||
|
||||
tv.setTrustStore("/some/file/cacerts");
|
||||
assertEquals("/some/file/cacerts", tv.getTrustStore());
|
||||
}
|
||||
|
||||
public void testTrustStoreSystemPropertySetDuringAfterPropertiesSet() throws Exception {
|
||||
AbstractTicketValidator tv = new MockAbstractTicketValidator();
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
|
||||
// We need an existing file to use as the truststore property
|
||||
Resource r = new ClassPathResource("log4j.properties");
|
||||
String filename = r.getFile().getAbsolutePath();
|
||||
|
||||
tv.setTrustStore(filename);
|
||||
assertEquals(filename, tv.getTrustStore());
|
||||
|
||||
String before = System.getProperty("javax.net.ssl.trustStore");
|
||||
tv.afterPropertiesSet();
|
||||
assertEquals(filename, System.getProperty("javax.net.ssl.trustStore"));
|
||||
|
||||
if (before == null) {
|
||||
System.setProperty("javax.net.ssl.trustStore", "");
|
||||
} else {
|
||||
System.setProperty("javax.net.ssl.trustStore", before);
|
||||
}
|
||||
}
|
||||
|
||||
public void testMissingTrustStoreFileCausesException() throws Exception {
|
||||
AbstractTicketValidator tv = new MockAbstractTicketValidator();
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
tv.setTrustStore("/non/existent/file");
|
||||
|
||||
try {
|
||||
tv.afterPropertiesSet();
|
||||
|
||||
fail("Expected exception with non-existent truststore");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockAbstractTicketValidator extends AbstractTicketValidator {
|
||||
private boolean returnTicket;
|
||||
|
||||
public MockAbstractTicketValidator(boolean returnTicket) {
|
||||
this.returnTicket = returnTicket;
|
||||
}
|
||||
|
||||
private MockAbstractTicketValidator() {
|
||||
}
|
||||
|
||||
public TicketResponse confirmTicketValid(String serviceTicket)
|
||||
throws AuthenticationException {
|
||||
if (returnTicket) {
|
||||
return new TicketResponse("user", new Vector(),
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
}
|
||||
|
||||
throw new BadCredentialsException("As requested by mock");
|
||||
}
|
||||
}
|
||||
}
|
||||
-136
@@ -1,136 +0,0 @@
|
||||
/* 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.providers.cas.ticketvalidator;
|
||||
|
||||
import edu.yale.its.tp.cas.client.ProxyTicketValidator;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.AuthenticationServiceException;
|
||||
import org.springframework.security.BadCredentialsException;
|
||||
|
||||
import org.springframework.security.providers.cas.TicketResponse;
|
||||
|
||||
import org.springframework.security.ui.cas.ServiceProperties;
|
||||
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link CasProxyTicketValidator}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class CasProxyTicketValidatorTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
|
||||
public CasProxyTicketValidatorTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CasProxyTicketValidatorTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(CasProxyTicketValidatorTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testGetters() {
|
||||
CasProxyTicketValidator tv = new CasProxyTicketValidator();
|
||||
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
|
||||
assertEquals("http://my.com/webapp/casProxy/someValidator", tv.getProxyCallbackUrl());
|
||||
}
|
||||
|
||||
public void testNormalOperation() {
|
||||
ServiceProperties sp = new ServiceProperties();
|
||||
sp.setSendRenew(true);
|
||||
sp.setService("https://my.com/webapp//j_spring_cas_security_check");
|
||||
|
||||
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(true, false);
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
tv.setServiceProperties(sp);
|
||||
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
|
||||
|
||||
TicketResponse response = tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
|
||||
|
||||
assertEquals("user", response.getUser());
|
||||
}
|
||||
|
||||
public void testProxyTicketValidatorInternalExceptionsGracefullyHandled() {
|
||||
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(false, true);
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
tv.setProxyCallbackUrl("http://my.com/webapp/casProxy/someValidator");
|
||||
|
||||
try {
|
||||
tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
|
||||
fail("Should have thrown AuthenticationServiceException");
|
||||
} catch (AuthenticationServiceException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testValidationFailsOkAndOperationWithoutAProxyCallbackUrl() {
|
||||
CasProxyTicketValidator tv = new MockCasProxyTicketValidator(false, false);
|
||||
tv.setCasValidate("https://company.com/cas/proxyvalidate");
|
||||
tv.setServiceProperties(new ServiceProperties());
|
||||
|
||||
try {
|
||||
tv.confirmTicketValid("ST-0-ER94xMJmn6pha35CQRoZ");
|
||||
fail("Should have thrown BadCredentialsExpected");
|
||||
} catch (BadCredentialsException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockCasProxyTicketValidator extends CasProxyTicketValidator {
|
||||
private boolean returnTicket;
|
||||
private boolean throwAuthenticationServiceException;
|
||||
|
||||
public MockCasProxyTicketValidator(boolean returnTicket, boolean throwAuthenticationServiceException) {
|
||||
this.returnTicket = returnTicket;
|
||||
this.throwAuthenticationServiceException = throwAuthenticationServiceException;
|
||||
}
|
||||
|
||||
private MockCasProxyTicketValidator() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected TicketResponse validateNow(ProxyTicketValidator pv)
|
||||
throws AuthenticationServiceException, BadCredentialsException {
|
||||
if (returnTicket) {
|
||||
return new TicketResponse("user", new Vector(),
|
||||
"PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt");
|
||||
}
|
||||
|
||||
if (throwAuthenticationServiceException) {
|
||||
throw new AuthenticationServiceException("As requested by mock");
|
||||
}
|
||||
|
||||
throw new BadCredentialsException("As requested by mock");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.MockAclManager;
|
||||
import org.springframework.security.MockApplicationContext;
|
||||
|
||||
import org.springframework.security.acl.AclEntry;
|
||||
import org.springframework.security.acl.AclManager;
|
||||
import org.springframework.security.acl.basic.MockAclObjectIdentity;
|
||||
import org.springframework.security.acl.basic.SimpleAclEntry;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.PageContext;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AclTag}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AclTagTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final MyAclTag aclTag = new MyAclTag();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenAclManagerUnawareOfObject()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION).toString());
|
||||
aclTag.setDomainObject(new Integer(54));
|
||||
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenNoListOfPermissionsGiven()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(null);
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenPrincipalDoesNotHoldAnyPermissions()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ));
|
||||
assertEquals(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ),
|
||||
aclTag.getHasPermission());
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals("object1", aclTag.getDomainObject());
|
||||
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenPrincipalDoesNotHoldRequiredPermissions()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(new Integer(SimpleAclEntry.DELETE).toString());
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenSecurityContextEmpty()
|
||||
throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
aclTag.setHasPermission(new Long(SimpleAclEntry.ADMINISTRATION).toString());
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals(Tag.SKIP_BODY, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testInclusionPermittedWhenDomainObjectIsNull()
|
||||
throws JspException {
|
||||
aclTag.setHasPermission(new Integer(SimpleAclEntry.READ).toString());
|
||||
aclTag.setDomainObject(null);
|
||||
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testJspExceptionThrownIfHasPermissionNotValidFormat()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission("0,5, 6"); // shouldn't be any space
|
||||
|
||||
try {
|
||||
aclTag.doStartTag();
|
||||
fail("Should have thrown JspException");
|
||||
} catch (JspException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalHoldsPermissionOfMultipleList()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ));
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalHoldsPermissionOfSingleList()
|
||||
throws JspException {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
aclTag.setHasPermission(new Integer(SimpleAclEntry.READ).toString());
|
||||
aclTag.setDomainObject("object1");
|
||||
assertEquals(Tag.EVAL_BODY_INCLUDE, aclTag.doStartTag());
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockAclEntry implements AclEntry {
|
||||
// just so AclTag iterates some different types of AclEntrys
|
||||
}
|
||||
|
||||
private class MyAclTag extends AclTag {
|
||||
protected ApplicationContext getContext(PageContext pageContext) {
|
||||
ConfigurableApplicationContext context = MockApplicationContext.getContext();
|
||||
|
||||
// Create an AclManager
|
||||
AclManager aclManager = new MockAclManager("object1", "rod",
|
||||
new AclEntry[] {
|
||||
new MockAclEntry(),
|
||||
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
|
||||
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.READ)
|
||||
});
|
||||
|
||||
// Register the AclManager into our ApplicationContext
|
||||
context.getBeanFactory().registerSingleton("aclManager", aclManager);
|
||||
|
||||
return context;
|
||||
}
|
||||
}
|
||||
}
|
||||
-126
@@ -1,126 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
import org.springframework.security.userdetails.User;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AuthenticationTag}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AuthenticationTagTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final MyAuthenticationTag authenticationTag = new MyAuthenticationTag();
|
||||
private final Authentication auth = new TestingAuthenticationToken(new User("rodUserDetails", "koala", true, true, true,
|
||||
true, new GrantedAuthority[] {}), "koala", new GrantedAuthority[] {});
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalIsAUserDetailsInstance()throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authenticationTag.setProperty("name");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
assertEquals("rodUserDetails", authenticationTag.getLastMessage());
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalIsAString() throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("rodAsString", "koala", new GrantedAuthority[] {}));
|
||||
|
||||
authenticationTag.setProperty("principal");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
assertEquals("rodAsString", authenticationTag.getLastMessage());
|
||||
}
|
||||
|
||||
public void testNestedPropertyIsReadCorrectly() throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authenticationTag.setProperty("principal.username");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
assertEquals("rodUserDetails", authenticationTag.getLastMessage());
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalIsNull() throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken(null, "koala", new GrantedAuthority[] {}));
|
||||
|
||||
authenticationTag.setProperty("principal");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
}
|
||||
|
||||
public void testOperationWhenSecurityContextIsNull() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
authenticationTag.setProperty("principal");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
assertEquals(null, authenticationTag.getLastMessage());
|
||||
}
|
||||
|
||||
public void testSkipsBodyIfNullOrEmptyOperation() throws Exception {
|
||||
authenticationTag.setProperty("");
|
||||
assertEquals(Tag.SKIP_BODY, authenticationTag.doStartTag());
|
||||
assertEquals(Tag.EVAL_PAGE, authenticationTag.doEndTag());
|
||||
}
|
||||
|
||||
public void testThrowsExceptionForUnrecognisedProperty() {
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
authenticationTag.setProperty("qsq");
|
||||
|
||||
try {
|
||||
authenticationTag.doStartTag();
|
||||
authenticationTag.doEndTag();
|
||||
fail("Should have throwns JspException");
|
||||
} catch (JspException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MyAuthenticationTag extends AuthenticationTag {
|
||||
String lastMessage = null;
|
||||
|
||||
public String getLastMessage() {
|
||||
return lastMessage;
|
||||
}
|
||||
|
||||
protected void writeMessage(String msg) throws JspException {
|
||||
lastMessage = msg;
|
||||
}
|
||||
}
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author Francois Beausoleil
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AuthorizeTagAttributeTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final AuthorizeTag authorizeTag = new AuthorizeTag();
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_RESTRICTED"),
|
||||
});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAssertsIfAllGrantedSecond() throws JspException {
|
||||
authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER");
|
||||
authorizeTag.setIfAnyGranted("ROLE_RESTRICTED");
|
||||
assertEquals("prevents request - principal is missing ROLE_SUPERTELLER", Tag.SKIP_BODY,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testAssertsIfAnyGrantedLast() throws JspException {
|
||||
authorizeTag.setIfAnyGranted("ROLE_BANKER");
|
||||
assertEquals("prevents request - principal is missing ROLE_BANKER", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testAssertsIfNotGrantedFirst() throws JspException {
|
||||
authorizeTag.setIfNotGranted("ROLE_RESTRICTED");
|
||||
authorizeTag.setIfAllGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED");
|
||||
authorizeTag.setIfAnyGranted("ROLE_SUPERVISOR");
|
||||
assertEquals("prevents request - principal has ROLE_RESTRICTED", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute()
|
||||
throws JspException {
|
||||
authorizeTag.setIfAnyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER ");
|
||||
assertEquals("allows request - principal has ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testIfAllGrantedIgnoresWhitespaceInAttribute()
|
||||
throws JspException {
|
||||
authorizeTag.setIfAllGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r ");
|
||||
assertEquals("allows request - principal has ROLE_RESTRICTED " + "and ROLE_SUPERVISOR", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testIfNotGrantedIgnoresWhitespaceInAttribute()
|
||||
throws JspException {
|
||||
authorizeTag.setIfNotGranted(" \t ROLE_TELLER \r");
|
||||
assertEquals("allows request - principal does not have ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author Francois Beausoleil
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AuthorizeTagCustomGrantedAuthorityTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final AuthorizeTag authorizeTag = new AuthorizeTag();
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {new CustomGrantedAuthority("ROLE_TELLER")});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAllowsRequestWhenCustomAuthorityPresentsCorrectRole()
|
||||
throws JspException {
|
||||
authorizeTag.setIfAnyGranted("ROLE_TELLER");
|
||||
assertEquals("authorized - ROLE_TELLER in both sets", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testRejectsRequestWhenCustomAuthorityReturnsNull()
|
||||
throws JspException {
|
||||
authorizeTag.setIfAnyGranted("ROLE_TELLER");
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {new CustomGrantedAuthority(null)}));
|
||||
|
||||
try {
|
||||
authorizeTag.doStartTag();
|
||||
fail("Failed to reject GrantedAuthority with NULL getAuthority()");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue("expected", true);
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private static class CustomGrantedAuthority implements GrantedAuthority {
|
||||
private final String authority;
|
||||
|
||||
public CustomGrantedAuthority(String authority) {
|
||||
this.authority = authority;
|
||||
}
|
||||
|
||||
public String getAuthority() {
|
||||
return authority;
|
||||
}
|
||||
}
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import org.springframework.mock.web.MockPageContext;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* Test case to implement commons-el expression language expansion.
|
||||
*/
|
||||
public class AuthorizeTagExpressionLanguageTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final AuthorizeTag authorizeTag = new AuthorizeTag();
|
||||
private MockPageContext pageContext;
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
pageContext = new MockPageContext();
|
||||
authorizeTag.setPageContext(pageContext);
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_TELLER"),});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAllGrantedUsesExpressionLanguageWhenExpressionIsEL()
|
||||
throws JspException {
|
||||
pageContext.setAttribute("authority", "ROLE_TELLER");
|
||||
authorizeTag.setIfAllGranted("${authority}");
|
||||
|
||||
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testAnyGrantedUsesExpressionLanguageWhenExpressionIsEL()
|
||||
throws JspException {
|
||||
pageContext.setAttribute("authority", "ROLE_TELLER");
|
||||
authorizeTag.setIfAnyGranted("${authority}");
|
||||
|
||||
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testNotGrantedUsesExpressionLanguageWhenExpressionIsEL()
|
||||
throws JspException {
|
||||
pageContext.setAttribute("authority", "ROLE_TELLER");
|
||||
authorizeTag.setIfNotGranted("${authority}");
|
||||
|
||||
assertEquals("allows body - authority var contains ROLE_TELLER", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
/* 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.taglibs.authz;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
import javax.servlet.jsp.tagext.Tag;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*
|
||||
* @author Francois Beausoleil
|
||||
* @version $Id$
|
||||
*/
|
||||
public class AuthorizeTagTests extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final AuthorizeTag authorizeTag = new AuthorizeTag();
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE SUPERVISOR"), new GrantedAuthorityImpl("ROLE_TELLER"),
|
||||
});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAlwaysReturnsUnauthorizedIfNoUserFound() throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
authorizeTag.setIfAllGranted("ROLE_TELLER");
|
||||
assertEquals("prevents request - no principal in Context", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() throws JspException {
|
||||
assertEquals("", authorizeTag.getIfAllGranted());
|
||||
assertEquals("", authorizeTag.getIfAnyGranted());
|
||||
assertEquals("", authorizeTag.getIfNotGranted());
|
||||
|
||||
assertEquals("prevents body output - no authorities granted", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testOutputsBodyIfOneRolePresent() throws JspException {
|
||||
authorizeTag.setIfAnyGranted("ROLE_TELLER");
|
||||
assertEquals("authorized - ROLE_TELLER in both sets", Tag.EVAL_BODY_INCLUDE, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testOutputsBodyWhenAllGranted() throws JspException {
|
||||
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER");
|
||||
assertEquals("allows request - all required roles granted on principal", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testOutputsBodyWhenNotGrantedSatisfied() throws JspException {
|
||||
authorizeTag.setIfNotGranted("ROLE_BANKER");
|
||||
assertEquals("allows request - principal doesn't have ROLE_BANKER", Tag.EVAL_BODY_INCLUDE,
|
||||
authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testPreventsBodyOutputIfNoSecurityContext() throws JspException {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
authorizeTag.setIfAnyGranted("ROLE_BANKER");
|
||||
|
||||
assertEquals("prevents output - no context defined", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testSkipsBodyIfNoAnyRolePresent() throws JspException {
|
||||
authorizeTag.setIfAnyGranted("ROLE_BANKER");
|
||||
assertEquals("unauthorized - ROLE_BANKER not in granted authorities", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testSkipsBodyWhenMissingAnAllGranted() throws JspException {
|
||||
authorizeTag.setIfAllGranted("ROLE SUPERVISOR,ROLE_TELLER,ROLE_BANKER");
|
||||
assertEquals("prevents request - missing ROLE_BANKER on principal", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
|
||||
public void testSkipsBodyWhenNotGrantedUnsatisfied() throws JspException {
|
||||
authorizeTag.setIfNotGranted("ROLE_TELLER");
|
||||
assertEquals("prevents request - principal has ROLE_TELLER", Tag.SKIP_BODY, authorizeTag.doStartTag());
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
/* 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.taglibs.velocity;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import javax.servlet.jsp.JspException;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*/
|
||||
public class AuthzImplAttributeTest extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private final Authz authz = new AuthzImpl();
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_RESTRICTED"),
|
||||
});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAssertsIfAllGrantedSecond() {
|
||||
boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_SUPERTELLER");
|
||||
boolean r2 = authz.anyGranted("ROLE_RESTRICTED");
|
||||
|
||||
//prevents request - principal is missing ROLE_SUPERTELLE
|
||||
assertFalse(r1 && r2);
|
||||
}
|
||||
|
||||
public void testAssertsIfAnyGrantedLast() {
|
||||
boolean r2 = authz.anyGranted("ROLE_BANKER");
|
||||
|
||||
// prevents request - principal is missing ROLE_BANKER
|
||||
assertFalse(r2);
|
||||
}
|
||||
|
||||
public void testAssertsIfNotGrantedFirst() {
|
||||
boolean r1 = authz.allGranted("ROLE_SUPERVISOR,ROLE_RESTRICTED");
|
||||
boolean r2 = authz.noneGranted("ROLE_RESTRICTED");
|
||||
boolean r3 = authz.anyGranted("ROLE_SUPERVISOR");
|
||||
|
||||
//prevents request - principal has ROLE_RESTRICTED
|
||||
assertFalse(r1 && r2 && r3);
|
||||
}
|
||||
|
||||
public void testAssertsIfNotGrantedIgnoresWhitespaceInAttribute() {
|
||||
//allows request - principal has ROLE_SUPERVISOR
|
||||
assertTrue(authz.anyGranted("\tROLE_SUPERVISOR \t, \r\n\t ROLE_TELLER "));
|
||||
}
|
||||
|
||||
public void testIfAllGrantedIgnoresWhitespaceInAttribute() {
|
||||
//allows request - principal has ROLE_RESTRICTED and ROLE_SUPERVISOR
|
||||
assertTrue(authz.allGranted("\nROLE_SUPERVISOR\t,ROLE_RESTRICTED\t\n\r "));
|
||||
}
|
||||
|
||||
public void testIfNotGrantedIgnoresWhitespaceInAttribute()
|
||||
throws JspException {
|
||||
//prevents request - principal does not have ROLE_TELLER
|
||||
assertFalse(authz.allGranted(" \t ROLE_TELLER \r"));
|
||||
}
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
/* 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.taglibs.velocity;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.GrantedAuthorityImpl;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*/
|
||||
public class AuthzImplAuthorizeTagTest extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private Authz authz = new AuthzImpl();
|
||||
private TestingAuthenticationToken currentUser;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
currentUser = new TestingAuthenticationToken("abc", "123",
|
||||
new GrantedAuthority[] {
|
||||
new GrantedAuthorityImpl("ROLE_SUPERVISOR"), new GrantedAuthorityImpl("ROLE_TELLER"),
|
||||
});
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(currentUser);
|
||||
}
|
||||
|
||||
protected void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
public void testAlwaysReturnsUnauthorizedIfNoUserFound() {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
//prevents request - no principal in Context
|
||||
assertFalse(authz.allGranted("ROLE_TELLER"));
|
||||
}
|
||||
|
||||
public void testDefaultsToNotOutputtingBodyWhenNoRequiredAuthorities() {
|
||||
//prevents body output - no authorities granted
|
||||
assertFalse(authz.allGranted(""));
|
||||
assertFalse(authz.anyGranted(""));
|
||||
assertFalse(authz.noneGranted(""));
|
||||
}
|
||||
|
||||
public void testOutputsBodyIfOneRolePresent() {
|
||||
//authorized - ROLE_TELLER in both sets
|
||||
assertTrue(authz.anyGranted("ROLE_TELLER"));
|
||||
}
|
||||
|
||||
public void testOutputsBodyWhenAllGranted() {
|
||||
// allows request - all required roles granted on principal
|
||||
assertTrue(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER"));
|
||||
}
|
||||
|
||||
public void testOutputsBodyWhenNotGrantedSatisfied() {
|
||||
// allows request - principal doesn't have ROLE_BANKER
|
||||
assertTrue(authz.noneGranted("ROLE_BANKER"));
|
||||
}
|
||||
|
||||
public void testPreventsBodyOutputIfNoSecureContext() {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
// prevents output - no context defined
|
||||
assertFalse(authz.anyGranted("ROLE_BANKER"));
|
||||
}
|
||||
|
||||
public void testSkipsBodyIfNoAnyRolePresent() {
|
||||
// unauthorized - ROLE_BANKER not in granted authorities
|
||||
assertFalse(authz.anyGranted("ROLE_BANKER"));
|
||||
}
|
||||
|
||||
public void testSkipsBodyWhenMissingAnAllGranted() {
|
||||
// prevents request - missing ROLE_BANKER on principal
|
||||
assertFalse(authz.allGranted("ROLE_SUPERVISOR,ROLE_TELLER,ROLE_BANKER"));
|
||||
}
|
||||
|
||||
public void testSkipsBodyWhenNotGrantedUnsatisfied() {
|
||||
// prevents request - principal has ROLE_TELLER
|
||||
assertFalse(authz.noneGranted("ROLE_TELLER"));
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
/* 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.taglibs.velocity;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.security.Authentication;
|
||||
import org.springframework.security.GrantedAuthority;
|
||||
import org.springframework.security.MockAclManager;
|
||||
|
||||
import org.springframework.security.acl.AclEntry;
|
||||
import org.springframework.security.acl.AclManager;
|
||||
import org.springframework.security.acl.basic.MockAclObjectIdentity;
|
||||
import org.springframework.security.acl.basic.SimpleAclEntry;
|
||||
|
||||
import org.springframework.security.context.SecurityContextHolder;
|
||||
|
||||
import org.springframework.security.providers.TestingAuthenticationToken;
|
||||
|
||||
import org.springframework.security.userdetails.User;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
|
||||
|
||||
/**
|
||||
* DOCUMENT ME!
|
||||
*/
|
||||
public class AuthzImplTest extends TestCase {
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
private Authz authz = new AuthzImpl();
|
||||
private ConfigurableApplicationContext ctx;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
/*String[] paths = { "applicationEmpty.xml" };
|
||||
ctx = new ClassPathXmlApplicationContext(paths);*/
|
||||
ctx = new StaticApplicationContext();
|
||||
|
||||
// Create an AclManager
|
||||
AclManager aclManager = new MockAclManager("object1", "rod",
|
||||
new AclEntry[] {
|
||||
new MockAclEntry(),
|
||||
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.ADMINISTRATION),
|
||||
new SimpleAclEntry("rod", new MockAclObjectIdentity(), null, SimpleAclEntry.READ)
|
||||
});
|
||||
|
||||
// Register the AclManager into our ApplicationContext
|
||||
ctx.getBeanFactory().registerSingleton("aclManager", aclManager);
|
||||
}
|
||||
|
||||
public void testIllegalArgumentExceptionThrownIfHasPermissionNotValidFormat() {
|
||||
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = "0,5, 6"; // shouldn't be any space
|
||||
|
||||
try {
|
||||
authz.hasPermission(null, permissions);
|
||||
} catch (IllegalArgumentException iae) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenAclManagerUnawareOfObject() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
boolean result = authz.hasPermission(new Integer(54), new Long(SimpleAclEntry.ADMINISTRATION).toString());
|
||||
|
||||
assertFalse(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenNoListOfPermissionsGiven() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
boolean result = authz.hasPermission("object1", null);
|
||||
|
||||
assertFalse(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenPrincipalDoesNotHoldAnyPermissions() {
|
||||
Authentication auth = new TestingAuthenticationToken("john", "crow", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ);
|
||||
|
||||
boolean result = authz.hasPermission("object1", permissions);
|
||||
|
||||
assertFalse(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenPrincipalDoesNotHoldRequiredPermissions() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Integer(SimpleAclEntry.DELETE).toString();
|
||||
|
||||
boolean result = authz.hasPermission("object1", permissions);
|
||||
|
||||
assertFalse(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionDeniedWhenSecurityContextEmpty() {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Long(SimpleAclEntry.ADMINISTRATION).toString();
|
||||
|
||||
boolean result = authz.hasPermission("object1", permissions);
|
||||
|
||||
assertFalse(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testInclusionPermittedWhenDomainObjectIsNull() {
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Integer(SimpleAclEntry.READ).toString();
|
||||
|
||||
boolean result = authz.hasPermission(null, permissions);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalHoldsPermissionOfMultipleList() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Integer(SimpleAclEntry.ADMINISTRATION) + "," + new Integer(SimpleAclEntry.READ);
|
||||
|
||||
boolean result = authz.hasPermission("object1", permissions);
|
||||
|
||||
assertTrue(result);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalHoldsPermissionOfSingleList() {
|
||||
Authentication auth = new TestingAuthenticationToken("rod", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
authz.setAppCtx(ctx);
|
||||
|
||||
String permissions = new Integer(SimpleAclEntry.READ).toString();
|
||||
|
||||
boolean result = authz.hasPermission("object1", permissions);
|
||||
|
||||
assertTrue(result);
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
/*
|
||||
* Test method for 'com.alibaba.exodus2.web.common.security.pulltool.AuthzImpl.getPrincipal()'
|
||||
*/
|
||||
public void testOperationWhenPrincipalIsAString() {
|
||||
Authentication auth = new TestingAuthenticationToken("rodAsString", "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
assertEquals("rodAsString", authz.getPrincipal());
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalIsAUserDetailsInstance() {
|
||||
Authentication auth = new TestingAuthenticationToken(new User("rodUserDetails", "koala", true, true, true,
|
||||
true, new GrantedAuthority[] {}), "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
assertEquals("rodUserDetails", authz.getPrincipal());
|
||||
}
|
||||
|
||||
public void testOperationWhenPrincipalIsNull() {
|
||||
Authentication auth = new TestingAuthenticationToken(null, "koala", new GrantedAuthority[] {});
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
assertNull(authz.getPrincipal());
|
||||
}
|
||||
|
||||
public void testOperationWhenSecurityContextIsNull() {
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
|
||||
assertEquals(null, authz.getPrincipal());
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(null);
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockAclEntry implements AclEntry {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
// just so AclTag iterates some different types of AclEntrys
|
||||
}
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
|
||||
|
||||
<!--
|
||||
- Application context containing business beans.
|
||||
-
|
||||
- Used by all artifacts.
|
||||
-
|
||||
- $Id:applicationContext-test.xml 1754 2006-11-17 02:01:21Z benalex $
|
||||
-->
|
||||
|
||||
<beans>
|
||||
|
||||
<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="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</value>
|
||||
</property>
|
||||
</bean>
|
||||
</constructor-arg>
|
||||
</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="test" />
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -1,27 +0,0 @@
|
||||
-- Not required. Just shows the sort of queries being sent to DB.
|
||||
|
||||
|
||||
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, ACL_SID ACLI_SID, ACL_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
|
||||
|
||||
ACLI_SID.ID = ACL_OBJECT_IDENTITY.OWNER_SID
|
||||
and ACL_CLASS.ID = ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS
|
||||
and (
|
||||
(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY = 1
|
||||
and ACL_CLASS.CLASS = 'sample.contact.Contact')
|
||||
or
|
||||
(ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY = 2000
|
||||
and ACL_CLASS.CLASS = 'sample.contact.Contact')
|
||||
) order by ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY asc, ACL_ENTRY.ACE_ORDER asc
|
||||
@@ -1,45 +0,0 @@
|
||||
-- Injected into DatabaseSeeder via applicationContext-test.xml (see test case JdbcAclServiceTests)
|
||||
|
||||
-- DROP TABLE ACL_ENTRY;
|
||||
-- DROP TABLE ACL_OBJECT_IDENTITY;
|
||||
-- DROP TABLE ACL_CLASS;
|
||||
-- DROP TABLE ACL_SID;
|
||||
|
||||
|
||||
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));
|
||||
|
||||
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));
|
||||
|
||||
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,
|
||||
OBJECT_ID_CLASS BIGINT NOT NULL,
|
||||
OBJECT_ID_IDENTITY BIGINT NOT NULL,
|
||||
PARENT_OBJECT BIGINT,
|
||||
OWNER_SID BIGINT,
|
||||
ENTRIES_INHERITING BOOLEAN NOT NULL,
|
||||
CONSTRAINT UNIQUE_UK_3 UNIQUE(OBJECT_ID_CLASS,OBJECT_ID_IDENTITY),
|
||||
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));
|
||||
|
||||
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,
|
||||
MASK INTEGER NOT NULL,
|
||||
GRANTING BOOLEAN NOT NULL,
|
||||
AUDIT_SUCCESS BOOLEAN NOT NULL,
|
||||
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));
|
||||
@@ -28,18 +28,14 @@
|
||||
|
||||
<!-- Setup a cache we can use in tests of the caching layer -->
|
||||
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
|
||||
<property name="configLocation">
|
||||
<value>classpath:/ehcache-failsafe.xml</value>
|
||||
</property>
|
||||
<property name="configLocation" value="classpath:/ehcache-failsafe.xml"/>
|
||||
</bean>
|
||||
|
||||
<bean id="eHCacheBackend" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
|
||||
<property name="cacheManager">
|
||||
<ref local="cacheManager"/>
|
||||
</property>
|
||||
<property name="cacheName">
|
||||
<value>testingCache</value>
|
||||
</property>
|
||||
<property name="cacheName" value="testingCache"/>
|
||||
</bean>
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user