Replace try/catch with AssertJ

Replace manual try/catch/fail blocks with AssertJ calls.
This commit is contained in:
Phillip Webb 2020-09-10 12:06:07 -07:00 committed by Josh Cummings
parent d9276ed8f3
commit 910b81928f
98 changed files with 717 additions and 2122 deletions

View File

@ -22,7 +22,8 @@ import org.springframework.security.acls.domain.AclFormattingUtils;
import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Permission;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/** /**
* Tests for {@link AclFormattingUtils}. * Tests for {@link AclFormattingUtils}.
@ -33,30 +34,11 @@ public class AclFormattingUtilsTests {
@Test @Test
public final void testDemergePatternsParametersConstraints() { public final void testDemergePatternsParametersConstraints() {
try { assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns(null, "SOME STRING"));
AclFormattingUtils.demergePatterns(null, "SOME STRING"); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", null));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING"));
catch (IllegalArgumentException expected) { assertThatNoException().isThrownBy(() -> AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH"));
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.demergePatterns("SOME STRING", "SAME LENGTH");
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
} }
@Test @Test
@ -71,29 +53,11 @@ public class AclFormattingUtilsTests {
@Test @Test
public final void testMergePatternsParametersConstraints() { public final void testMergePatternsParametersConstraints() {
try { assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns(null, "SOME STRING"));
AclFormattingUtils.mergePatterns(null, "SOME STRING"); assertThatIllegalArgumentException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", null));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING"));
catch (IllegalArgumentException expected) { assertThatNoException().isThrownBy(() -> AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH"));
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "LONGER SOME STRING");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
AclFormattingUtils.mergePatterns("SOME STRING", "SAME LENGTH");
}
catch (IllegalArgumentException notExpected) {
}
} }
@Test @Test
@ -108,18 +72,10 @@ public class AclFormattingUtilsTests {
@Test @Test
public final void testBinaryPrints() { public final void testBinaryPrints() {
assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****"); assertThat(AclFormattingUtils.printBinary(15)).isEqualTo("............................****");
try { assertThatIllegalArgumentException()
AclFormattingUtils.printBinary(15, Permission.RESERVED_ON); .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_ON));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF));
catch (IllegalArgumentException notExpected) {
}
try {
AclFormattingUtils.printBinary(15, Permission.RESERVED_OFF);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException notExpected) {
}
assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx"); assertThat(AclFormattingUtils.printBinary(15, 'x')).isEqualTo("............................xxxx");
} }

View File

@ -36,7 +36,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.core.SpringSecurityMessageSource;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -50,15 +51,12 @@ import static org.mockito.Mockito.verify;
@SuppressWarnings({ "unchecked" }) @SuppressWarnings({ "unchecked" })
public class AclEntryAfterInvocationProviderTests { public class AclEntryAfterInvocationProviderTests {
@Test(expected = IllegalArgumentException.class) @Test
public void rejectsMissingPermissions() { public void rejectsMissingPermissions() {
try { assertThatIllegalArgumentException()
new AclEntryAfterInvocationProvider(mock(AclService.class), null); .isThrownBy(() -> new AclEntryAfterInvocationProvider(mock(AclService.class), null));
fail("Exception expected"); assertThatIllegalArgumentException().isThrownBy(
} () -> new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList()));
catch (IllegalArgumentException expected) {
}
new AclEntryAfterInvocationProvider(mock(AclService.class), Collections.<Permission>emptyList());
} }
@Test @Test
@ -98,7 +96,7 @@ public class AclEntryAfterInvocationProviderTests {
SecurityConfig.createList("AFTER_ACL_READ"), returned)); SecurityConfig.createList("AFTER_ACL_READ"), returned));
} }
@Test(expected = AccessDeniedException.class) @Test
public void accessIsDeniedIfPermissionIsNotGranted() { public void accessIsDeniedIfPermissionIsNotGranted() {
AclService service = mock(AclService.class); AclService service = mock(AclService.class);
Acl acl = mock(Acl.class); Acl acl = mock(Acl.class);
@ -113,16 +111,13 @@ public class AclEntryAfterInvocationProviderTests {
provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class)); provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
provider.setProcessDomainObjectClass(Object.class); provider.setProcessDomainObjectClass(Object.class);
provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class)); provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
try { assertThatExceptionOfType(AccessDeniedException.class)
provider.decide(mock(Authentication.class), new Object(), .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
// Second scenario with no acls found // Second scenario with no acls found
provider.decide(mock(Authentication.class), new Object(), assertThatExceptionOfType(AccessDeniedException.class)
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()); .isThrownBy(() -> provider.decide(mock(Authentication.class), new Object(),
SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"), new Object()));
} }
@Test @Test

View File

@ -25,7 +25,7 @@ import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.Sid;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -39,27 +39,14 @@ public class AccessControlImplEntryTests {
@Test @Test
public void testConstructorRequiredFields() { public void testConstructorRequiredFields() {
// Check Acl field is present // Check Acl field is present
try { assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, null,
new AccessControlEntryImpl(null, null, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, new PrincipalSid("johndoe"), BasePermission.ADMINISTRATION, true, true, true));
true, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check Sid field is present // Check Sid field is present
try { assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class), null,
new AccessControlEntryImpl(null, mock(Acl.class), null, BasePermission.ADMINISTRATION, true, true, true); BasePermission.ADMINISTRATION, true, true, true));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check Permission field is present // Check Permission field is present
try { assertThatIllegalArgumentException().isThrownBy(() -> new AccessControlEntryImpl(null, mock(Acl.class),
new AccessControlEntryImpl(null, mock(Acl.class), new PrincipalSid("johndoe"), null, true, true, true); new PrincipalSid("johndoe"), null, true, true, true));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -46,7 +46,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.util.FieldUtils; import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -97,58 +98,38 @@ public class AclImplTests {
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorsRejectNullObjectIdentity() { public void constructorsRejectNullObjectIdentity() {
try { assertThatIllegalArgumentException().isThrownBy(
new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")); () -> new AclImpl(null, 1, this.authzStrategy, this.pgs, null, null, true, new PrincipalSid("joe")));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger));
catch (IllegalArgumentException expected) {
}
new AclImpl(null, 1, this.authzStrategy, this.mockAuditLogger);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void constructorsRejectNullId() { public void constructorsRejectNullId() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy,
new AclImpl(this.objectIdentity, null, this.authzStrategy, this.pgs, null, null, true, this.pgs, null, null, true, new PrincipalSid("joe")));
new PrincipalSid("joe")); assertThatIllegalArgumentException()
fail("Should have thrown IllegalArgumentException"); .isThrownBy(() -> new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger));
}
catch (IllegalArgumentException expected) {
}
new AclImpl(this.objectIdentity, null, this.authzStrategy, this.mockAuditLogger);
} }
@SuppressWarnings("deprecation") @Test
@Test(expected = IllegalArgumentException.class)
public void constructorsRejectNullAclAuthzStrategy() { public void constructorsRejectNullAclAuthzStrategy() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null,
new AclImpl(this.objectIdentity, 1, null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, new DefaultPermissionGrantingStrategy(this.mockAuditLogger), null, null, true,
null, true, new PrincipalSid("joe")); new PrincipalSid("joe")));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger));
catch (IllegalArgumentException expected) {
}
new AclImpl(this.objectIdentity, 1, null, this.mockAuditLogger);
} }
@Test @Test
public void insertAceRejectsNullParameters() { public void insertAceRejectsNullParameters() {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
try { assertThatIllegalArgumentException()
acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true); .isThrownBy(() -> acl.insertAce(0, null, new GrantedAuthoritySid("ROLE_IGNORED"), true));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> acl.insertAce(0, BasePermission.READ, null, true));
}
catch (IllegalArgumentException expected) {
}
try {
acl.insertAce(0, BasePermission.READ, null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -232,12 +213,7 @@ public class AclImplTests {
new SimpleGrantedAuthority("ROLE_GENERAL")); new SimpleGrantedAuthority("ROLE_GENERAL"));
MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true, MutableAcl acl = new AclImpl(this.objectIdentity, (1), strategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
try { assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> acl.deleteAce(99));
acl.deleteAce(99);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
} }
@Test @Test
@ -245,18 +221,9 @@ public class AclImplTests {
MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true, MutableAcl acl = new AclImpl(this.objectIdentity, 1, this.authzStrategy, this.pgs, null, null, true,
new PrincipalSid("joe")); new PrincipalSid("joe"));
Sid ben = new PrincipalSid("ben"); Sid ben = new PrincipalSid("ben");
try { assertThatIllegalArgumentException()
acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false); .isThrownBy(() -> acl.isGranted(new ArrayList<>(0), Arrays.asList(ben), false));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> acl.isGranted(READ, new ArrayList<>(0), false));
}
catch (IllegalArgumentException expected) {
}
try {
acl.isGranted(READ, new ArrayList<>(0), false);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -277,25 +244,16 @@ public class AclImplTests {
List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE); List<Permission> permissions = Arrays.asList(BasePermission.READ, BasePermission.CREATE);
List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST")); List<Sid> sids = Arrays.asList(new PrincipalSid("ben"), new GrantedAuthoritySid("ROLE_GUEST"));
assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse(); assertThat(rootAcl.isGranted(permissions, sids, false)).isFalse();
try { assertThatExceptionOfType(NotFoundException.class)
rootAcl.isGranted(permissions, SCOTT, false); .isThrownBy(() -> rootAcl.isGranted(permissions, SCOTT, false));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue(); assertThat(rootAcl.isGranted(WRITE, SCOTT, false)).isTrue();
assertThat(rootAcl.isGranted(WRITE, assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse(); Arrays.asList(new PrincipalSid("rod"), new GrantedAuthoritySid("WRITE_ACCESS_ROLE")), false)).isFalse();
assertThat(rootAcl.isGranted(WRITE, assertThat(rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue(); Arrays.asList(new GrantedAuthoritySid("WRITE_ACCESS_ROLE"), new PrincipalSid("rod")), false)).isTrue();
try {
// Change the type of the Sid and check the granting process // Change the type of the Sid and check the granting process
rootAcl.isGranted(WRITE, assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> rootAcl.isGranted(WRITE,
Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false); Arrays.asList(new GrantedAuthoritySid("rod"), new PrincipalSid("WRITE_ACCESS_ROLE")), false));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
} }
@Test @Test
@ -348,18 +306,9 @@ public class AclImplTests {
assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse(); assertThat(childAcl1.isGranted(DELETE, BEN, false)).isFalse();
// Check granting process for child2 (doesn't inherit the permissions from its // Check granting process for child2 (doesn't inherit the permissions from its
// parent) // parent)
try { assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> childAcl2.isGranted(CREATE, SCOTT, false));
assertThat(childAcl2.isGranted(CREATE, SCOTT, false)).isTrue(); assertThatExceptionOfType(NotFoundException.class)
fail("It should have thrown NotFoundException"); .isThrownBy(() -> childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false));
}
catch (NotFoundException expected) {
}
try {
childAcl2.isGranted(CREATE, Arrays.asList((Sid) new PrincipalSid("joe")), false);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
} }
@Test @Test

View File

@ -30,7 +30,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
/** /**
* Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl} security * Test class for {@link AclAuthorizationStrategyImpl} and {@link AclImpl} security
@ -72,24 +73,12 @@ public class AclImplementationSecurityCheckTests {
new SimpleGrantedAuthority("ROLE_THREE")); new SimpleGrantedAuthority("ROLE_THREE"));
Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger()); Acl acl2 = new AclImpl(identity, 1L, aclAuthorizationStrategy2, new ConsoleAuditLogger());
// Check access in case the principal has no authorization rights // Check access in case the principal has no authorization rights
try { assertThatExceptionOfType(NotFoundException.class).isThrownBy(
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL); () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_GENERAL));
fail("It should have thrown NotFoundException"); assertThatExceptionOfType(NotFoundException.class).isThrownBy(
} () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING));
catch (NotFoundException expected) { assertThatExceptionOfType(NotFoundException.class).isThrownBy(
} () -> aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy2.securityCheck(acl2, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
} }
@Test @Test
@ -112,28 +101,16 @@ public class AclImplementationSecurityCheckTests {
// The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the // The CHANGE_AUDITING and CHANGE_OWNERSHIP should fail since the
// principal doesn't have these authorities, // principal doesn't have these authorities,
// nor granting access // nor granting access
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING); () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING));
fail("It should have thrown AccessDeniedException"); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
} () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
catch (AccessDeniedException expected) {
}
try {
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// Add granting access to this principal // Add granting access to this principal
aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true); aclFirstDeny.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), true);
// and try again for CHANGE_AUDITING - the first ACE's granting flag // and try again for CHANGE_AUDITING - the first ACE's granting flag
// (false) will deny this access // (false) will deny this access
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(
aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING); () -> aclAuthorizationStrategy.securityCheck(aclFirstDeny, AclAuthorizationStrategy.CHANGE_AUDITING));
fail("It should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
// Create another ACL and give the principal the ADMINISTRATION // Create another ACL and give the principal the ADMINISTRATION
// permission, with granting access // permission, with granting access
MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl aclFirstAllow = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
@ -143,27 +120,15 @@ public class AclImplementationSecurityCheckTests {
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING); aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING);
// Add a deny ACE and test again for CHANGE_AUDITING // Add a deny ACE and test again for CHANGE_AUDITING
aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false); aclFirstAllow.insertAce(1, BasePermission.ADMINISTRATION, new PrincipalSid(auth), false);
try { assertThatNoException().isThrownBy(
aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING); () -> aclAuthorizationStrategy.securityCheck(aclFirstAllow, AclAuthorizationStrategy.CHANGE_AUDITING));
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
// Create an ACL with no ACE // Create an ACL with no ACE
MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl aclNoACE = new AclImpl(identity, 1L, aclAuthorizationStrategy, new ConsoleAuditLogger());
try { assertThatExceptionOfType(NotFoundException.class).isThrownBy(
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING); () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_AUDITING));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// and still grant access for CHANGE_GENERAL // and still grant access for CHANGE_GENERAL
try { assertThatNoException().isThrownBy(
aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL); () -> aclAuthorizationStrategy.securityCheck(aclNoACE, AclAuthorizationStrategy.CHANGE_GENERAL));
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
} }
@Test @Test
@ -184,22 +149,14 @@ public class AclImplementationSecurityCheckTests {
MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl childAcl = new AclImpl(identity, 2, aclAuthorizationStrategy, new ConsoleAuditLogger());
// Check against the 'child' acl, which doesn't offer any authorization // Check against the 'child' acl, which doesn't offer any authorization
// rights on CHANGE_OWNERSHIP // rights on CHANGE_OWNERSHIP
try { assertThatExceptionOfType(NotFoundException.class).isThrownBy(
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Link the child with its parent and test again against the // Link the child with its parent and test again against the
// CHANGE_OWNERSHIP right // CHANGE_OWNERSHIP right
childAcl.setParent(parentAcl); childAcl.setParent(parentAcl);
childAcl.setEntriesInheriting(true); childAcl.setEntriesInheriting(true);
try { assertThatNoException().isThrownBy(
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
// Create a root parent and link it to the middle parent // Create a root parent and link it to the middle parent
MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); MutableAcl rootParentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger()); parentAcl = new AclImpl(identity, 1, aclAuthorizationStrategy, new ConsoleAuditLogger());
@ -207,12 +164,8 @@ public class AclImplementationSecurityCheckTests {
parentAcl.setEntriesInheriting(true); parentAcl.setEntriesInheriting(true);
parentAcl.setParent(rootParentAcl); parentAcl.setParent(rootParentAcl);
childAcl.setParent(parentAcl); childAcl.setParent(parentAcl);
try { assertThatNoException().isThrownBy(
aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP); () -> aclAuthorizationStrategy.securityCheck(childAcl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
}
catch (NotFoundException expected) {
fail("It shouldn't have thrown NotFoundException");
}
} }
@Test @Test
@ -227,24 +180,12 @@ public class AclImplementationSecurityCheckTests {
Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy, Acl acl = new AclImpl(identity, 1, aclAuthorizationStrategy,
new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false, new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()), null, null, false,
new PrincipalSid(auth)); new PrincipalSid(auth));
try { assertThatNoException()
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL); .isThrownBy(() -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_GENERAL));
} assertThatExceptionOfType(NotFoundException.class).isThrownBy(
catch (AccessDeniedException notExpected) { () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING));
fail("It shouldn't have thrown AccessDeniedException"); assertThatNoException().isThrownBy(
} () -> aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP));
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_AUDITING);
fail("It shouldn't have thrown AccessDeniedException");
}
catch (NotFoundException expected) {
}
try {
aclAuthorizationStrategy.securityCheck(acl, AclAuthorizationStrategy.CHANGE_OWNERSHIP);
}
catch (AccessDeniedException notExpected) {
fail("It shouldn't have thrown AccessDeniedException");
}
} }
} }

View File

@ -21,7 +21,9 @@ import org.junit.Test;
import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentity;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/** /**
* Tests for {@link ObjectIdentityImpl}. * Tests for {@link ObjectIdentityImpl}.
@ -36,40 +38,15 @@ public class ObjectIdentityImplTests {
@Test @Test
public void constructorsRespectRequiredFields() { public void constructorsRespectRequiredFields() {
// Check one-argument constructor required field // Check one-argument constructor required field
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(null));
new ObjectIdentityImpl(null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check String-Serializable constructor required field // Check String-Serializable constructor required field
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl("", 1L));
new ObjectIdentityImpl("", 1L);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// Check Serializable parameter is not null // Check Serializable parameter is not null
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, null));
new ObjectIdentityImpl(DOMAIN_CLASS, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// The correct way of using String-Serializable constructor // The correct way of using String-Serializable constructor
try { assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(DOMAIN_CLASS, 1L));
new ObjectIdentityImpl(DOMAIN_CLASS, 1L);
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
// Check the Class-Serializable constructor // Check the Class-Serializable constructor
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(MockIdDomainObject.class, null));
new ObjectIdentityImpl(MockIdDomainObject.class, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -82,35 +59,17 @@ public class ObjectIdentityImplTests {
@Test @Test
public void testGetIdMethodConstraints() { public void testGetIdMethodConstraints() {
// Check the getId() method is present // Check the getId() method is present
try { assertThatExceptionOfType(IdentityUnavailableException.class)
new ObjectIdentityImpl("A_STRING_OBJECT"); .isThrownBy(() -> new ObjectIdentityImpl("A_STRING_OBJECT"));
fail("It should have thrown IdentityUnavailableException");
}
catch (IdentityUnavailableException expected) {
}
// getId() should return a non-null value // getId() should return a non-null value
MockIdDomainObject mockId = new MockIdDomainObject(); MockIdDomainObject mockId = new MockIdDomainObject();
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// getId() should return a Serializable object // getId() should return a Serializable object
mockId.setId(new MockIdDomainObject()); mockId.setId(new MockIdDomainObject());
try { assertThatIllegalArgumentException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
new ObjectIdentityImpl(mockId);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
// getId() should return a Serializable object // getId() should return a Serializable object
mockId.setId(100L); mockId.setId(100L);
try { assertThatNoException().isThrownBy(() -> new ObjectIdentityImpl(mockId));
new ObjectIdentityImpl(mockId);
}
catch (IllegalArgumentException expected) {
}
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)

View File

@ -48,14 +48,12 @@ import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.Acl; import org.springframework.security.acls.model.Acl;
import org.springframework.security.acls.model.AuditableAccessControlEntry; import org.springframework.security.acls.model.AuditableAccessControlEntry;
import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAcl;
import org.springframework.security.acls.model.NotFoundException;
import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.ObjectIdentity;
import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid; import org.springframework.security.acls.model.Sid;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
/** /**
* Tests {@link BasicLookupStrategy} * Tests {@link BasicLookupStrategy}
@ -290,12 +288,7 @@ public abstract class AbstractBasicLookupStrategyTests {
// is already in cache and the element before it must not be stored in // is already in cache and the element before it must not be stored in
// cache // cache
List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid); List<ObjectIdentity> allOids = Arrays.asList(grandParentOid, parent1Oid, parent2Oid, childOid);
try {
foundAcls = this.strategy.readAclsById(allOids, sids); foundAcls = this.strategy.readAclsById(allOids, sids);
}
catch (NotFoundException notExpected) {
fail("It shouldn't have thrown NotFoundException");
}
Acl foundParent2Acl = foundAcls.get(parent2Oid); Acl foundParent2Acl = foundAcls.get(parent2Oid);
assertThat(foundParent2Acl).isNotNull(); assertThat(foundParent2Acl).isNotNull();
assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue(); assertThat(foundParent2Acl.isGranted(checkPermission, sids, false)).isTrue();

View File

@ -52,7 +52,7 @@ import org.springframework.security.util.FieldUtils;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -102,41 +102,11 @@ public class EhCacheBasedAclCacheTests {
@Test @Test
public void methodsRejectNullParameters() { public void methodsRejectNullParameters() {
try { assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((Serializable) null));
Serializable id = null; assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.evictFromCache((ObjectIdentity) null));
this.myCache.evictFromCache(id); assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((Serializable) null));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.getFromCache((ObjectIdentity) null));
} assertThatIllegalArgumentException().isThrownBy(() -> this.myCache.putInCache(null));
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.evictFromCache(obj);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
Serializable id = null;
this.myCache.getFromCache(id);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
ObjectIdentity obj = null;
this.myCache.getFromCache(obj);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
MutableAcl acl = null;
this.myCache.putInCache(acl);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
// SEC-527 // SEC-527

View File

@ -55,7 +55,8 @@ import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
@ -161,91 +162,80 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService Map<ObjectIdentity, Acl> map = this.jdbcMutableAclService
.readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid())); .readAclsById(Arrays.asList(getTopParentOid(), getMiddleParentOid(), getChildOid()));
assertThat(map).hasSize(3); assertThat(map).hasSize(3);
// Replace our current objects with their retrieved versions // Get the retrieved versions
topParent = (MutableAcl) map.get(getTopParentOid()); MutableAcl retrievedTopParent = (MutableAcl) map.get(getTopParentOid());
middleParent = (MutableAcl) map.get(getMiddleParentOid()); MutableAcl retrievedMiddleParent = (MutableAcl) map.get(getMiddleParentOid());
child = (MutableAcl) map.get(getChildOid()); MutableAcl retrievedChild = (MutableAcl) map.get(getChildOid());
// Check the retrieved versions has IDs // Check the retrieved versions has IDs
assertThat(topParent.getId()).isNotNull(); assertThat(retrievedTopParent.getId()).isNotNull();
assertThat(middleParent.getId()).isNotNull(); assertThat(retrievedMiddleParent.getId()).isNotNull();
assertThat(child.getId()).isNotNull(); assertThat(retrievedChild.getId()).isNotNull();
// Check their parents were correctly persisted // Check their parents were correctly persisted
assertThat(topParent.getParentAcl()).isNull(); assertThat(retrievedTopParent.getParentAcl()).isNull();
assertThat(middleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid()); assertThat(retrievedMiddleParent.getParentAcl().getObjectIdentity()).isEqualTo(getTopParentOid());
assertThat(child.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); assertThat(retrievedChild.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Check their ACEs were correctly persisted // Check their ACEs were correctly persisted
assertThat(topParent.getEntries()).hasSize(2); assertThat(retrievedTopParent.getEntries()).hasSize(2);
assertThat(middleParent.getEntries()).hasSize(1); assertThat(retrievedMiddleParent.getEntries()).hasSize(1);
assertThat(child.getEntries()).hasSize(1); assertThat(retrievedChild.getEntries()).hasSize(1);
// Check the retrieved rights are correct // Check the retrieved rights are correct
List<Permission> read = Arrays.asList(BasePermission.READ); List<Permission> read = Arrays.asList(BasePermission.READ);
List<Permission> write = Arrays.asList(BasePermission.WRITE); List<Permission> write = Arrays.asList(BasePermission.WRITE);
List<Permission> delete = Arrays.asList(BasePermission.DELETE); List<Permission> delete = Arrays.asList(BasePermission.DELETE);
List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth)); List<Sid> pSid = Arrays.asList((Sid) new PrincipalSid(this.auth));
assertThat(topParent.isGranted(read, pSid, false)).isTrue(); assertThat(retrievedTopParent.isGranted(read, pSid, false)).isTrue();
assertThat(topParent.isGranted(write, pSid, false)).isFalse(); assertThat(retrievedTopParent.isGranted(write, pSid, false)).isFalse();
assertThat(middleParent.isGranted(delete, pSid, false)).isTrue(); assertThat(retrievedMiddleParent.isGranted(delete, pSid, false)).isTrue();
assertThat(child.isGranted(delete, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse();
try { assertThatExceptionOfType(NotFoundException.class)
child.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false); .isThrownBy(() -> retrievedChild.isGranted(Arrays.asList(BasePermission.ADMINISTRATION), pSid, false));
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Now check the inherited rights (when not explicitly overridden) also look OK // Now check the inherited rights (when not explicitly overridden) also look OK
assertThat(child.isGranted(read, pSid, false)).isTrue(); assertThat(retrievedChild.isGranted(read, pSid, false)).isTrue();
assertThat(child.isGranted(write, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(write, pSid, false)).isFalse();
assertThat(child.isGranted(delete, pSid, false)).isFalse(); assertThat(retrievedChild.isGranted(delete, pSid, false)).isFalse();
// Next change the child so it doesn't inherit permissions from above // Next change the child so it doesn't inherit permissions from above
child.setEntriesInheriting(false); retrievedChild.setEntriesInheriting(false);
this.jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(retrievedChild);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); MutableAcl nonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.isEntriesInheriting()).isFalse(); assertThat(nonInheritingChild.isEntriesInheriting()).isFalse();
// Check the child permissions no longer inherit // Check the child permissions no longer inherit
assertThat(child.isGranted(delete, pSid, true)).isFalse(); assertThat(nonInheritingChild.isGranted(delete, pSid, true)).isFalse();
try { assertThatExceptionOfType(NotFoundException.class)
child.isGranted(read, pSid, true); .isThrownBy(() -> nonInheritingChild.isGranted(read, pSid, true));
fail("Should have thrown NotFoundException"); assertThatExceptionOfType(NotFoundException.class)
} .isThrownBy(() -> nonInheritingChild.isGranted(write, pSid, true));
catch (NotFoundException expected) {
}
try {
child.isGranted(write, pSid, true);
fail("Should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
// Let's add an identical permission to the child, but it'll appear AFTER the // Let's add an identical permission to the child, but it'll appear AFTER the
// current permission, so has no impact // current permission, so has no impact
child.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true); nonInheritingChild.insertAce(1, BasePermission.DELETE, new PrincipalSid(this.auth), true);
// Let's also add another permission to the child // Let's also add another permission to the child
child.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true); nonInheritingChild.insertAce(2, BasePermission.CREATE, new PrincipalSid(this.auth), true);
// Save the changed child // Save the changed child
this.jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(nonInheritingChild);
child = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid()); MutableAcl retrievedNonInheritingChild = (MutableAcl) this.jdbcMutableAclService.readAclById(getChildOid());
assertThat(child.getEntries()).hasSize(3); assertThat(retrievedNonInheritingChild.getEntries()).hasSize(3);
// Output permissions // Output permissions
for (int i = 0; i < child.getEntries().size(); i++) { for (int i = 0; i < retrievedNonInheritingChild.getEntries().size(); i++) {
System.out.println(child.getEntries().get(i)); System.out.println(retrievedNonInheritingChild.getEntries().get(i));
} }
// Check the permissions are as they should be // Check the permissions are as they should be
assertThat(child.isGranted(delete, pSid, true)).isFalse(); // as earlier assertThat(retrievedNonInheritingChild.isGranted(delete, pSid, true)).isFalse(); // as
// earlier
// permission // permission
// overrode // overrode
assertThat(child.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue(); assertThat(retrievedNonInheritingChild.isGranted(Arrays.asList(BasePermission.CREATE), pSid, true)).isTrue();
// Now check the first ACE (index 0) really is DELETE for our Sid and is // Now check the first ACE (index 0) really is DELETE for our Sid and is
// non-granting // non-granting
AccessControlEntry entry = child.getEntries().get(0); AccessControlEntry entry = retrievedNonInheritingChild.getEntries().get(0);
assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask()); assertThat(entry.getPermission().getMask()).isEqualTo(BasePermission.DELETE.getMask());
assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth)); assertThat(entry.getSid()).isEqualTo(new PrincipalSid(this.auth));
assertThat(entry.isGranting()).isFalse(); assertThat(entry.isGranting()).isFalse();
assertThat(entry.getId()).isNotNull(); assertThat(entry.getId()).isNotNull();
// Now delete that first ACE // Now delete that first ACE
child.deleteAce(0); retrievedNonInheritingChild.deleteAce(0);
// Save and check it worked // Save and check it worked
child = this.jdbcMutableAclService.updateAcl(child); MutableAcl savedChild = this.jdbcMutableAclService.updateAcl(retrievedNonInheritingChild);
assertThat(child.getEntries()).hasSize(2); assertThat(savedChild.getEntries()).hasSize(2);
assertThat(child.isGranted(delete, pSid, false)).isTrue(); assertThat(savedChild.isGranted(delete, pSid, false)).isTrue();
SecurityContextHolder.clearContext(); SecurityContextHolder.clearContext();
} }
@ -267,18 +257,10 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid()); assertThat(childAcl.getParentAcl().getObjectIdentity()).isEqualTo(getMiddleParentOid());
// Delete the mid-parent and test if the child was deleted, as well // Delete the mid-parent and test if the child was deleted, as well
this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true); this.jdbcMutableAclService.deleteAcl(getMiddleParentOid(), true);
try { assertThatExceptionOfType(NotFoundException.class)
this.jdbcMutableAclService.readAclById(getMiddleParentOid()); .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getMiddleParentOid()));
fail("It should have thrown NotFoundException"); assertThatExceptionOfType(NotFoundException.class)
} .isThrownBy(() -> this.jdbcMutableAclService.readAclById(getChildOid()));
catch (NotFoundException expected) {
}
try {
this.jdbcMutableAclService.readAclById(getChildOid());
fail("It should have thrown NotFoundException");
}
catch (NotFoundException expected) {
}
Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid()); Acl acl = this.jdbcMutableAclService.readAclById(getTopParentOid());
assertThat(acl).isNotNull(); assertThat(acl).isNotNull();
assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity()); assertThat(getTopParentOid()).isEqualTo(acl.getObjectIdentity());
@ -286,34 +268,17 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
@Test @Test
public void constructorRejectsNullParameters() { public void constructorRejectsNullParameters() {
try { assertThatIllegalArgumentException()
new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache); .isThrownBy(() -> new JdbcMutableAclService(null, this.lookupStrategy, this.aclCache));
fail("It should have thrown IllegalArgumentException"); assertThatIllegalArgumentException()
} .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, null, this.aclCache));
catch (IllegalArgumentException expected) { assertThatIllegalArgumentException()
} .isThrownBy(() -> new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null));
try {
new JdbcMutableAclService(this.dataSource, null, this.aclCache);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new JdbcMutableAclService(this.dataSource, this.lookupStrategy, null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void createAclRejectsNullParameter() { public void createAclRejectsNullParameter() {
try { assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.createAcl(null));
this.jdbcMutableAclService.createAcl(null);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -323,23 +288,14 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L); ObjectIdentity duplicateOid = new ObjectIdentityImpl(TARGET_CLASS, 100L);
this.jdbcMutableAclService.createAcl(duplicateOid); this.jdbcMutableAclService.createAcl(duplicateOid);
// Try to add the same object second time // Try to add the same object second time
try { assertThatExceptionOfType(AlreadyExistsException.class)
this.jdbcMutableAclService.createAcl(duplicateOid); .isThrownBy(() -> this.jdbcMutableAclService.createAcl(duplicateOid));
fail("It should have thrown AlreadyExistsException");
}
catch (AlreadyExistsException expected) {
}
} }
@Test @Test
@Transactional @Transactional
public void deleteAclRejectsNullParameters() { public void deleteAclRejectsNullParameters() {
try { assertThatIllegalArgumentException().isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(null, true));
this.jdbcMutableAclService.deleteAcl(null, true);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -351,18 +307,16 @@ public class JdbcMutableAclServiceTests extends AbstractTransactionalJUnit4Sprin
// Specify the inheritance hierarchy // Specify the inheritance hierarchy
child.setParent(parent); child.setParent(parent);
this.jdbcMutableAclService.updateAcl(child); this.jdbcMutableAclService.updateAcl(child);
// switch on FK
this.jdbcMutableAclService.setForeignKeysInDatabase(false);
try { try {
this.jdbcMutableAclService.setForeignKeysInDatabase(false); // switch on FK // checking in the class, not database
// checking in the assertThatExceptionOfType(ChildrenExistException.class)
// class, not database .isThrownBy(() -> this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false));
this.jdbcMutableAclService.deleteAcl(getTopParentOid(), false);
fail("It should have thrown ChildrenExistException");
}
catch (ChildrenExistException expected) {
} }
finally { finally {
this.jdbcMutableAclService.setForeignKeysInDatabase(true); // restore to the // restore to the default
// default this.jdbcMutableAclService.setForeignKeysInDatabase(true);
} }
} }

View File

@ -32,92 +32,36 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
public class SidTests { public class SidTests {
@Test @Test
public void testPrincipalSidConstructorsRequiredFields() { public void testPrincipalSidConstructorsRequiredFields() {
// Check one String-argument constructor // Check one String-argument constructor
try { assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((String) null));
String string = null; assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid(""));
new PrincipalSid(string); assertThatNoException().isThrownBy(() -> new PrincipalSid("johndoe"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new PrincipalSid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
new PrincipalSid("johndoe");
// throws no exception
// Check one Authentication-argument constructor // Check one Authentication-argument constructor
try { assertThatIllegalArgumentException().isThrownBy(() -> new PrincipalSid((Authentication) null));
Authentication authentication = null; assertThatIllegalArgumentException()
new PrincipalSid(authentication); .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken(null, "password")));
fail("It should have thrown IllegalArgumentException"); assertThatNoException()
} .isThrownBy(() -> new PrincipalSid(new TestingAuthenticationToken("johndoe", "password")));
catch (IllegalArgumentException expected) {
}
try {
Authentication authentication = new TestingAuthenticationToken(null, "password");
new PrincipalSid(authentication);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
Authentication authentication = new TestingAuthenticationToken("johndoe", "password");
new PrincipalSid(authentication);
// throws no exception
} }
@Test @Test
public void testGrantedAuthoritySidConstructorsRequiredFields() { public void testGrantedAuthoritySidConstructorsRequiredFields() {
// Check one String-argument constructor // Check one String-argument constructor
try { assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((String) null));
String string = null; assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid(""));
new GrantedAuthoritySid(string); assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid("ROLE_TEST"));
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("");
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new GrantedAuthoritySid("ROLE_TEST");
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
// Check one GrantedAuthority-argument constructor // Check one GrantedAuthority-argument constructor
try { assertThatIllegalArgumentException().isThrownBy(() -> new GrantedAuthoritySid((GrantedAuthority) null));
GrantedAuthority ga = null; assertThatIllegalArgumentException()
new GrantedAuthoritySid(ga); .isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority(null)));
fail("It should have thrown IllegalArgumentException"); assertThatNoException().isThrownBy(() -> new GrantedAuthoritySid(new SimpleGrantedAuthority("ROLE_TEST")));
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority(null);
new GrantedAuthoritySid(ga);
fail("It should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
new GrantedAuthoritySid(ga);
}
catch (IllegalArgumentException notExpected) {
fail("It shouldn't have thrown IllegalArgumentException");
}
} }
@Test @Test

View File

@ -49,7 +49,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -112,12 +112,7 @@ public class AnnotationSecurityAspectTests {
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
public void internalPrivateCallIsIntercepted() { public void internalPrivateCallIsIntercepted() {
SecurityContextHolder.getContext().setAuthentication(this.anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate());
this.secured.publicCallsPrivate();
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
this.securedSub.publicCallsPrivate(); this.securedSub.publicCallsPrivate();
} }

View File

@ -41,6 +41,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -192,20 +193,10 @@ public class CasAuthenticationProviderTests {
result = cap.authenticate(token); result = cap.authenticate(token);
verify(validator, times(2)).validate(ticket, serviceUrl); verify(validator, times(2)).validate(ticket, serviceUrl);
token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
try { assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.authenticate(token);
fail("Expected Exception");
}
catch (IllegalStateException success) {
}
cap.setServiceProperties(null); cap.setServiceProperties(null);
cap.afterPropertiesSet(); cap.afterPropertiesSet();
try { assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token));
cap.authenticate(token);
fail("Expected Exception");
}
catch (IllegalStateException success) {
}
} }
@Test(expected = BadCredentialsException.class) @Test(expected = BadCredentialsException.class)

View File

@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link CasAuthenticationToken}. * Tests {@link CasAuthenticationToken}.
@ -52,44 +53,19 @@ public class CasAuthenticationTokenTests {
@Test @Test
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
final Assertion assertion = new AssertionImpl("test"); Assertion assertion = new AssertionImpl("test");
try { assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken(null, makeUserDetails(),
new CasAuthenticationToken(null, makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); "Password", this.ROLES, makeUserDetails(), assertion));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(
} () -> new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion));
catch (IllegalArgumentException expected) { assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), null,
} this.ROLES, makeUserDetails(), assertion));
try { assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(),
new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion); "Password", this.ROLES, makeUserDetails(), null));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(
} () -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion));
catch (IllegalArgumentException expected) { assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(),
} "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion));
try {
new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new CasAuthenticationToken("key", makeUserDetails(), "Password",
AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
@ -125,12 +101,8 @@ public class CasAuthenticationTokenTests {
@Test @Test
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
try { assertThatExceptionOfType(NoSuchMethodException.class)
CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null); .isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
} }
@Test @Test

View File

@ -24,7 +24,7 @@ import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link EhCacheBasedTicketCache}. * Tests {@link EhCacheBasedTicketCache}.
@ -67,12 +67,7 @@ public class EhCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTe
@Test @Test
public void testStartupDetectsMissingCache() throws Exception { public void testStartupDetectsMissingCache() throws Exception {
EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache(); EhCacheBasedTicketCache cache = new EhCacheBasedTicketCache();
try { assertThatIllegalArgumentException().isThrownBy(cache::afterPropertiesSet);
cache.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
Ehcache myCache = cacheManager.getCache("castickets"); Ehcache myCache = cacheManager.getCache("castickets");
cache.setCache(myCache); cache.setCache(myCache);
assertThat(cache.getCache()).isEqualTo(myCache); assertThat(cache.getCache()).isEqualTo(myCache);

View File

@ -25,7 +25,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.ServiceProperties;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link CasAuthenticationEntryPoint}. * Tests {@link CasAuthenticationEntryPoint}.
@ -38,26 +38,16 @@ public class CasAuthenticationEntryPointTests {
public void testDetectsMissingLoginFormUrl() throws Exception { public void testDetectsMissingLoginFormUrl() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setServiceProperties(new ServiceProperties()); ep.setServiceProperties(new ServiceProperties());
try { assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
ep.afterPropertiesSet(); .withMessage("loginUrl must be specified");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("loginUrl must be specified");
}
} }
@Test @Test
public void testDetectsMissingServiceProperties() throws Exception { public void testDetectsMissingServiceProperties() throws Exception {
CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint();
ep.setLoginUrl("https://cas/login"); ep.setLoginUrl("https://cas/login");
try { assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
ep.afterPropertiesSet(); .withMessage("serviceProperties must be specified");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("serviceProperties must be specified");
}
} }
@Test @Test

View File

@ -22,7 +22,7 @@ import org.springframework.security.cas.SamlServiceProperties;
import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.ServiceProperties;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link ServiceProperties}. * Tests {@link ServiceProperties}.
@ -41,19 +41,9 @@ public class ServicePropertiesTests {
public void nullServiceWhenAuthenticateAllTokens() throws Exception { public void nullServiceWhenAuthenticateAllTokens() throws Exception {
ServiceProperties sp = new ServiceProperties(); ServiceProperties sp = new ServiceProperties();
sp.setAuthenticateAllArtifacts(true); sp.setAuthenticateAllArtifacts(true);
try { assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
sp.afterPropertiesSet();
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
sp.setAuthenticateAllArtifacts(false); sp.setAuthenticateAllArtifacts(false);
try { assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet);
sp.afterPropertiesSet();
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
} }
@Test @Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.config.authentication.AuthenticationManagerF
import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests which make sure invalid configurations are rejected by the namespace. In * Tests which make sure invalid configurations are rejected by the namespace. In
@ -59,17 +59,14 @@ public class InvalidConfigurationTests {
@Test @Test
public void missingAuthenticationManagerGivesSensibleErrorMessage() { public void missingAuthenticationManagerGivesSensibleErrorMessage() {
try { assertThatExceptionOfType(BeanCreationException.class)
setContext("<http auto-config='true' />"); .isThrownBy(() -> setContext("<http auto-config='true' />")).satisfies((ex) -> {
fail();
}
catch (BeanCreationException ex) {
Throwable cause = ultimateCause(ex); Throwable cause = ultimateCause(ex);
assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause; NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER); assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE); assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
} });
} }
private Throwable ultimateCause(Throwable ex) { private Throwable ultimateCause(Throwable ex) {

View File

@ -32,8 +32,7 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -78,15 +77,11 @@ public class SecurityNamespaceHandlerTests {
@Test @Test
public void pre32SchemaAreNotSupported() { public void pre32SchemaAreNotSupported() {
try { assertThatExceptionOfType(BeanDefinitionParsingException.class)
new InMemoryXmlApplicationContext("<user-service id='us'>" .isThrownBy(() -> new InMemoryXmlApplicationContext(
+ " <user name='bob' password='bobspassword' authorities='ROLE_A' />" + "</user-service>", "3.0.3", "<user-service id='us'><user name='bob' password='bobspassword' authorities='ROLE_A' /></user-service>",
null); "3.0.3", null))
fail("Expected BeanDefinitionParsingException"); .withMessageContaining("You cannot use a spring-security-2.0.xsd");
}
catch (BeanDefinitionParsingException expected) {
assertThat(expected.getMessage().contains("You cannot use a spring-security-2.0.xsd"));
}
} }
// SEC-1868 // SEC-1868

View File

@ -54,6 +54,7 @@ import org.springframework.security.test.web.servlet.response.SecurityMockMvcRes
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -91,11 +92,8 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0)); given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep) AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build(); .inMemoryAuthentication().and().build();
try { assertThatExceptionOfType(AuthenticationException.class)
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); .isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")));
}
catch (AuthenticationException success) {
}
verify(aep).publishAuthenticationFailure(any(), any()); verify(aep).publishAuthenticationFailure(any(), any());
} }

View File

@ -110,11 +110,8 @@ public class GlobalMethodSecurityConfigurationTests {
@Test @Test
public void methodSecurityAuthenticationManagerPublishesEvent() { public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire(); this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
try { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")); () -> this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")));
}
catch (AuthenticationException ex) {
}
assertThat(this.events.getEvents()).extracting(Object::getClass) assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class); .containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
} }

View File

@ -45,8 +45,7 @@ import org.springframework.web.socket.config.annotation.AbstractWebSocketMessage
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests { public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
@ -76,13 +75,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
public void securityMappings() { public void securityMappings() {
loadConfig(WebSocketSecurityConfig.class); loadConfig(WebSocketSecurityConfig.class);
clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE)); clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE));
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)); .isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
private void loadConfig(Class<?>... configs) { private void loadConfig(Class<?>... configs) {

View File

@ -78,7 +78,7 @@ import org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHa
import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession; import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class AbstractSecurityWebSocketMessageBrokerConfigurerTests { public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
@ -108,13 +108,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void simpleRegistryMappings() { public void simpleRegistryMappings() {
loadConfig(SockJsSecurityConfig.class); loadConfig(SockJsSecurityConfig.class);
clientInboundChannel().send(message("/permitAll")); clientInboundChannel().send(message("/permitAll"));
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/denyAll")); .isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
@Test @Test
@ -158,13 +154,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication"); Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel(); MessageChannel messageChannel = clientInboundChannel();
try { assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
messageChannel.send(message); .withCauseInstanceOf(MissingCsrfTokenException.class);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
} }
@Test @Test
@ -173,13 +164,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
Message<?> message = message(headers, "/authentication"); Message<?> message = message(headers, "/authentication");
MessageChannel messageChannel = clientInboundChannel(); MessageChannel messageChannel = clientInboundChannel();
try { assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
messageChannel.send(message); .withCauseInstanceOf(MissingCsrfTokenException.class);
fail("Expected Exception");
}
catch (MessageDeliveryException success) {
assertThat(success.getCause()).isInstanceOf(MissingCsrfTokenException.class);
}
} }
@Test @Test
@ -236,39 +222,27 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
public void msmsRegistryCustomPatternMatcher() { public void msmsRegistryCustomPatternMatcher() {
loadConfig(MsmsRegistryCustomPatternMatcherConfig.class); loadConfig(MsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a.b")); clientInboundChannel().send(message("/app/a.b"));
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/app/a.b.c")); .isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
@Test @Test
public void overrideMsmsRegistryCustomPatternMatcher() { public void overrideMsmsRegistryCustomPatternMatcher() {
loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class); loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b")); clientInboundChannel().send(message("/app/a/b"));
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/app/a/b/c")); .isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
@Test @Test
public void defaultPatternMatcher() { public void defaultPatternMatcher() {
loadConfig(DefaultPatternMatcherConfig.class); loadConfig(DefaultPatternMatcherConfig.class);
clientInboundChannel().send(message("/app/a/b")); clientInboundChannel().send(message("/app/a/b"));
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/app/a/b/c")); .isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
@Test @Test
@ -276,13 +250,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
loadConfig(CustomExpressionConfig.class); loadConfig(CustomExpressionConfig.class);
clientInboundChannel().send(message("/denyRob")); clientInboundChannel().send(message("/denyRob"));
this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER"); this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER");
try { assertThatExceptionOfType(MessageDeliveryException.class)
clientInboundChannel().send(message("/denyRob")); .isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
fail("Expected Exception"); .withCauseInstanceOf(AccessDeniedException.class);
}
catch (MessageDeliveryException expected) {
assertThat(expected.getCause()).isInstanceOf(AccessDeniedException.class);
}
} }
@Test @Test

View File

@ -59,7 +59,7 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.util.FieldUtils; import org.springframework.security.util.FieldUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Ben Alex * @author Ben Alex
@ -174,13 +174,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// someOther(int) should not be matched by someOther(String), but should require // someOther(int) should not be matched by someOther(String), but should require
// ROLE_USER // ROLE_USER
this.target.someOther(0); this.target.someOther(0);
try {
// String version should required admin role // String version should required admin role
this.target.someOther("somestring"); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.target.someOther("somestring"));
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
} }
@Test @Test
@ -199,12 +194,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// String method should not be protected // String method should not be protected
this.target.someOther("somestring"); this.target.someOther("somestring");
// All others should require ROLE_USER // All others should require ROLE_USER
try { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
this.target.someOther(0); .isThrownBy(() -> this.target.someOther(0));
fail("Expected AuthenticationCredentialsNotFoundException");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("user", "password")); .setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
this.target.someOther(0); this.target.someOther(0);
@ -389,12 +380,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// External MDS should take precedence over PreAuthorize // External MDS should take precedence over PreAuthorize
SecurityContextHolder.getContext().setAuthentication(this.bob); SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target"); Foo foo = (Foo) this.appContext.getBean("target");
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A")); foo.foo(new SecurityConfig("A"));
@ -415,12 +401,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests {
// @formatter:on // @formatter:on
SecurityContextHolder.getContext().setAuthentication(this.bob); SecurityContextHolder.getContext().setAuthentication(this.bob);
Foo foo = (Foo) this.appContext.getBean("target"); Foo foo = (Foo) this.appContext.getBean("target");
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> foo.foo(new SecurityConfig("A")));
foo.foo(new SecurityConfig("A"));
fail("Bob can't invoke admin methods");
}
catch (AccessDeniedException expected) {
}
SecurityContextHolder.getContext() SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password")); .setAuthentication(new UsernamePasswordAuthenticationToken("admin", "password"));
foo.foo(new SecurityConfig("A")); foo.foo(new SecurityConfig("A"));

View File

@ -36,6 +36,8 @@ import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Ben Alex * @author Ben Alex
*/ */
@ -93,11 +95,8 @@ public class SecuredAnnotationDrivenBeanDefinitionParserTests {
@Test(expected = AccessDeniedException.class) @Test(expected = AccessDeniedException.class)
public void targetIsSerializableAfterUse() throws Exception { public void targetIsSerializableAfterUse() throws Exception {
try { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
this.target.someAdminMethod(); .isThrownBy(this.target::someAdminMethod);
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A")); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("u", "p", "ROLE_A"));
BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target); BusinessService chompedTarget = (BusinessService) serializeAndDeserialize(this.target);
chompedTarget.someAdminMethod(); chompedTarget.someAdminMethod();

View File

@ -26,7 +26,7 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.config.util.InMemoryXmlApplicationContext; import org.springframework.security.config.util.InMemoryXmlApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for SEC-428 (and SEC-1204). * Tests for SEC-428 (and SEC-1204).
@ -97,12 +97,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on // @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target"); ITargetObject target = (ITargetObject) this.appContext.getBean("target");
// Check both against interface and class // Check both against interface and class
try { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
target.makeLowerCase("TEST"); .isThrownBy(() -> target.makeLowerCase("TEST"));
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
target.makeUpperCase("test"); target.makeUpperCase("test");
} }
@ -128,12 +124,8 @@ public class MethodSecurityInterceptorWithAopConfigTests {
// @formatter:on // @formatter:on
ITargetObject target = (ITargetObject) this.appContext.getBean("target"); ITargetObject target = (ITargetObject) this.appContext.getBean("target");
try { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
target.makeLowerCase("TEST"); .isThrownBy(() -> target.makeLowerCase("TEST"));
fail("AuthenticationCredentialsNotFoundException expected");
}
catch (AuthenticationCredentialsNotFoundException expected) {
}
target.makeUpperCase("test"); target.makeUpperCase("test");
} }

View File

@ -25,7 +25,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
/** /**
* Tests for {@link RoleHierarchyImpl}. * Tests for {@link RoleHierarchyImpl}.
@ -102,48 +103,23 @@ public class RoleHierarchyImplTests {
@Test @Test
public void testCyclesInRoleHierarchy() { public void testCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try { assertThatExceptionOfType(CycleInRoleHierarchyException.class)
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"); .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_A"));
fail("Cycle in role hierarchy was not detected!"); assertThatExceptionOfType(CycleInRoleHierarchyException.class)
} .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"));
catch (CycleInRoleHierarchyException ex) { assertThatExceptionOfType(CycleInRoleHierarchyException.class)
} .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A"));
try { assertThatExceptionOfType(CycleInRoleHierarchyException.class).isThrownBy(() -> roleHierarchyImpl
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_A"); .setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B"));
fail("Cycle in role hierarchy was not detected!"); assertThatExceptionOfType(CycleInRoleHierarchyException.class)
} .isThrownBy(() -> roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B"));
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_A");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy(
"ROLE_A > ROLE_B\nROLE_B > ROLE_C\nROLE_C > ROLE_E\nROLE_E > ROLE_D\nROLE_D > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
try {
roleHierarchyImpl.setHierarchy("ROLE_C > ROLE_B\nROLE_B > ROLE_A\nROLE_A > ROLE_B");
fail("Cycle in role hierarchy was not detected!");
}
catch (CycleInRoleHierarchyException ex) {
}
} }
@Test @Test
public void testNoCyclesInRoleHierarchy() { public void testNoCyclesInRoleHierarchy() {
RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl(); RoleHierarchyImpl roleHierarchyImpl = new RoleHierarchyImpl();
try { assertThatNoException().isThrownBy(() -> roleHierarchyImpl
roleHierarchyImpl.setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"); .setHierarchy("ROLE_A > ROLE_B\nROLE_A > ROLE_C\nROLE_C > ROLE_D\nROLE_B > ROLE_D"));
}
catch (CycleInRoleHierarchyException ex) {
fail("A cycle in role hierarchy was incorrectly detected!");
}
} }
// SEC-863 // SEC-863

View File

@ -31,7 +31,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.util.SimpleMethodInvocation; import org.springframework.security.util.SimpleMethodInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AfterInvocationProviderManager}. * Tests {@link AfterInvocationProviderManager}.
@ -72,13 +72,7 @@ public class AfterInvocationProviderManagerTests {
public void testRejectsEmptyProvidersList() { public void testRejectsEmptyProvidersList() {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
List list = new Vector(); List list = new Vector();
try { assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list));
manager.setProviders(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
} }
@Test @Test
@ -88,25 +82,13 @@ public class AfterInvocationProviderManagerTests {
list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1"))); list.add(new MockAfterInvocationProvider("swap1", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP1")));
list.add(45); list.add(45);
list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3"))); list.add(new MockAfterInvocationProvider("swap3", MethodInvocation.class, new SecurityConfig("GIVE_ME_SWAP3")));
try { assertThatIllegalArgumentException().isThrownBy(() -> manager.setProviders(list));
manager.setProviders(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
} }
@Test @Test
public void testRejectsNullProvidersList() throws Exception { public void testRejectsNullProvidersList() throws Exception {
AfterInvocationProviderManager manager = new AfterInvocationProviderManager(); AfterInvocationProviderManager manager = new AfterInvocationProviderManager();
try { assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet);
manager.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
} }
@Test @Test

View File

@ -26,6 +26,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
/** /**
@ -96,12 +97,7 @@ public class RunAsManagerImplTests {
@Test @Test
public void testStartupDetectsMissingKey() throws Exception { public void testStartupDetectsMissingKey() throws Exception {
RunAsManagerImpl runAs = new RunAsManagerImpl(); RunAsManagerImpl runAs = new RunAsManagerImpl();
try { assertThatIllegalArgumentException().isThrownBy(runAs::afterPropertiesSet);
runAs.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -22,7 +22,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests {@link RunAsUserToken}. * Tests {@link RunAsUserToken}.
@ -52,14 +52,8 @@ public class RunAsUserTokenTests {
@Test @Test
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
Class<RunAsUserToken> clazz = RunAsUserToken.class; assertThatExceptionOfType(NoSuchMethodException.class)
try { .isThrownBy(() -> RunAsUserToken.class.getDeclaredConstructor((Class[]) null));
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
assertThat(true).isTrue();
}
} }
@Test @Test

View File

@ -47,7 +47,7 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -251,12 +251,8 @@ public class MethodSecurityInterceptorTests {
given(this.authman.authenticate(this.token)).willReturn(this.token); given(this.authman.authenticate(this.token)).willReturn(this.token);
willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class), willThrow(new AccessDeniedException("rejected")).given(this.adm).decide(any(Authentication.class),
any(MethodInvocation.class), any(List.class)); any(MethodInvocation.class), any(List.class));
try { assertThatExceptionOfType(AccessDeniedException.class)
this.advisedTarget.makeUpperCase("HELLO"); .isThrownBy(() -> this.advisedTarget.makeUpperCase("HELLO"));
fail("Expected Exception");
}
catch (AccessDeniedException expected) {
}
verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class)); verify(this.eventPublisher).publishEvent(any(AuthorizationFailureEvent.class));
} }
@ -297,12 +293,7 @@ public class MethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs); this.interceptor.setRunAsManager(runAs);
mdsReturnsUserRole(); mdsReturnsUserRole();
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.advisedTarget.makeUpperCase("hello"));
this.advisedTarget.makeUpperCase("hello");
fail("Expected Exception");
}
catch (RuntimeException success) {
}
// Check we've changed back // Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@ -323,12 +314,7 @@ public class MethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class); AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
given(mi.proceed()).willThrow(new Throwable()); given(mi.proceed()).willThrow(new Throwable());
try { assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.interceptor.invoke(mi));
this.interceptor.invoke(mi);
fail("Expected exception");
}
catch (Throwable expected) {
}
verifyZeroInteractions(aim); verifyZeroInteractions(aim);
} }

View File

@ -45,7 +45,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -127,12 +127,8 @@ public class AspectJMethodSecurityInterceptorTests {
public void callbackIsNotInvokedWhenPermissionDenied() { public void callbackIsNotInvokedWhenPermissionDenied() {
willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any()); willThrow(new AccessDeniedException("denied")).given(this.adm).decide(any(), any(), any());
SecurityContextHolder.getContext().setAuthentication(this.token); SecurityContextHolder.getContext().setAuthentication(this.token);
try { assertThatExceptionOfType(AccessDeniedException.class)
this.interceptor.invoke(this.joinPoint, this.aspectJCallback); .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
fail("Expected AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
verify(this.aspectJCallback, never()).proceedWithObject(); verify(this.aspectJCallback, never()).proceedWithObject();
} }
@ -156,12 +152,8 @@ public class AspectJMethodSecurityInterceptorTests {
AfterInvocationManager aim = mock(AfterInvocationManager.class); AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException()); given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try { assertThatExceptionOfType(RuntimeException.class)
this.interceptor.invoke(this.joinPoint, this.aspectJCallback); .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
fail("Expected exception");
}
catch (RuntimeException expected) {
}
verifyZeroInteractions(aim); verifyZeroInteractions(aim);
} }
@ -178,12 +170,8 @@ public class AspectJMethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs); this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException()); given(this.aspectJCallback.proceedWithObject()).willThrow(new RuntimeException());
try { assertThatExceptionOfType(RuntimeException.class)
this.interceptor.invoke(this.joinPoint, this.aspectJCallback); .isThrownBy(() -> this.interceptor.invoke(this.joinPoint, this.aspectJCallback));
fail("Expected Exception");
}
catch (RuntimeException success) {
}
// Check we've changed back // Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);
@ -202,12 +190,7 @@ public class AspectJMethodSecurityInterceptorTests {
this.interceptor.setRunAsManager(runAs); this.interceptor.setRunAsManager(runAs);
given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken); given(runAs.buildRunAs(eq(this.token), any(MethodInvocation.class), any(List.class))).willReturn(runAsToken);
given(this.joinPoint.proceed()).willThrow(new RuntimeException()); given(this.joinPoint.proceed()).willThrow(new RuntimeException());
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(this.joinPoint));
this.interceptor.invoke(this.joinPoint);
fail("Expected Exception");
}
catch (RuntimeException success) {
}
// Check we've changed back // Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.token);

View File

@ -17,6 +17,7 @@
package org.springframework.security.access.vote; package org.springframework.security.access.vote;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Vector; import java.util.Vector;
@ -28,7 +29,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AbstractAccessDecisionManager}. * Tests {@link AbstractAccessDecisionManager}.
@ -86,23 +87,12 @@ public class AbstractAccessDecisionManagerTests {
@Test @Test
public void testRejectsEmptyList() { public void testRejectsEmptyList() {
List list = new Vector(); assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(Collections.emptyList()));
try {
new MockDecisionManagerImpl(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testRejectsNullVotersList() { public void testRejectsNullVotersList() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null));
new MockDecisionManagerImpl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -113,12 +103,7 @@ public class AbstractAccessDecisionManagerTests {
@Test @Test
public void testWillNotStartIfDecisionVotersNotSet() { public void testWillNotStartIfDecisionVotersNotSet() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null));
new MockDecisionManagerImpl(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
private class MockDecisionManagerImpl extends AbstractAccessDecisionManager { private class MockDecisionManagerImpl extends AbstractAccessDecisionManager {

View File

@ -30,7 +30,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AuthenticatedVoter}. * Tests {@link AuthenticatedVoter}.
@ -82,12 +82,7 @@ public class AuthenticatedVoterTests {
@Test @Test
public void testSetterRejectsNull() { public void testSetterRejectsNull() {
AuthenticatedVoter voter = new AuthenticatedVoter(); AuthenticatedVoter voter = new AuthenticatedVoter();
try { assertThatIllegalArgumentException().isThrownBy(() -> voter.setAuthenticationTrustResolver(null));
voter.setAuthenticationTrustResolver(null);
fail("Expected IAE");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests {@link UnanimousBased}. * Tests {@link UnanimousBased}.
@ -73,12 +73,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager(); UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" }); List<ConfigAttribute> config = SecurityConfig.createList(new String[] { "ROLE_1", "DENY_FOR_SURE" });
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
} }
@Test @Test
@ -94,12 +89,7 @@ public class UnanimousBasedTests {
TestingAuthenticationToken auth = makeTestToken(); TestingAuthenticationToken auth = makeTestToken();
UnanimousBased mgr = makeDecisionManager(); UnanimousBased mgr = makeDecisionManager();
List<ConfigAttribute> config = SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE"); List<ConfigAttribute> config = SecurityConfig.createList("ROLE_WE_DO_NOT_HAVE");
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
} }
@Test @Test
@ -116,12 +106,7 @@ public class UnanimousBasedTests {
UnanimousBased mgr = makeDecisionManager(); UnanimousBased mgr = makeDecisionManager();
assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default assertThat(!mgr.isAllowIfAllAbstainDecisions()).isTrue(); // check default
List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL"); List<ConfigAttribute> config = SecurityConfig.createList("IGNORED_BY_ALL");
try { assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> mgr.decide(auth, new Object(), config));
mgr.decide(auth, new Object(), config);
fail("Should have thrown AccessDeniedException");
}
catch (AccessDeniedException expected) {
}
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -171,12 +171,8 @@ public class ProviderManagerTests {
public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() { public void authenticationExceptionIsRethrownIfNoLaterProviderAuthenticates() {
ProviderManager mgr = new ProviderManager(Arrays ProviderManager mgr = new ProviderManager(Arrays
.asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null))); .asList(createProviderWhichThrows(new BadCredentialsException("")), createProviderWhichReturns(null)));
try { assertThatExceptionOfType(BadCredentialsException.class)
mgr.authenticate(mock(Authentication.class)); .isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
// SEC-546 // SEC-546
@ -186,12 +182,8 @@ public class ProviderManagerTests {
}); });
AuthenticationProvider otherProvider = mock(AuthenticationProvider.class); AuthenticationProvider otherProvider = mock(AuthenticationProvider.class);
ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider)); ProviderManager authMgr = new ProviderManager(Arrays.asList(iThrowAccountStatusException, otherProvider));
try { assertThatExceptionOfType(AccountStatusException.class)
authMgr.authenticate(mock(Authentication.class)); .isThrownBy(() -> authMgr.authenticate(mock(Authentication.class)));
fail("Expected AccountStatusException");
}
catch (AccountStatusException expected) {
}
verifyNoInteractions(otherProvider); verifyNoInteractions(otherProvider);
} }
@ -212,12 +204,8 @@ public class ProviderManagerTests {
}); });
AuthenticationManager parent = mock(AuthenticationManager.class); AuthenticationManager parent = mock(AuthenticationManager.class);
ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent); ProviderManager mgr = new ProviderManager(Collections.singletonList(iThrowAccountStatusException), parent);
try { assertThatExceptionOfType(AccountStatusException.class)
mgr.authenticate(mock(Authentication.class)); .isThrownBy(() -> mgr.authenticate(mock(Authentication.class)));
fail("Expected exception");
}
catch (AccountStatusException expected) {
}
verifyNoInteractions(parent); verifyNoInteractions(parent);
} }
@ -232,13 +220,8 @@ public class ProviderManagerTests {
ProviderManager mgr = new ProviderManager( ProviderManager mgr = new ProviderManager(
Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent); Collections.singletonList(createProviderWhichThrows(new BadCredentialsException(""))), parent);
mgr.setAuthenticationEventPublisher(publisher); mgr.setAuthenticationEventPublisher(publisher);
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
mgr.authenticate(authReq); .satisfies((ex) -> verify(publisher).publishAuthenticationFailure(ex, authReq));
fail("Expected exception");
}
catch (BadCredentialsException expected) {
verify(publisher).publishAuthenticationFailure(expected, authReq);
}
} }
@Test @Test
@ -251,15 +234,10 @@ public class ProviderManagerTests {
mgr.setAuthenticationEventPublisher(publisher); mgr.setAuthenticationEventPublisher(publisher);
// Set a provider that throws an exception - this is the exception we expect to be // Set a provider that throws an exception - this is the exception we expect to be
// propagated // propagated
final BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent"); BadCredentialsException expected = new BadCredentialsException("I'm the one from the parent");
given(parent.authenticate(authReq)).willThrow(expected); given(parent.authenticate(authReq)).willThrow(expected);
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(authReq))
mgr.authenticate(authReq); .isSameAs(expected);
fail("Expected exception");
}
catch (BadCredentialsException ex) {
assertThat(ex).isSameAs(expected);
}
} }
@Test @Test
@ -271,13 +249,7 @@ public class ProviderManagerTests {
final Authentication authReq = mock(Authentication.class); final Authentication authReq = mock(Authentication.class);
AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class); AuthenticationEventPublisher publisher = mock(AuthenticationEventPublisher.class);
mgr.setAuthenticationEventPublisher(publisher); mgr.setAuthenticationEventPublisher(publisher);
try { assertThatExceptionOfType(LockedException.class).isThrownBy(() -> mgr.authenticate(authReq));
mgr.authenticate(authReq);
fail("Expected exception");
}
catch (LockedException ex) {
assertThat(ex).isSameAs(expected);
}
verify(publisher).publishAuthenticationFailure(expected, authReq); verify(publisher).publishAuthenticationFailure(expected, authReq);
} }
@ -287,13 +259,9 @@ public class ProviderManagerTests {
InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected"); InternalAuthenticationServiceException expected = new InternalAuthenticationServiceException("Expected");
ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected), ProviderManager mgr = new ProviderManager(Arrays.asList(createProviderWhichThrows(expected),
createProviderWhichThrows(new BadCredentialsException("Oops"))), null); createProviderWhichThrows(new BadCredentialsException("Oops"))), null);
final Authentication authReq = mock(Authentication.class); Authentication authReq = mock(Authentication.class);
try { assertThatExceptionOfType(InternalAuthenticationServiceException.class)
mgr.authenticate(authReq); .isThrownBy(() -> mgr.authenticate(authReq));
fail("Expected Exception");
}
catch (InternalAuthenticationServiceException success) {
}
} }
// gh-6281 // gh-6281
@ -307,13 +275,8 @@ public class ProviderManagerTests {
parentMgr.setAuthenticationEventPublisher(publisher); parentMgr.setAuthenticationEventPublisher(publisher);
childMgr.setAuthenticationEventPublisher(publisher); childMgr.setAuthenticationEventPublisher(publisher);
final Authentication authReq = mock(Authentication.class); final Authentication authReq = mock(Authentication.class);
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> childMgr.authenticate(authReq))
childMgr.authenticate(authReq); .isSameAs(badCredentialsExParent);
fail("Expected exception");
}
catch (BadCredentialsException ex) {
assertThat(ex).isSameAs(badCredentialsExParent);
}
verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent verify(publisher).publishAuthenticationFailure(badCredentialsExParent, authReq); // Parent
// publishes // publishes
verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event) verifyNoMoreInteractions(publisher); // Child should not publish (duplicate event)

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link UsernamePasswordAuthenticationToken}. * Tests {@link UsernamePasswordAuthenticationToken}.
@ -32,29 +32,25 @@ public class UsernamePasswordAuthenticationTokenTests {
@Test @Test
public void authenticatedPropertyContractIsSatisfied() { public void authenticatedPropertyContractIsSatisfied() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", UsernamePasswordAuthenticationToken grantedToken = new UsernamePasswordAuthenticationToken("Test", "Password",
AuthorityUtils.NO_AUTHORITIES); AuthorityUtils.NO_AUTHORITIES);
// check default given we passed some GrantedAuthorty[]s (well, we passed empty // check default given we passed some GrantedAuthorty[]s (well, we passed empty
// list) // list)
assertThat(token.isAuthenticated()).isTrue(); assertThat(grantedToken.isAuthenticated()).isTrue();
// check explicit set to untrusted (we can safely go from trusted to untrusted, // check explicit set to untrusted (we can safely go from trusted to untrusted,
// but not the reverse) // but not the reverse)
token.setAuthenticated(false); grantedToken.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue(); assertThat(!grantedToken.isAuthenticated()).isTrue();
// Now let's create a UsernamePasswordAuthenticationToken without any // Now let's create a UsernamePasswordAuthenticationToken without any
// GrantedAuthorty[]s (different constructor) // GrantedAuthorty[]s (different constructor)
token = new UsernamePasswordAuthenticationToken("Test", "Password"); UsernamePasswordAuthenticationToken noneGrantedToken = new UsernamePasswordAuthenticationToken("Test",
assertThat(!token.isAuthenticated()).isTrue(); "Password");
assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
// check we're allowed to still set it to untrusted // check we're allowed to still set it to untrusted
token.setAuthenticated(false); noneGrantedToken.setAuthenticated(false);
assertThat(!token.isAuthenticated()).isTrue(); assertThat(!noneGrantedToken.isAuthenticated()).isTrue();
// check denied changing it to trusted // check denied changing it to trusted
try { assertThatIllegalArgumentException().isThrownBy(() -> noneGrantedToken.setAuthenticated(true));
token.setAuthenticated(true);
fail("Should have prohibited setAuthenticated(true)");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AnonymousAuthenticationProvider}. * Tests {@link AnonymousAuthenticationProvider}.
@ -40,22 +41,12 @@ public class AnonymousAuthenticationProviderTests {
AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty"); AnonymousAuthenticationProvider aap = new AnonymousAuthenticationProvider("qwerty");
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test", AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token));
aap.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
public void testDetectsMissingKey() { public void testDetectsMissingKey() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationProvider(null));
new AnonymousAuthenticationProvider(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -27,7 +27,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AnonymousAuthenticationToken}. * Tests {@link AnonymousAuthenticationToken}.
@ -40,30 +41,11 @@ public class AnonymousAuthenticationTokenTests {
@Test @Test
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken(null, "Test", ROLES_12));
new AnonymousAuthenticationToken(null, "Test", ROLES_12); assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", null, ROLES_12));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", null));
} assertThatIllegalArgumentException()
catch (IllegalArgumentException expected) { .isThrownBy(() -> new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES));
}
try {
new AnonymousAuthenticationToken("key", null, ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test", null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new AnonymousAuthenticationToken("key", "Test", AuthorityUtils.NO_AUTHORITIES);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -85,13 +67,8 @@ public class AnonymousAuthenticationTokenTests {
@Test @Test
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
Class<?> clazz = AnonymousAuthenticationToken.class; assertThatExceptionOfType(NoSuchMethodException.class)
try { .isThrownBy(() -> AnonymousAuthenticationToken.class.getDeclaredConstructor((Class[]) null));
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
} }
@Test @Test

View File

@ -50,6 +50,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -77,12 +78,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -92,12 +88,8 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("rod", null);
try { assertThatExceptionOfType(BadCredentialsException.class)
provider.authenticate(authenticationToken); .isThrownBy(() -> provider.authenticate(authenticationToken));
fail("Expected BadCredenialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -106,12 +98,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountExpired());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown AccountExpiredException");
}
catch (AccountExpiredException expected) {
}
} }
@Test @Test
@ -120,35 +107,20 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterAccountLocked());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(LockedException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown LockedException");
}
catch (LockedException expected) {
}
} }
@Test @Test
public void testAuthenticateFailsIfCredentialsExpired() { public void testAuthenticateFailsIfCredentialsExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter", "opal");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(CredentialsExpiredException.class)
provider.authenticate(token); .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "opal")));
fail("Should have thrown CredentialsExpiredException");
}
catch (CredentialsExpiredException expected) {
}
// Check that wrong password causes BadCredentialsException, rather than // Check that wrong password causes BadCredentialsException, rather than
// CredentialsExpiredException // CredentialsExpiredException
token = new UsernamePasswordAuthenticationToken("peter", "wrong_password"); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
try { () -> provider.authenticate(new UsernamePasswordAuthenticationToken("peter", "wrong_password")));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -157,12 +129,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserPeter()); provider.setUserDetailsService(new MockUserDetailsServiceUserPeter());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown DisabledException");
}
catch (DisabledException expected) {
}
} }
@Test @Test
@ -171,12 +138,8 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError()); provider.setUserDetailsService(new MockUserDetailsServiceSimulateBackendError());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(InternalAuthenticationServiceException.class)
provider.authenticate(token); .isThrownBy(() -> provider.authenticate(token));
fail("Should have thrown InternalAuthenticationServiceException");
}
catch (InternalAuthenticationServiceException expected) {
}
} }
@Test @Test
@ -185,12 +148,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -199,12 +157,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -215,12 +168,7 @@ public class DaoAuthenticationProviderTests {
// UsernameNotFoundExceptions // UsernameNotFoundExceptions
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
} }
@Test @Test
@ -230,12 +178,7 @@ public class DaoAuthenticationProviderTests {
assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -245,19 +188,9 @@ public class DaoAuthenticationProviderTests {
assertThat(provider.isHideUserNotFoundExceptions()).isTrue(); assertThat(provider.isHideUserNotFoundExceptions()).isTrue();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()); provider.setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -266,12 +199,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.setUserCache(new MockUserCache()); provider.setUserCache(new MockUserCache());
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -389,14 +317,8 @@ public class DaoAuthenticationProviderTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala"); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("rod", "koala");
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull()); provider.setUserDetailsService(new MockUserDetailsServiceReturnsNull());
try { assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(token))
provider.authenticate(token); .withMessage("UserDetailsService returned null, which is an interface contract violation");
fail("Should have thrown AuthenticationServiceException");
}
catch (AuthenticationServiceException expected) {
assertThat("UserDetailsService returned null, which is an interface contract violation")
.isEqualTo(expected.getMessage());
}
} }
@Test @Test
@ -436,12 +358,7 @@ public class DaoAuthenticationProviderTests {
@Test @Test
public void testStartupFailsIfNoAuthenticationDao() throws Exception { public void testStartupFailsIfNoAuthenticationDao() throws Exception {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
try { assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -450,12 +367,7 @@ public class DaoAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class); assertThat(provider.getUserCache().getClass()).isEqualTo(NullUserCache.class);
provider.setUserCache(null); provider.setUserCache(null);
try { assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -486,12 +398,7 @@ public class DaoAuthenticationProviderTests {
provider.setPasswordEncoder(encoder); provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
provider.afterPropertiesSet(); provider.afterPropertiesSet();
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
// ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail // ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail
// if encoded password is null // if encoded password is null
verify(encoder).matches(isA(String.class), isA(String.class)); verify(encoder).matches(isA(String.class), isA(String.class));
@ -507,12 +414,7 @@ public class DaoAuthenticationProviderTests {
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod(); MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
userDetailsService.password = encoder.encode((CharSequence) token.getCredentials()); userDetailsService.password = encoder.encode((CharSequence) token.getCredentials());
provider.setUserDetailsService(userDetailsService); provider.setUserDetailsService(userDetailsService);
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
} }
@Test @Test
@ -521,12 +423,7 @@ public class DaoAuthenticationProviderTests {
DaoAuthenticationProvider provider = createProvider(); DaoAuthenticationProvider provider = createProvider();
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
} }
/** /**
@ -554,12 +451,8 @@ public class DaoAuthenticationProviderTests {
List<Long> userNotFoundTimes = new ArrayList<>(sampleSize); List<Long> userNotFoundTimes = new ArrayList<>(sampleSize);
for (int i = 0; i < sampleSize; i++) { for (int i = 0; i < sampleSize; i++) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { assertThatExceptionOfType(UsernameNotFoundException.class)
provider.authenticate(notFoundUser); .isThrownBy(() -> provider.authenticate(notFoundUser));
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
userNotFoundTimes.add(System.currentTimeMillis() - start); userNotFoundTimes.add(System.currentTimeMillis() - start);
} }
double userFoundAvg = avg(userFoundTimes); double userFoundAvg = avg(userFoundTimes);
@ -584,12 +477,7 @@ public class DaoAuthenticationProviderTests {
provider.setHideUserNotFoundExceptions(false); provider.setHideUserNotFoundExceptions(false);
provider.setPasswordEncoder(encoder); provider.setPasswordEncoder(encoder);
provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
provider.authenticate(token);
fail("Expected Exception");
}
catch (UsernameNotFoundException success) {
}
verify(encoder, times(0)).matches(anyString(), anyString()); verify(encoder, times(0)).matches(anyString(), anyString());
} }

View File

@ -24,7 +24,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link AbstractAuthenticationEvent} and its subclasses. * Tests {@link AbstractAuthenticationEvent} and its subclasses.
@ -59,22 +59,13 @@ public class AuthenticationEventTests {
@Test @Test
public void testRejectsNullAuthentication() { public void testRejectsNullAuthentication() {
AuthenticationException exception = new DisabledException("TEST"); AuthenticationException exception = new DisabledException("TEST");
try { assertThatIllegalArgumentException().isThrownBy(() -> new AuthenticationFailureDisabledEvent(null, exception));
new AuthenticationFailureDisabledEvent(null, exception);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testRejectsNullAuthenticationException() { public void testRejectsNullAuthenticationException() {
try { assertThatIllegalArgumentException()
new AuthenticationFailureDisabledEvent(getAuthentication(), null); .isThrownBy(() -> new AuthenticationFailureDisabledEvent(getAuthentication(), null));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
} }

View File

@ -44,7 +44,7 @@ import org.springframework.security.core.session.SessionDestroyedEvent;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isA;
@ -112,23 +112,15 @@ public class DefaultJaasAuthenticationProviderTests {
@Test @Test
public void authenticateBadPassword() { public void authenticateBadPassword() {
try { assertThatExceptionOfType(AuthenticationException.class)
this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")); .isThrownBy(() -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException success) {
}
verifyFailedLogin(); verifyFailedLogin();
} }
@Test @Test
public void authenticateBadUser() { public void authenticateBadUser() {
try { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")); () -> this.provider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException success) {
}
verifyFailedLogin(); verifyFailedLogin();
} }

View File

@ -46,6 +46,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionDestroyedEvent; import org.springframework.security.core.session.SessionDestroyedEvent;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -73,12 +75,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testBadPassword() { public void testBadPassword() {
try { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")); () -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf")));
fail("LoginException should have been thrown for the bad password");
}
catch (AuthenticationException ex) {
}
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull(); .isNotNull();
@ -87,12 +85,8 @@ public class JaasAuthenticationProviderTests {
@Test @Test
public void testBadUser() { public void testBadUser() {
try { assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")); () -> this.jaasProvider.authenticate(new UsernamePasswordAuthenticationToken("asdf", "password")));
fail("LoginException should have been thrown for the bad user");
}
catch (AuthenticationException ex) {
}
assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull(); assertThat(this.eventCheck.failedEvent).as("Failure event not fired").isNotNull();
assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null") assertThat(this.eventCheck.failedEvent.getException()).withFailMessage("Failure event exception was null")
.isNotNull(); .isNotNull();
@ -115,13 +109,8 @@ public class JaasAuthenticationProviderTests {
myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters()); myJaasProvider.setAuthorityGranters(this.jaasProvider.getAuthorityGranters());
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName()); myJaasProvider.setLoginContextName(this.jaasProvider.getLoginContextName());
try { assertThatIllegalArgumentException().isThrownBy(() -> myJaasProvider.afterPropertiesSet())
myJaasProvider.afterPropertiesSet(); .withMessageStartingWith("loginConfig must be set on");
fail("Should have thrown ApplicationContextException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().startsWith("loginConfig must be set on")).isTrue();
}
} }
// SEC-1239 // SEC-1239
@ -160,21 +149,11 @@ public class JaasAuthenticationProviderTests {
myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers()); myJaasProvider.setCallbackHandlers(this.jaasProvider.getCallbackHandlers());
myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig()); myJaasProvider.setLoginConfig(this.jaasProvider.getLoginConfig());
myJaasProvider.setLoginContextName(null); myJaasProvider.setLoginContextName(null);
try { assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
myJaasProvider.afterPropertiesSet(); .withMessageStartingWith("loginContextName must be set on");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).startsWith("loginContextName must be set on");
}
myJaasProvider.setLoginContextName(""); myJaasProvider.setLoginContextName("");
try { assertThatIllegalArgumentException().isThrownBy(myJaasProvider::afterPropertiesSet)
myJaasProvider.afterPropertiesSet(); .withMessageStartingWith("loginContextName must be set on");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage().startsWith("loginContextName must be set on"));
}
} }
@Test @Test

View File

@ -31,7 +31,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests SecurityContextLoginModule * Tests SecurityContextLoginModule
@ -71,12 +71,7 @@ public class SecurityContextLoginModuleTests {
@Test @Test
public void testLoginException() { public void testLoginException() {
try { assertThatExceptionOfType(LoginException.class).isThrownBy(this.module::login);
this.module.login();
fail("LoginException expected, there is no Authentication in the SecurityContext");
}
catch (LoginException ex) {
}
} }
@Test @Test
@ -101,13 +96,8 @@ public class SecurityContextLoginModuleTests {
@Test @Test
public void testNullAuthenticationInSecurityContext() { public void testNullAuthenticationInSecurityContext() {
try {
SecurityContextHolder.getContext().setAuthentication(null); SecurityContextHolder.getContext().setAuthentication(null);
this.module.login(); assertThatExceptionOfType(Exception.class).isThrownBy(this.module::login);
fail("LoginException expected, the authentication is null in the SecurityContext");
}
catch (Exception ex) {
}
} }
@Test @Test

View File

@ -23,7 +23,7 @@ import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -47,12 +47,7 @@ public class RemoteAuthenticationManagerImplTests {
@Test @Test
public void testStartupChecksAuthenticationManagerSet() throws Exception { public void testStartupChecksAuthenticationManagerSet() throws Exception {
RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl(); RemoteAuthenticationManagerImpl manager = new RemoteAuthenticationManagerImpl();
try { assertThatIllegalArgumentException().isThrownBy(manager::afterPropertiesSet);
manager.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
manager.setAuthenticationManager(mock(AuthenticationManager.class)); manager.setAuthenticationManager(mock(AuthenticationManager.class));
manager.afterPropertiesSet(); manager.afterPropertiesSet();
} }

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link RemoteAuthenticationProvider}. * Tests {@link RemoteAuthenticationProvider}.
@ -39,12 +40,8 @@ public class RemoteAuthenticationProviderTests {
public void testExceptionsGetPassedBackToCaller() { public void testExceptionsGetPassedBackToCaller() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try { assertThatExceptionOfType(RemoteAuthenticationException.class)
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "password")));
fail("Should have thrown RemoteAuthenticationException");
}
catch (RemoteAuthenticationException expected) {
}
} }
@Test @Test
@ -57,12 +54,7 @@ public class RemoteAuthenticationProviderTests {
@Test @Test
public void testStartupChecksAuthenticationManagerSet() throws Exception { public void testStartupChecksAuthenticationManagerSet() throws Exception {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
try { assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true)); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(true));
provider.afterPropertiesSet(); provider.afterPropertiesSet();
} }
@ -81,12 +73,8 @@ public class RemoteAuthenticationProviderTests {
public void testNullCredentialsDoesNotCauseNullPointerException() { public void testNullCredentialsDoesNotCauseNullPointerException() {
RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false)); provider.setRemoteAuthenticationManager(new MockRemoteAuthenticationManager(false));
try { assertThatExceptionOfType(RemoteAuthenticationException.class)
provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null)); .isThrownBy(() -> provider.authenticate(new UsernamePasswordAuthenticationToken("rod", null)));
fail("Expected Exception");
}
catch (RemoteAuthenticationException success) {
}
} }
@Test @Test

View File

@ -26,7 +26,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link RememberMeAuthenticationProvider}. * Tests {@link RememberMeAuthenticationProvider}.
@ -40,22 +41,12 @@ public class RememberMeAuthenticationProviderTests {
RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty"); RememberMeAuthenticationProvider aap = new RememberMeAuthenticationProvider("qwerty");
RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test", RememberMeAuthenticationToken token = new RememberMeAuthenticationToken("WRONG_KEY", "Test",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> aap.authenticate(token));
aap.authenticate(token);
fail("Should have thrown BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
public void testDetectsMissingKey() { public void testDetectsMissingKey() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationProvider(null));
new RememberMeAuthenticationProvider(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -16,7 +16,7 @@
package org.springframework.security.authentication.rememberme; package org.springframework.security.authentication.rememberme;
import java.util.ArrayList; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Test; import org.junit.Test;
@ -27,7 +27,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link RememberMeAuthenticationToken}. * Tests {@link RememberMeAuthenticationToken}.
@ -40,26 +40,11 @@ public class RememberMeAuthenticationTokenTests {
@Test @Test
public void testConstructorRejectsNulls() { public void testConstructorRejectsNulls() {
try { assertThatIllegalArgumentException()
new RememberMeAuthenticationToken(null, "Test", ROLES_12); .isThrownBy(() -> new RememberMeAuthenticationToken(null, "Test", ROLES_12));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> new RememberMeAuthenticationToken("key", null, ROLES_12));
} assertThatIllegalArgumentException().isThrownBy(
catch (IllegalArgumentException expected) { () -> new RememberMeAuthenticationToken("key", "Test", Arrays.asList((GrantedAuthority) null)));
}
try {
new RememberMeAuthenticationToken("key", null, ROLES_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
List<GrantedAuthority> authsContainingNull = new ArrayList<>();
authsContainingNull.add(null);
new RememberMeAuthenticationToken("key", "Test", authsContainingNull);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -26,7 +26,8 @@ import org.junit.Test;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException;
/** /**
* @author TSARDD * @author TSARDD
@ -39,26 +40,13 @@ public class SimpleRoles2GrantedAuthoritiesMapperTests {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
mapper.setConvertAttributeToLowerCase(true); mapper.setConvertAttributeToLowerCase(true);
mapper.setConvertAttributeToUpperCase(true); mapper.setConvertAttributeToUpperCase(true);
try { assertThatIllegalArgumentException().isThrownBy(mapper::afterPropertiesSet);
mapper.afterPropertiesSet();
fail("Expected exception not thrown");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
} }
@Test @Test
public final void testAfterPropertiesSet() { public final void testAfterPropertiesSet() {
SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper(); SimpleAttributes2GrantedAuthoritiesMapper mapper = new SimpleAttributes2GrantedAuthoritiesMapper();
try { assertThatNoException().isThrownBy(mapper::afterPropertiesSet);
mapper.afterPropertiesSet();
}
catch (Exception unexpected) {
fail("Unexpected exception: " + unexpected);
}
} }
@Test @Test

View File

@ -22,7 +22,7 @@ import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link SecurityContextHolder}. * Tests {@link SecurityContextHolder}.
@ -55,12 +55,7 @@ public class SecurityContextHolderTests {
@Test @Test
public void testRejectsNulls() { public void testRejectsNulls() {
try { assertThatIllegalArgumentException().isThrownBy(() -> SecurityContextHolder.setContext(null));
SecurityContextHolder.setContext(null);
fail("Should have rejected null");
}
catch (IllegalArgumentException expected) {
}
} }
} }

View File

@ -22,7 +22,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.AuthorityUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author TSARDD * @author TSARDD
@ -34,15 +34,7 @@ public class UserDetailsByNameServiceWrapperTests {
@Test @Test
public final void testAfterPropertiesSet() { public final void testAfterPropertiesSet() {
UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper(); UserDetailsByNameServiceWrapper svc = new UserDetailsByNameServiceWrapper();
try { assertThatIllegalArgumentException().isThrownBy(svc::afterPropertiesSet);
svc.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
} }
@Test @Test

View File

@ -30,7 +30,8 @@ import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link User}. * Tests {@link User}.
@ -63,50 +64,25 @@ public class UserTests {
@Test @Test
public void testNoArgConstructorDoesntExist() { public void testNoArgConstructorDoesntExist() {
Class<User> clazz = User.class; assertThatExceptionOfType(NoSuchMethodException.class)
try { .isThrownBy(() -> User.class.getDeclaredConstructor((Class[]) null));
clazz.getDeclaredConstructor((Class[]) null);
fail("Should have thrown NoSuchMethodException");
}
catch (NoSuchMethodException expected) {
}
} }
@Test @Test
public void testNullValuesRejected() { public void testNullValuesRejected() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, ROLE_12));
new User(null, "koala", true, true, true, true, ROLE_12); assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", null, true, true, true, true, ROLE_12));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
new User("rod", null, true, true, true, true, ROLE_12);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null); auths.add(null);
new User("rod", "koala", true, true, true, true, auths); assertThatIllegalArgumentException().isThrownBy(() -> new User("rod", "koala", true, true, true, true, auths));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testNullWithinGrantedAuthorityElementIsRejected() { public void testNullWithinGrantedAuthorityElementIsRejected() {
try {
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE"); List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("ROLE_ONE");
auths.add(null); auths.add(null);
auths.add(new SimpleGrantedAuthority("ROLE_THREE")); auths.add(new SimpleGrantedAuthority("ROLE_THREE"));
new User(null, "koala", true, true, true, true, auths); assertThatIllegalArgumentException().isThrownBy(() -> new User(null, "koala", true, true, true, true, auths));
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -25,7 +25,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -92,23 +93,14 @@ public class JdbcDaoImplTests {
@Test @Test
public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception { public void testLookupFailsIfUserHasNoGrantedAuthorities() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao(); JdbcDaoImpl dao = makePopulatedJdbcDao();
try { assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> dao.loadUserByUsername("cooper"));
dao.loadUserByUsername("cooper");
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
} }
@Test @Test
public void testLookupFailsWithWrongUsername() throws Exception { public void testLookupFailsWithWrongUsername() throws Exception {
JdbcDaoImpl dao = makePopulatedJdbcDao(); JdbcDaoImpl dao = makePopulatedJdbcDao();
try { assertThatExceptionOfType(UsernameNotFoundException.class)
dao.loadUserByUsername("UNKNOWN_USER"); .isThrownBy(() -> dao.loadUserByUsername("UNKNOWN_USER"));
fail("Should have thrown UsernameNotFoundException");
}
catch (UsernameNotFoundException expected) {
}
} }
@Test @Test
@ -152,24 +144,16 @@ public class JdbcDaoImplTests {
@Test @Test
public void testStartupFailsIfDataSourceNotSet() { public void testStartupFailsIfDataSourceNotSet() {
JdbcDaoImpl dao = new JdbcDaoImpl(); JdbcDaoImpl dao = new JdbcDaoImpl();
try { assertThatIllegalArgumentException().isThrownBy(dao::afterPropertiesSet);
dao.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testStartupFailsIfUserMapSetToNull() { public void testStartupFailsIfUserMapSetToNull() {
JdbcDaoImpl dao = new JdbcDaoImpl(); JdbcDaoImpl dao = new JdbcDaoImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> {
dao.setDataSource(null); dao.setDataSource(null);
dao.afterPropertiesSet(); dao.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException"); });
}
catch (IllegalArgumentException expected) {
}
} }
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)

View File

@ -44,7 +44,7 @@ import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -229,12 +229,8 @@ public class JdbcUserDetailsManagerTests {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
this.manager.setAuthenticationManager(am); this.manager.setAuthenticationManager(am);
try { assertThatExceptionOfType(BadCredentialsException.class)
this.manager.changePassword("password", "newPassword"); .isThrownBy(() -> this.manager.changePassword("password", "newPassword"));
fail("Expected BadCredentialsException");
}
catch (BadCredentialsException expected) {
}
// Check password hasn't changed. // Check password hasn't changed.
UserDetails newJoe = this.manager.loadUserByUsername("joe"); UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password"); assertThat(newJoe.getPassword()).isEqualTo("password");

View File

@ -19,6 +19,7 @@ package org.springframework.security.util;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -32,11 +33,7 @@ public class FieldUtilsTests {
assertThat(FieldUtils.getFieldValue(tc, "nested.protectedField")).isEqualTo("z"); assertThat(FieldUtils.getFieldValue(tc, "nested.protectedField")).isEqualTo("z");
FieldUtils.setProtectedFieldValue("protectedField", tc, "y"); FieldUtils.setProtectedFieldValue("protectedField", tc, "y");
assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("y"); assertThat(FieldUtils.getProtectedFieldValue("protectedField", tc)).isEqualTo("y");
try { assertThatIllegalStateException().isThrownBy(() -> FieldUtils.getProtectedFieldValue("nonExistentField", tc));
FieldUtils.getProtectedFieldValue("nonExistentField", tc);
}
catch (IllegalStateException expected) {
}
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")

View File

@ -38,7 +38,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -90,14 +90,10 @@ public class SpringSecurityLdapTemplateITests {
@Test @Test
public void namingExceptionIsTranslatedCorrectly() { public void namingExceptionIsTranslatedCorrectly() {
try { assertThatExceptionOfType(UncategorizedLdapException.class)
this.template.executeReadOnly((ContextExecutor) (dirContext) -> { .isThrownBy(() -> this.template.executeReadOnly((ContextExecutor) (dirContext) -> {
throw new NamingException(); throw new NamingException();
}); }));
fail("Expected UncategorizedLdapException on NamingException");
}
catch (UncategorizedLdapException expected) {
}
} }
@Test @Test

View File

@ -33,7 +33,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link BindAuthenticator}. * Tests for {@link BindAuthenticator}.
@ -77,13 +77,8 @@ public class BindAuthenticatorTests {
@Test @Test
public void testAuthenticationWithInvalidUserNameFails() { public void testAuthenticationWithInvalidUserNameFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator
try { .authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password")));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"));
fail("Shouldn't be able to bind with invalid username");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test
@ -131,13 +126,8 @@ public class BindAuthenticatorTests {
@Test @Test
public void testAuthenticationWithWrongPasswordFails() { public void testAuthenticationWithWrongPasswordFails() {
this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
try { () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword")));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"));
fail("Shouldn't be able to bind with wrong password");
}
catch (BadCredentialsException expected) {
}
} }
@Test @Test

View File

@ -36,7 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link PasswordComparisonAuthenticator}. * Tests for {@link PasswordComparisonAuthenticator}.
@ -80,13 +80,8 @@ public class PasswordComparisonAuthenticatorTests {
.isEmpty(); .isEmpty();
this.authenticator.setUserSearch(new MockUserSearch(null)); this.authenticator.setUserSearch(new MockUserSearch(null));
this.authenticator.afterPropertiesSet(); this.authenticator.afterPropertiesSet();
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(
try { () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass")));
this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
fail("Expected exception on failed user search");
}
catch (UsernameNotFoundException expected) {
}
} }
@Test(expected = BadCredentialsException.class) @Test(expected = BadCredentialsException.class)

View File

@ -33,6 +33,7 @@ import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
/** /**
@ -112,14 +113,8 @@ public class ApacheDSContainerTests {
List<Integer> ports = getDefaultPorts(1); List<Integer> ports = getDefaultPorts(1);
server.setPort(ports.get(0)); server.setPort(ports.get(0));
server.setLdapOverSslEnabled(true); server.setLdapOverSslEnabled(true);
assertThatIllegalArgumentException().isThrownBy(server::afterPropertiesSet)
try { .withMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
server.afterPropertiesSet();
fail("Expected an IllegalArgumentException to be thrown.");
}
catch (IllegalArgumentException ex) {
assertThat(ex).hasMessage("When LdapOverSsl is enabled, the keyStoreFile property must be set.");
}
} }
@Test @Test

View File

@ -29,7 +29,7 @@ import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.SpringSecurityLdapTemplate; import org.springframework.security.ldap.SpringSecurityLdapTemplate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests for {@link UnboundIdContainer}, specifically relating to LDIF file detection. * Tests for {@link UnboundIdContainer}, specifically relating to LDIF file detection.
@ -72,26 +72,18 @@ public class UnboundIdContainerLdifTests {
@Test @Test
public void unboundIdContainerWhenMalformedLdifThenException() { public void unboundIdContainerWhenMalformedLdifThenException() {
try { assertThatExceptionOfType(Exception.class)
this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class); .isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MalformedLdifConfig.class))
failBecauseExceptionWasNotThrown(IllegalStateException.class); .withCauseInstanceOf(IllegalStateException.class)
} .withMessageContaining("Unable to load LDIF classpath:test-server-malformed.txt");
catch (Exception ex) {
assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:test-server-malformed.txt");
}
} }
@Test @Test
public void unboundIdContainerWhenMissingLdifThenException() { public void unboundIdContainerWhenMissingLdifThenException() {
try { assertThatExceptionOfType(Exception.class)
this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class); .isThrownBy(() -> this.appCtx = new AnnotationConfigApplicationContext(MissingLdifConfig.class))
failBecauseExceptionWasNotThrown(IllegalStateException.class); .withCauseInstanceOf(IllegalStateException.class)
} .withMessageContaining("Unable to load LDIF classpath:does-not-exist.ldif");
catch (Exception ex) {
assertThat(ex.getCause()).isInstanceOf(IllegalStateException.class);
assertThat(ex.getMessage()).contains("Unable to load LDIF classpath:does-not-exist.ldif");
}
} }
@Test @Test

View File

@ -39,7 +39,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -174,14 +174,7 @@ public class LdapUserDetailsManagerTests {
assertThat(don.getAuthorities()).hasSize(2); assertThat(don.getAuthorities()).hasSize(2);
this.mgr.deleteUser("don"); this.mgr.deleteUser("don");
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.mgr.loadUserByUsername("don"));
try {
this.mgr.loadUserByUsername("don");
fail("Expected UsernameNotFoundException after deleting user");
}
catch (UsernameNotFoundException expected) {
// expected
}
// Check that no authorities are left // Check that no authorities are left
assertThat(this.mgr.getUserAuthorities(this.mgr.usernameMapper.buildDn("don"), "don")).hasSize(0); assertThat(this.mgr.getUserAuthorities(this.mgr.usernameMapper.buildDn("don"), "don")).hasSize(0);

View File

@ -36,7 +36,7 @@ import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper; import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -67,18 +67,10 @@ public class LdapAuthenticationProviderTests {
public void testEmptyOrNullUserNameThrowsException() { public void testEmptyOrNullUserNameThrowsException() {
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(), LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(),
new MockAuthoritiesPopulator()); new MockAuthoritiesPopulator());
try { assertThatExceptionOfType(BadCredentialsException.class)
ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password")); .isThrownBy(() -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password")));
fail("Expected BadCredentialsException for empty username"); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(
} () -> ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword")));
catch (BadCredentialsException expected) {
}
try {
ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword"));
fail("Expected BadCredentialsException for null username");
}
catch (BadCredentialsException expected) {
}
} }
@Test(expected = BadCredentialsException.class) @Test(expected = BadCredentialsException.class)
@ -156,13 +148,8 @@ public class LdapAuthenticationProviderTests {
CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException()); CommunicationException expectedCause = new CommunicationException(new javax.naming.CommunicationException());
given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause); given(mockAuthenticator.authenticate(authRequest)).willThrow(expectedCause);
LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator); LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(mockAuthenticator);
try { assertThatExceptionOfType(InternalAuthenticationServiceException.class)
ldapProvider.authenticate(authRequest); .isThrownBy(() -> ldapProvider.authenticate(authRequest)).havingCause().isSameAs(expectedCause);
fail("Expected Exception");
}
catch (InternalAuthenticationServiceException success) {
assertThat(success.getCause()).isSameAs(expectedCause);
}
} }
class MockAuthenticator implements LdapAuthenticator { class MockAuthenticator implements LdapAuthenticator {

View File

@ -54,7 +54,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory; import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider.ContextFactory;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -169,12 +169,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class), given(ctx.search(eq(new DistinguishedName("DC=mydomain,DC=eu")), any(String.class), any(Object[].class),
any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr)); any(SearchControls.class))).willReturn(new MockNamingEnumeration(sr));
this.provider.contextFactory = createContextFactoryReturning(ctx); this.provider.contextFactory = createContextFactoryReturning(ctx);
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.authenticate(this.joe);
fail("Expected BadCredentialsException for user with no domain information");
}
catch (BadCredentialsException expected) {
}
this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password")); this.provider.authenticate(new UsernamePasswordAuthenticationToken("joe@mydomain.eu", "password"));
} }
@ -278,12 +273,7 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
@Test(expected = CredentialsExpiredException.class) @Test(expected = CredentialsExpiredException.class)
public void expiredPasswordIsCorrectlyMapped() { public void expiredPasswordIsCorrectlyMapped() {
this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]")); this.provider.contextFactory = createContextFactoryThrowing(new AuthenticationException(msg + "532, xxxx]"));
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.provider.authenticate(this.joe));
this.provider.authenticate(this.joe);
fail("BadCredentialsException should had been thrown");
}
catch (BadCredentialsException expected) {
}
this.provider.setConvertSubErrorCodesToExceptions(true); this.provider.setConvertSubErrorCodesToExceptions(true);
this.provider.authenticate(this.joe); this.provider.authenticate(this.joe);
} }
@ -323,18 +313,12 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
this.provider.authenticate(this.joe); this.provider.authenticate(this.joe);
} }
@Test(expected = org.springframework.ldap.CommunicationException.class) @Test
public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Throwable { public void nonAuthenticationExceptionIsConvertedToSpringLdapException() throws Throwable {
try { assertThatExceptionOfType(InternalAuthenticationServiceException.class).isThrownBy(() -> {
this.provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg)); this.provider.contextFactory = createContextFactoryThrowing(new CommunicationException(msg));
this.provider.authenticate(this.joe); this.provider.authenticate(this.joe);
} }).withCauseInstanceOf(org.springframework.ldap.CommunicationException.class);
catch (InternalAuthenticationServiceException ex) {
// Since GH-8418 ldap communication exception is wrapped into
// InternalAuthenticationServiceException.
// This test is about the wrapped exception, so we throw it.
throw ex.getCause();
}
} }
@Test(expected = org.springframework.security.authentication.InternalAuthenticationServiceException.class) @Test(expected = org.springframework.security.authentication.InternalAuthenticationServiceException.class)
@ -368,16 +352,10 @@ public class ActiveDirectoryLdapAuthenticationProviderTests {
Hashtable<String, Object> env = new Hashtable<>(); Hashtable<String, Object> env = new Hashtable<>();
env.put("java.naming.ldap.factory.socket", "unknown.package.NonExistingSocketFactory"); env.put("java.naming.ldap.factory.socket", "unknown.package.NonExistingSocketFactory");
this.provider.setContextEnvironmentProperties(env); this.provider.setContextEnvironmentProperties(env);
try { assertThatExceptionOfType(InternalAuthenticationServiceException.class)
this.provider.authenticate(this.joe); .isThrownBy(() -> this.provider.authenticate(this.joe))
fail("CommunicationException was expected with a root cause of ClassNotFoundException"); .withCauseInstanceOf(org.springframework.ldap.CommunicationException.class)
} .withRootCauseInstanceOf(ClassNotFoundException.class);
catch (InternalAuthenticationServiceException expected) {
assertThat(expected.getCause()).isInstanceOf(org.springframework.ldap.CommunicationException.class);
org.springframework.ldap.CommunicationException cause = (org.springframework.ldap.CommunicationException) expected
.getCause();
assertThat(cause.getRootCause()).isInstanceOf(ClassNotFoundException.class);
}
} }
ContextFactory createContextFactoryThrowing(final NamingException ex) { ContextFactory createContextFactoryThrowing(final NamingException ex) {

View File

@ -38,7 +38,7 @@ import org.openid4java.message.ax.FetchResponse;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -90,18 +90,10 @@ public class OpenID4JavaConsumerTests {
OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory());
given(mgr.authenticate(ArgumentMatchers.<DiscoveryInformation>any(), any(), any())) given(mgr.authenticate(ArgumentMatchers.<DiscoveryInformation>any(), any(), any()))
.willThrow(new MessageException("msg"), new ConsumerException("msg")); .willThrow(new MessageException("msg"), new ConsumerException("msg"));
try { assertThatExceptionOfType(OpenIDConsumerException.class)
consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""));
fail("OpenIDConsumerException was not thrown"); assertThatExceptionOfType(OpenIDConsumerException.class)
} .isThrownBy(() -> consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""));
catch (OpenIDConsumerException expected) {
}
try {
consumer.beginConsumption(new MockHttpServletRequest(), "", "", "");
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
} }
@Test @Test
@ -125,24 +117,9 @@ public class OpenID4JavaConsumerTests {
.willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException("")); .willThrow(new MessageException(""), new AssociationException(""), new DiscoveryException(""));
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("x=5"); request.setQueryString("x=5");
try { assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
consumer.endConsumption(request); assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
fail("OpenIDConsumerException was not thrown"); assertThatExceptionOfType(OpenIDConsumerException.class).isThrownBy(() -> consumer.endConsumption(request));
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
try {
consumer.endConsumption(request);
fail("OpenIDConsumerException was not thrown");
}
catch (OpenIDConsumerException expected) {
}
} }
@SuppressWarnings("serial") @SuppressWarnings("serial")

View File

@ -31,7 +31,8 @@ import org.springframework.security.core.userdetails.UserDetailsByNameServiceWra
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link OpenIDAuthenticationProvider} * Tests {@link OpenIDAuthenticationProvider}
@ -60,13 +61,8 @@ public class OpenIDAuthenticationProviderTests {
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.CANCELLED, USERNAME, "", Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.CANCELLED, USERNAME, "",
null); null);
assertThat(preAuth.isAuthenticated()).isFalse(); assertThat(preAuth.isAuthenticated()).isFalse();
try { assertThatExceptionOfType(AuthenticationCancelledException.class)
provider.authenticate(preAuth); .isThrownBy(() -> provider.authenticate(preAuth)).withMessage("Log in cancelled");
fail("Should throw an AuthenticationException");
}
catch (AuthenticationCancelledException expected) {
assertThat(expected.getMessage()).isEqualTo("Log in cancelled");
}
} }
/* /*
@ -80,13 +76,8 @@ public class OpenIDAuthenticationProviderTests {
provider.setUserDetailsService(new MockUserDetailsService()); provider.setUserDetailsService(new MockUserDetailsService());
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.ERROR, USERNAME, "", null); Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.ERROR, USERNAME, "", null);
assertThat(preAuth.isAuthenticated()).isFalse(); assertThat(preAuth.isAuthenticated()).isFalse();
try { assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth))
provider.authenticate(preAuth); .withMessage("Error message from server: ");
fail("Should throw an AuthenticationException");
}
catch (AuthenticationServiceException expected) {
assertThat(expected.getMessage()).isEqualTo("Error message from server: ");
}
} }
/* /*
@ -101,13 +92,8 @@ public class OpenIDAuthenticationProviderTests {
new UserDetailsByNameServiceWrapper<>(new MockUserDetailsService())); new UserDetailsByNameServiceWrapper<>(new MockUserDetailsService()));
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null); Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.FAILURE, USERNAME, "", null);
assertThat(preAuth.isAuthenticated()).isFalse(); assertThat(preAuth.isAuthenticated()).isFalse();
try { assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(preAuth))
provider.authenticate(preAuth); .withMessage("Log in failed - identity could not be verified");
fail("Should throw an AuthenticationException");
}
catch (BadCredentialsException expected) {
assertThat("Log in failed - identity could not be verified").isEqualTo(expected.getMessage());
}
} }
/* /*
@ -122,14 +108,8 @@ public class OpenIDAuthenticationProviderTests {
Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SETUP_NEEDED, USERNAME, "", Authentication preAuth = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SETUP_NEEDED, USERNAME, "",
null); null);
assertThat(preAuth.isAuthenticated()).isFalse(); assertThat(preAuth.isAuthenticated()).isFalse();
try { assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> provider.authenticate(preAuth))
provider.authenticate(preAuth); .withMessage("The server responded setup was needed, which shouldn't happen");
fail("Should throw an AuthenticationException");
}
catch (AuthenticationServiceException expected) {
assertThat("The server responded setup was needed, which shouldn't happen")
.isEqualTo(expected.getMessage());
}
} }
/* /*
@ -158,13 +138,7 @@ public class OpenIDAuthenticationProviderTests {
@Test @Test
public void testDetectsMissingAuthoritiesPopulator() throws Exception { public void testDetectsMissingAuthoritiesPopulator() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
try { assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.afterPropertiesSet();
fail("Should have thrown Exception");
}
catch (IllegalArgumentException expected) {
// ignored
}
} }
/* /*
@ -207,13 +181,7 @@ public class OpenIDAuthenticationProviderTests {
@Test @Test
public void testValidation() throws Exception { public void testValidation() throws Exception {
OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider(); OpenIDAuthenticationProvider provider = new OpenIDAuthenticationProvider();
try { assertThatIllegalArgumentException().isThrownBy(provider::afterPropertiesSet);
provider.afterPropertiesSet();
fail("IllegalArgumentException expected, ssoAuthoritiesPopulator is null");
}
catch (IllegalArgumentException ex) {
// expected
}
provider = new OpenIDAuthenticationProvider(); provider = new OpenIDAuthenticationProvider();
provider.setUserDetailsService(new MockUserDetailsService()); provider.setUserDetailsService(new MockUserDetailsService());
provider.afterPropertiesSet(); provider.afterPropertiesSet();

View File

@ -30,7 +30,7 @@ import org.springframework.security.util.SimpleMethodInvocation;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link ContextPropagatingRemoteInvocation} and * Tests {@link ContextPropagatingRemoteInvocation} and
@ -59,15 +59,10 @@ public class ContextPropagatingRemoteInvocationTests {
Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala"); Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken("rod", "koala");
SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication);
ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation();
try {
// Set up the wrong arguments. // Set up the wrong arguments.
remoteInvocation.setArguments(new Object[] {}); remoteInvocation.setArguments(new Object[] {});
remoteInvocation.invoke(TargetObject.class.newInstance()); assertThatIllegalArgumentException()
fail("Expected IllegalArgumentException"); .isThrownBy(() -> remoteInvocation.invoke(TargetObject.class.newInstance()));
}
catch (IllegalArgumentException ex) {
// expected
}
assertThat(SecurityContextHolder.getContext().getAuthentication()) assertThat(SecurityContextHolder.getContext().getAuthentication())
.withFailMessage("Authentication must be null").isNull(); .withFailMessage("Authentication must be null").isNull();
} }

View File

@ -29,8 +29,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -85,14 +84,9 @@ public class Saml2WebSsoAuthenticationFilterTests {
this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}");
this.request.setPathInfo("/some/other/path/non-existent-id"); this.request.setPathInfo("/some/other/path/non-existent-id");
this.request.setParameter("SAMLResponse", "response"); this.request.setParameter("SAMLResponse", "response");
try { assertThatExceptionOfType(Saml2AuthenticationException.class)
this.filter.attemptAuthentication(this.request, this.response); .isThrownBy(() -> this.filter.attemptAuthentication(this.request, this.response))
failBecauseExceptionWasNotThrown(Saml2AuthenticationException.class); .withMessage("No relying party registration found");
}
catch (Exception ex) {
assertThat(ex).isInstanceOf(Saml2AuthenticationException.class);
assertThat(ex.getMessage()).isEqualTo("No relying party registration found");
}
} }
} }

View File

@ -29,7 +29,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* Tests {@link AuthenticationTag}. * Tests {@link AuthenticationTag}.
@ -106,13 +106,10 @@ public class AuthenticationTagTests {
public void testThrowsExceptionForUnrecognisedProperty() { public void testThrowsExceptionForUnrecognisedProperty() {
SecurityContextHolder.getContext().setAuthentication(this.auth); SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authenticationTag.setProperty("qsq"); this.authenticationTag.setProperty("qsq");
try { assertThatExceptionOfType(JspException.class).isThrownBy(() -> {
this.authenticationTag.doStartTag(); this.authenticationTag.doStartTag();
this.authenticationTag.doEndTag(); this.authenticationTag.doEndTag();
fail("Should have throwns JspException"); });
}
catch (JspException expected) {
}
} }
@Test @Test

View File

@ -43,7 +43,7 @@ import org.springframework.security.web.firewall.RequestRejectedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -206,12 +206,8 @@ public class FilterChainProxyTests {
throw new ServletException("oops"); throw new ServletException("oops");
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), }).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class)); any(FilterChain.class));
try { assertThatExceptionOfType(ServletException.class)
this.fcp.doFilter(this.request, this.response, this.chain); .isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
fail("Expected Exception");
}
catch (ServletException success) {
}
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
} }

View File

@ -22,7 +22,7 @@ import java.util.Map;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link PortMapperImpl}. * Tests {@link PortMapperImpl}.
@ -43,23 +43,13 @@ public class PortMapperImplTests {
@Test @Test
public void testDetectsEmptyMap() { public void testDetectsEmptyMap() {
PortMapperImpl portMapper = new PortMapperImpl(); PortMapperImpl portMapper = new PortMapperImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(new HashMap<>()));
portMapper.setPortMappings(new HashMap<>());
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testDetectsNullMap() { public void testDetectsNullMap() {
PortMapperImpl portMapper = new PortMapperImpl(); PortMapperImpl portMapper = new PortMapperImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(null));
portMapper.setPortMappings(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -73,12 +63,7 @@ public class PortMapperImplTests {
PortMapperImpl portMapper = new PortMapperImpl(); PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("79", "80559"); map.put("79", "80559");
try { assertThatIllegalArgumentException().isThrownBy(() -> portMapper.setPortMappings(map));
portMapper.setPortMappings(map);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -21,7 +21,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link PortResolverImpl}. * Tests {@link PortResolverImpl}.
@ -51,12 +51,7 @@ public class PortResolverImplTests {
@Test @Test
public void testDetectsEmptyPortMapper() { public void testDetectsEmptyPortMapper() {
PortResolverImpl pr = new PortResolverImpl(); PortResolverImpl pr = new PortResolverImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> pr.setPortMapper(null));
pr.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -48,7 +48,6 @@ import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -258,16 +257,12 @@ public class ExceptionTranslationFilterTests {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint); ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet(); filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() }; Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
for (Exception e : exceptions) { for (Exception exception : exceptions) {
FilterChain fc = mock(FilterChain.class); FilterChain fc = mock(FilterChain.class);
willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try { assertThatExceptionOfType(Exception.class)
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc); .isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc))
fail("Should have thrown Exception"); .isSameAs(exception);
}
catch (Exception expected) {
assertThat(expected).isSameAs(e);
}
} }
} }

View File

@ -33,6 +33,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -47,14 +48,10 @@ public class ChannelDecisionManagerImplTests {
@Test @Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception { public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(new Vector()); cdm.setChannelProcessors(new Vector());
cdm.afterPropertiesSet(); cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException"); }).withMessage("A list of ChannelProcessors is required");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
} }
@Test @Test
@ -62,25 +59,16 @@ public class ChannelDecisionManagerImplTests {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
List list = new Vector(); List list = new Vector();
list.add("THIS IS NOT A CHANNELPROCESSOR"); list.add("THIS IS NOT A CHANNELPROCESSOR");
try { assertThatIllegalArgumentException().isThrownBy(() -> cdm.setChannelProcessors(list));
cdm.setChannelProcessors(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testCannotSetNullChannelProcessorsList() throws Exception { public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try { assertThatIllegalArgumentException().isThrownBy(() -> {
cdm.setChannelProcessors(null); cdm.setChannelProcessors(null);
cdm.afterPropertiesSet(); cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException"); }).withMessage("A list of ChannelProcessors is required");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
} }
@Test @Test
@ -164,13 +152,8 @@ public class ChannelDecisionManagerImplTests {
@Test @Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception { public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl(); ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try { assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet)
cdm.afterPropertiesSet(); .withMessage("A list of ChannelProcessors is required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
} }
private class MockChannelProcessor implements ChannelProcessor { private class MockChannelProcessor implements ChannelProcessor {

View File

@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -74,12 +74,7 @@ public class InsecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception { public void testDecideRejectsNulls() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor(); InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.afterPropertiesSet(); processor.afterPropertiesSet();
try { assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -97,34 +92,19 @@ public class InsecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception { public void testMissingEntryPoint() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor(); InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setEntryPoint(null); processor.setEntryPoint(null);
try { assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
processor.afterPropertiesSet(); .withMessage("entryPoint required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
} }
@Test @Test
public void testMissingSecureChannelKeyword() throws Exception { public void testMissingSecureChannelKeyword() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor(); InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setInsecureKeyword(null); processor.setInsecureKeyword(null);
try { assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
processor.afterPropertiesSet(); .withMessage("insecureKeyword required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
processor.setInsecureKeyword(""); processor.setInsecureKeyword("");
try { assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
processor.afterPropertiesSet(); .withMessage("insecureKeyword required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
} }
@Test @Test

View File

@ -30,7 +30,7 @@ import org.springframework.security.web.PortResolver;
import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.RedirectStrategy;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -43,23 +43,13 @@ public class RetryWithHttpEntryPointTests {
@Test @Test
public void testDetectsMissingPortMapper() { public void testDetectsMissingPortMapper() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try { assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testDetectsMissingPortResolver() { public void testDetectsMissingPortResolver() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint(); RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try { assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -27,7 +27,7 @@ import org.springframework.security.MockPortResolver;
import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.PortMapperImpl;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link RetryWithHttpsEntryPoint}. * Tests {@link RetryWithHttpsEntryPoint}.
@ -39,23 +39,13 @@ public class RetryWithHttpsEntryPointTests {
@Test @Test
public void testDetectsMissingPortMapper() { public void testDetectsMissingPortMapper() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try { assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortMapper(null));
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
public void testDetectsMissingPortResolver() { public void testDetectsMissingPortResolver() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint(); RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try { assertThatIllegalArgumentException().isThrownBy(() -> ep.setPortResolver(null));
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -74,12 +74,7 @@ public class SecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception { public void testDecideRejectsNulls() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor(); SecureChannelProcessor processor = new SecureChannelProcessor();
processor.afterPropertiesSet(); processor.afterPropertiesSet();
try { assertThatIllegalArgumentException().isThrownBy(() -> processor.decide(null, null));
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test
@ -97,34 +92,19 @@ public class SecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception { public void testMissingEntryPoint() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor(); SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setEntryPoint(null); processor.setEntryPoint(null);
try { assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
processor.afterPropertiesSet(); .withMessage("entryPoint required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("entryPoint required");
}
} }
@Test @Test
public void testMissingSecureChannelKeyword() throws Exception { public void testMissingSecureChannelKeyword() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor(); SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setSecureKeyword(null); processor.setSecureKeyword(null);
try { assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
processor.afterPropertiesSet(); .withMessage("secureKeyword required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
processor.setSecureKeyword(""); processor.setSecureKeyword("");
try { assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet())
processor.afterPropertiesSet(); .withMessage("secureKeyword required");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
} }
@Test @Test

View File

@ -42,7 +42,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.FilterInvocation;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -135,12 +135,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class); AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
verifyZeroInteractions(aim); verifyZeroInteractions(aim);
} }
@ -163,12 +158,7 @@ public class FilterSecurityInterceptorTests {
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK")); given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class); AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim); this.interceptor.setAfterInvocationManager(aim);
try { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.interceptor.invoke(fi));
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
// Check we've changed back // Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx); assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);

View File

@ -48,6 +48,7 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@ -251,13 +252,8 @@ public class AbstractAuthenticationProcessingFilterTests {
this.successHandler.setDefaultTargetUrl("/"); this.successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(this.successHandler); filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login"); filter.setFilterProcessesUrl("/login");
try { assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet)
filter.afterPropertiesSet(); .withMessage("authenticationManager must be specified");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified");
}
} }
@Test @Test
@ -266,13 +262,8 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationFailureHandler(this.failureHandler); filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class)); filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(this.successHandler); filter.setAuthenticationSuccessHandler(this.successHandler);
try { assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null))
filter.setFilterProcessesUrl(null); .withMessage("Pattern cannot be null or empty");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty");
}
} }
@Test @Test

View File

@ -43,6 +43,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
@ -205,7 +206,7 @@ public class AuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull(); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
} }
@Test(expected = ServletException.class) @Test
public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception { public void filterWhenConvertAndAuthenticationEmptyThenServerError() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER"); Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication); given(this.authenticationConverter.convert(any())).willReturn(authentication);
@ -216,14 +217,9 @@ public class AuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class); FilterChain chain = mock(FilterChain.class);
try { assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain));
filter.doFilter(request, response, chain);
}
catch (ServletException ex) {
verifyZeroInteractions(this.successHandler); verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
throw ex;
}
} }
@Test @Test

View File

@ -25,7 +25,7 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.security.web.savedrequest.SavedRequest;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -38,12 +38,7 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
handler.setDefaultTargetUrl("/acceptableRelativeUrl"); handler.setDefaultTargetUrl("/acceptableRelativeUrl");
handler.setDefaultTargetUrl("https://some.site.org/index.html"); handler.setDefaultTargetUrl("https://some.site.org/index.html");
handler.setDefaultTargetUrl("https://some.site.org/index.html"); handler.setDefaultTargetUrl("https://some.site.org/index.html");
try { assertThatIllegalArgumentException().isThrownBy(() -> handler.setDefaultTargetUrl("missingSlash"));
handler.setDefaultTargetUrl("missingSlash");
fail("Shouldn't accept default target without leading slash");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -23,7 +23,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -104,18 +104,8 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test @Test
public void setTargetUrlParameterEmptyTargetUrlParameter() { public void setTargetUrlParameterEmptyTargetUrlParameter() {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(); SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
try { assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(""));
ash.setTargetUrlParameter(""); assertThatIllegalArgumentException().isThrownBy(() -> ash.setTargetUrlParameter(" "));
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
try {
ash.setTargetUrlParameter(" ");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
} }
} }

View File

@ -27,7 +27,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -114,12 +114,8 @@ public class UsernamePasswordAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class); AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException("")); given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am); filter.setAuthenticationManager(am);
try { assertThatExceptionOfType(AuthenticationException.class)
filter.attemptAuthentication(request, new MockHttpServletResponse()); .isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse()));
fail("Expected AuthenticationException");
}
catch (AuthenticationException ex) {
}
} }
/** /**

View File

@ -29,7 +29,7 @@ import org.mockito.InOrder;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.inOrder;
@ -88,12 +88,8 @@ public class CompositeLogoutHandlerTests {
any(HttpServletResponse.class), any(Authentication.class)); any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler); List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers); LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
try { assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class),
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class)); mock(HttpServletResponse.class), mock(Authentication.class)));
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler); InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class), logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class)); any(HttpServletResponse.class), any(Authentication.class));

View File

@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
/** /**
@ -59,14 +59,8 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test @Test
public void testThatSettNullHttpStatusThrowsException() { public void testThatSettNullHttpStatusThrowsException() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null))
new HttpStatusReturningLogoutSuccessHandler(null); .withMessage("The provided HttpStatus must not be null.");
}
catch (IllegalArgumentException ex) {
assertThat(ex).hasMessage("The provided HttpStatus must not be null.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
} }
} }

View File

@ -42,7 +42,7 @@ import org.springframework.security.web.authentication.ForwardAuthenticationSucc
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -105,15 +105,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test @Test
public void testAfterPropertiesSet() { public void testAfterPropertiesSet() {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter(); ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
try { assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet);
filter.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
} }
// SEC-2045 // SEC-2045

View File

@ -26,22 +26,15 @@ import org.springframework.security.authentication.AuthenticationCredentialsNotF
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint; import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class Http403ForbiddenEntryPointTests { public class Http403ForbiddenEntryPointTests {
public void testCommence() { public void testCommence() throws IOException {
MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse resp = new MockHttpServletResponse(); MockHttpServletResponse resp = new MockHttpServletResponse();
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint(); Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
try {
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test")); fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status") assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(HttpServletResponse.SC_FORBIDDEN);
.isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
catch (IOException ex) {
fail("Unexpected exception thrown: " + ex);
}
} }
} }

View File

@ -35,7 +35,7 @@ import org.springframework.security.core.authority.mapping.SimpleMappableAttribu
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails; import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* @author TSARDD * @author TSARDD
@ -45,15 +45,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
@Test @Test
public final void testAfterPropertiesSetException() { public final void testAfterPropertiesSetException() {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
try { assertThatIllegalArgumentException().isThrownBy(t::afterPropertiesSet);
t.afterPropertiesSet();
fail("AfterPropertiesSet didn't throw expected exception");
}
catch (IllegalArgumentException expected) {
}
catch (Exception unexpected) {
fail("AfterPropertiesSet throws unexpected exception");
}
} }
@Test @Test
@ -139,12 +131,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(); J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles)); result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper()); result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
try {
result.afterPropertiesSet(); result.afterPropertiesSet();
}
catch (Exception expected) {
fail("AfterPropertiesSet throws unexpected exception");
}
return result; return result;
} }

View File

@ -29,7 +29,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -86,12 +86,8 @@ public class CompositeSessionAuthenticationStrategyTests {
.onAuthentication(this.authentication, this.request, this.response); .onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy( CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2)); Arrays.asList(this.strategy1, this.strategy2));
try { assertThatExceptionOfType(SessionAuthenticationException.class)
strategy.onAuthentication(this.authentication, this.request, this.response); .isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response));
fail("Expected Exception");
}
catch (SessionAuthenticationException success) {
}
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response); verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response); verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response);
} }

View File

@ -24,7 +24,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.DisabledException;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link BasicAuthenticationEntryPoint}. * Tests {@link BasicAuthenticationEntryPoint}.
@ -36,13 +36,8 @@ public class BasicAuthenticationEntryPointTests {
@Test @Test
public void testDetectsMissingRealmName() { public void testDetectsMissingRealmName() {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint(); BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
try { assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
ep.afterPropertiesSet(); .withMessage("realmName must be specified");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
} }
@Test @Test

View File

@ -23,7 +23,7 @@ import org.junit.Test;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link org.springframework.security.util.StringSplitUtils}. * Tests {@link org.springframework.security.util.StringSplitUtils}.
@ -90,36 +90,12 @@ public class DigestAuthUtilsTests {
@Test @Test
public void testSplitRejectsNullsAndIncorrectLengthStrings() { public void testSplitRejectsNullsAndIncorrectLengthStrings() {
try { assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split(null, "="));
DigestAuthUtils.split(null, "="); // null assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("", "="));
fail("Should have thrown IllegalArgumentException"); assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null));
} assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", ""));
catch (IllegalArgumentException expected) { assertThatIllegalArgumentException()
} .isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"));
try {
DigestAuthUtils.split("", "="); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("sdch=dfgf", null); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
} }
@Test @Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.authentication.DisabledException;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Tests {@link DigestAuthenticationEntryPoint}. * Tests {@link DigestAuthenticationEntryPoint}.
@ -53,13 +53,7 @@ public class DigestAuthenticationEntryPointTests {
public void testDetectsMissingKey() throws Exception { public void testDetectsMissingKey() throws Exception {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("realm"); ep.setRealmName("realm");
try { assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet).withMessage("key must be specified");
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("key must be specified");
}
} }
@Test @Test
@ -67,13 +61,8 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint(); DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setKey("dcdc"); ep.setKey("dcdc");
ep.setNonceValiditySeconds(12); ep.setNonceValiditySeconds(12);
try { assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
ep.afterPropertiesSet(); .withMessage("realmName must be specified");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("realmName must be specified");
}
} }
@Test @Test

View File

@ -33,7 +33,7 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.context.SecurityContextImpl;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow; import static org.mockito.BDDMockito.willThrow;
@ -69,12 +69,7 @@ public class SecurityContextPersistenceFilterTests {
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(); SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken); SecurityContextHolder.getContext().setAuthentication(this.testToken);
willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); willThrow(new IOException()).given(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try { assertThatIOException().isThrownBy(() -> filter.doFilter(request, response, chain));
filter.doFilter(request, response, chain);
fail("IOException should have been thrown");
}
catch (IOException expected) {
}
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
} }

View File

@ -20,7 +20,7 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/** /**
* @author Luke Taylor * @author Luke Taylor
@ -33,23 +33,14 @@ public class DefaultHttpFirewallTests {
@Test @Test
public void unnormalizedPathsAreRejected() { public void unnormalizedPathsAreRejected() {
DefaultHttpFirewall fw = new DefaultHttpFirewall(); DefaultHttpFirewall fw = new DefaultHttpFirewall();
MockHttpServletRequest request;
for (String path : this.unnormalizedPaths) { for (String path : this.unnormalizedPaths) {
request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path); request.setServletPath(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
fw.getFirewalledRequest(request); .isThrownBy(() -> fw.getFirewalledRequest(request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
request.setPathInfo(path); request.setPathInfo(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
fw.getFirewalledRequest(request); .isThrownBy(() -> fw.getFirewalledRequest(request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
} }
} }

View File

@ -19,10 +19,9 @@ package org.springframework.security.web.firewall;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
public class DefaultRequestRejectedHandlerTests { public class DefaultRequestRejectedHandlerTests {
@ -31,14 +30,9 @@ public class DefaultRequestRejectedHandlerTests {
public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception { public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception {
RequestRejectedException requestRejectedException = new RequestRejectedException("rejected"); RequestRejectedException requestRejectedException = new RequestRejectedException("rejected");
DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler(); DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler();
try { assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut
sut.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException); .handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException))
} .withMessage("rejected");
catch (RequestRejectedException exception) {
Assert.assertThat(exception.getMessage(), CoreMatchers.is("rejected"));
return;
}
Assert.fail("Exception was not rethrown");
} }
} }

View File

@ -24,7 +24,7 @@ import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -166,12 +166,7 @@ public class FirewalledResponseTests {
} }
private void validateLineEnding(String name, String value) { private void validateLineEnding(String name, String value) {
try { assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.validateCrlf(name, value));
this.fwResponse.validateCrlf(name, value);
fail("IllegalArgumentException should have thrown");
}
catch (IllegalArgumentException expected) {
}
} }
} }

View File

@ -27,7 +27,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
/** /**
* @author Rob Winch * @author Rob Winch
@ -94,12 +93,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) { for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", ""); this.request = new MockHttpServletRequest("GET", "");
this.request.setRequestURI(path); this.request.setRequestURI(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
this.firewall.getFirewalledRequest(this.request); .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
} }
} }
@ -108,12 +103,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) { for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", ""); this.request = new MockHttpServletRequest("GET", "");
this.request.setContextPath(path); this.request.setContextPath(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
this.firewall.getFirewalledRequest(this.request); .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
} }
} }
@ -122,12 +113,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) { for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", ""); this.request = new MockHttpServletRequest("GET", "");
this.request.setServletPath(path); this.request.setServletPath(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
this.firewall.getFirewalledRequest(this.request); .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
} }
} }
@ -136,12 +123,8 @@ public class StrictHttpFirewallTests {
for (String path : this.unnormalizedPaths) { for (String path : this.unnormalizedPaths) {
this.request = new MockHttpServletRequest("GET", ""); this.request = new MockHttpServletRequest("GET", "");
this.request.setPathInfo(path); this.request.setPathInfo(path);
try { assertThatExceptionOfType(RequestRejectedException.class)
this.firewall.getFirewalledRequest(this.request); .isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
fail(path + " is un-normalized");
}
catch (RequestRejectedException expected) {
}
} }
} }

View File

@ -51,7 +51,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -179,29 +179,20 @@ public class SecurityContextHolderAwareRequestFilterTests {
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER")); .willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(expectedAuth); SecurityContextHolder.getContext().setAuthentication(expectedAuth);
try { assertThatExceptionOfType(ServletException.class).isThrownBy(
wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())); () -> wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())));
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth); assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expectedAuth);
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler); verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString()); verify(this.request, times(0)).login(anyString(), anyString());
} }
}
@Test @Test
public void loginFail() throws Exception { public void loginFail() throws Exception {
AuthenticationException authException = new BadCredentialsException("Invalid"); AuthenticationException authException = new BadCredentialsException("Invalid");
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willThrow(authException); .willThrow(authException);
try { assertThatExceptionOfType(ServletException.class)
wrappedRequest().login("invalid", "credentials"); .isThrownBy(() -> wrappedRequest().login("invalid", "credentials")).withCause(authException);
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success.getCause()).isEqualTo(authException);
}
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler); verifyZeroInteractions(this.authenticationEntryPoint, this.logoutHandler);
verify(this.request, times(0)).login(anyString(), anyString()); verify(this.request, times(0)).login(anyString(), anyString());
@ -226,13 +217,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
String password = "password"; String password = "password";
ServletException authException = new ServletException("Failed Login"); ServletException authException = new ServletException("Failed Login");
willThrow(authException).given(this.request).login(username, password); willThrow(authException).given(this.request).login(username, password);
try { assertThatExceptionOfType(ServletException.class).isThrownBy(() -> wrappedRequest().login(username, password))
wrappedRequest().login(username, password); .isEqualTo(authException);
fail("Expected Exception");
}
catch (ServletException success) {
assertThat(success).isEqualTo(authException);
}
verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler); verifyZeroInteractions(this.authenticationEntryPoint, this.authenticationManager, this.logoutHandler);
} }

View File

@ -22,7 +22,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/** /**
* Test cases for {@link ThrowableAnalyzer}. * Test cases for {@link ThrowableAnalyzer}.
@ -78,22 +78,15 @@ public class ThrowableAnalyzerTests {
@Test @Test
public void testRegisterExtractorWithInvalidExtractor() { public void testRegisterExtractorWithInvalidExtractor() {
try { assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() {
new ThrowableAnalyzer() {
/**
* @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
*/
@Override @Override
protected void initExtractorMap() { protected void initExtractorMap() {
// null is no valid extractor // null is no valid extractor
super.registerExtractor(Exception.class, null); super.registerExtractor(Exception.class, null);
} }
};
fail("IllegalArgumentExpected"); });
}
catch (IllegalArgumentException ex) {
// ok
}
} }
@Test @Test
@ -199,25 +192,15 @@ public class ThrowableAnalyzerTests {
@Test @Test
public void testVerifyThrowableHierarchyWithNull() { public void testVerifyThrowableHierarchyWithNull() {
try { assertThatIllegalArgumentException()
ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class); .isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class));
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
} }
@Test @Test
public void testVerifyThrowableHierarchyWithNonmatchingType() { public void testVerifyThrowableHierarchyWithNonmatchingType() {
Throwable throwable = new IllegalStateException("Test"); Throwable throwable = new IllegalStateException("Test");
try { assertThatIllegalArgumentException().isThrownBy(
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class); () -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class));
fail("IllegalArgumentException expected");
}
catch (IllegalArgumentException ex) {
// ok
}
} }
/** /**