From 00895487b1bcb34dfe7e1243332a85dc94c9b70e Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 4 Nov 2026 10:56:42 +0800 Subject: [PATCH 1/3] test: cover custom Shiro authentication and session behavior --- .../biz/CoreAuthenticationRegressionTest.java | 183 ++++++++++++++++++ .../shiro/biz/CoreSessionRegressionTest.java | 91 +++++++++ 2 files changed, 274 insertions(+) create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreAuthenticationRegressionTest.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreSessionRegressionTest.java diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreAuthenticationRegressionTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreAuthenticationRegressionTest.java new file mode 100644 index 00000000..5c0911e9 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreAuthenticationRegressionTest.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2018 (https://github.com/loong10k). + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.shiro.biz; + +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.shiro.authc.*; +import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher; +import org.apache.shiro.biz.authc.pam.AtLeastTwoAuthenticatorStrategy; +import org.apache.shiro.biz.authc.pam.DefaultModularRealmAuthenticator; +import org.apache.shiro.cache.MapCache; +import org.apache.shiro.realm.Realm; +import org.junit.Test; +import static org.junit.Assert.*; + +/** Offline regressions for this repository's authentication implementations. */ +public class CoreAuthenticationRegressionTest { + private final AuthenticationToken token = new UsernamePasswordToken("alice", "secret"); + + @Test public void singleSupportingRealmIsCalledAndUnsupportedRealmIsNot() { + StubRealm unsupported = new StubRealm("unsupported", false, null); + StubRealm supported = new StubRealm("supported", true, info("supported")); + DefaultModularRealmAuthenticator authenticator = authenticator(unsupported, supported); + assertEquals("alice", authenticator.authenticate(token).getPrincipals().getPrimaryPrincipal()); + assertEquals(0, unsupported.calls); + assertEquals(1, supported.calls); + } + + @Test public void singleRealmAuthenticationPreservesCustomFailure() { + StubRealm realm = new StubRealm("locked", true, null); + LockedAccountException failure = new LockedAccountException("locked locally"); + realm.failure = failure; + assertSame(failure, assertThrows(LockedAccountException.class, + () -> authenticator(realm).authenticate(token))); + assertEquals(1, realm.calls); + } + + @Test public void noSupportingRealmRejectsBeforeCallingAnyRealm() { + StubRealm first = new StubRealm("first", false, null); + StubRealm second = new StubRealm("second", false, null); + assertThrows(AuthenticationException.class, () -> authenticator(first, second).authenticate(token)); + assertEquals(0, first.calls); + assertEquals(0, second.calls); + } + + @Test public void missingRealmsAndUnknownAccountAreRejected() { + assertThrows(AuthenticationException.class, + () -> new DefaultModularRealmAuthenticator().authenticate(token)); + assertThrows(UnknownAccountException.class, + () -> authenticator(new StubRealm("empty", true, null)).authenticate(token)); + } + + @Test public void twoRealmStrategyAcceptsTwoIndependentSuccesses() { + StubRealm first = new StubRealm("first", true, info("first")); + StubRealm second = new StubRealm("second", true, info("second")); + DefaultModularRealmAuthenticator authenticator = authenticator(first, second); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + AuthenticationInfo result = authenticator.authenticate(token); + assertEquals(2, result.getPrincipals().getRealmNames().size()); + assertTrue(result.getPrincipals().getRealmNames().containsAll(Arrays.asList("first", "second"))); + assertEquals(1, first.calls); + assertEquals(1, second.calls); + } + + @Test public void twoRealmStrategyRejectsOneSuccessAndOneFailure() { + StubRealm first = new StubRealm("first", true, info("first")); + StubRealm second = new StubRealm("second", true, null); + second.failure = new IncorrectCredentialsException("wrong password"); + DefaultModularRealmAuthenticator authenticator = authenticator(first, second); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + assertThrows(AuthenticationException.class, () -> authenticator.authenticate(token)); + assertEquals(1, first.calls); + assertEquals(1, second.calls); + } + + @Test public void twoRealmStrategyRejectsNullEmptyAndSingleRealmAggregates() { + AtLeastTwoAuthenticatorStrategy strategy = new AtLeastTwoAuthenticatorStrategy(); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, null)); + AuthenticationInfo empty = strategy.beforeAllAttempts(Collections.emptyList(), token); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, empty)); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, info("single"))); + } + + @Test public void wrongCredentialsReachRetryBoundaryAndCorrectCredentialsRemainBlocked() { + MatcherFixture fixture = new MatcherFixture(); + AuthenticationToken wrong = new UsernamePasswordToken("alice", "wrong"); + for (int attempt = 1; attempt < fixture.matcher.getRetryLimit(); attempt++) { + assertFalse(fixture.matcher.doCredentialsMatch(wrong, info("realm"))); + assertEquals(attempt, fixture.cache.get("alice").get()); + } + assertThrows(ExcessiveAttemptsException.class, + () -> fixture.matcher.doCredentialsMatch(wrong, info("realm"))); + assertThrows(ExcessiveAttemptsException.class, + () -> fixture.matcher.doCredentialsMatch(token, info("realm"))); + } + + @Test public void successClearsOnlyThatPrincipalsRetryState() { + MatcherFixture fixture = new MatcherFixture(); + assertFalse(fixture.matcher.doCredentialsMatch(new UsernamePasswordToken("alice", "bad"), info("realm"))); + assertFalse(fixture.matcher.doCredentialsMatch(new UsernamePasswordToken("bob", "bad"), info("realm"))); + assertTrue(fixture.matcher.doCredentialsMatch(token, info("realm"))); + assertNull(fixture.cache.get("alice")); + assertEquals(1, fixture.cache.get("bob").get()); + assertFalse(fixture.matcher.doCredentialsMatch(new UsernamePasswordToken("alice", "bad"), info("realm"))); + assertEquals(1, fixture.cache.get("alice").get()); + } + + @Test public void byteAndCharacterCredentialsCompareByContent() { + MatcherFixture fixture = new MatcherFixture(); + AuthenticationInfo account = new SimpleAuthenticationInfo("alice", new byte[]{1, 2, 3}, "realm"); + assertTrue(fixture.matcher.doCredentialsMatch(new UsernamePasswordToken("alice", "secret"), info("realm"))); + AuthenticationToken bytes = new AuthenticationToken() { + public Object getPrincipal() { return "alice"; } + public Object getCredentials() { return new byte[]{1, 2, 3}; } + }; + assertTrue(fixture.matcher.doCredentialsMatch(bytes, account)); + assertFalse(fixture.matcher.doCredentialsMatch(bytes, + new SimpleAuthenticationInfo("alice", new byte[]{1, 2, 4}, "realm"))); + } + + @Test public void onlyOneStrategyMustRejectTwoSuccessfulRealms() { + DefaultModularRealmAuthenticator authenticator = authenticator( + new StubRealm("first", true, info("first")), + new StubRealm("second", true, info("second"))); + authenticator.setAuthenticationStrategy(new org.apache.shiro.biz.authc.pam.OnlyOneAuthenticatorStrategy()); + assertThrows(AuthenticationException.class, () -> authenticator.authenticate(token)); + } + + private static AuthenticationInfo info(String realm) { + return new SimpleAuthenticationInfo("alice", "secret", realm); + } + private static DefaultModularRealmAuthenticator authenticator(Realm... realms) { + DefaultModularRealmAuthenticator authenticator = new DefaultModularRealmAuthenticator(); + authenticator.setRealms(Arrays.asList(realms)); + return authenticator; + } + private static final class StubRealm implements Realm { + private final String name; + private final boolean supported; + private final AuthenticationInfo result; + private AuthenticationException failure; + private int calls; + private StubRealm(String name, boolean supported, AuthenticationInfo result) { + this.name = name; this.supported = supported; this.result = result; + } + public String getName() { return name; } + public boolean supports(AuthenticationToken ignored) { return supported; } + public AuthenticationInfo getAuthenticationInfo(AuthenticationToken ignored) { + calls++; + if (failure != null) { throw failure; } + return result; + } + } + private static final class MatcherFixture { + private final MapCache cache = + new MapCache<>("test", new ConcurrentHashMap<>()); + private final DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher(); + private MatcherFixture() { + matcher.setCacheManager(new org.apache.shiro.cache.CacheManager() { + @SuppressWarnings("unchecked") + public org.apache.shiro.cache.Cache getCache(String name) { + assertEquals(matcher.getCredentialsRetryCacheName(), name); + return (org.apache.shiro.cache.Cache) cache; + } + }); + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreSessionRegressionTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreSessionRegressionTest.java new file mode 100644 index 00000000..210a047e --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CoreSessionRegressionTest.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2018 (https://github.com/loong10k). + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.shiro.biz; + +import java.io.*; +import java.util.Date; +import org.apache.shiro.session.ExpiredSessionException; +import org.apache.shiro.session.StoppedSessionException; +import org.apache.shiro.session.mgt.SimpleOnlineSession; +import org.apache.shiro.session.mgt.SimpleOnlineSession.OnlineStatus; +import org.junit.Test; +import static org.junit.Assert.*; + +/** Exercise the custom session serialization used by persisted sessions. */ +public class CoreSessionRegressionTest { + @Test public void roundTripPreservesOnlineHiddenAndForcedLogoutStates() throws Exception { + for (OnlineStatus status : OnlineStatus.values()) { + SimpleOnlineSession original = new SimpleOnlineSession("client-host"); + original.setId("session-1"); + original.setUserAgent("local-test-agent"); + original.setSystemHost("server-host"); + original.setStatus(status); + original.setAttribute("principal", "alice"); + original.markAttributeChanged(); + SimpleOnlineSession restored = roundTrip(original); + assertEquals(status, restored.getStatus()); + assertEquals("local-test-agent", restored.getUserAgent()); + assertEquals("server-host", restored.getSystemHost()); + assertEquals("client-host", restored.getHost()); + assertEquals("session-1", restored.getId()); + assertEquals("alice", restored.getAttribute("principal")); + assertFalse("dirty state is transient", restored.isAttributeChanged()); + } + } + + @Test public void roundTripSupportsAbsentOptionalFields() throws Exception { + SimpleOnlineSession session = new SimpleOnlineSession(); + session.setStatus(null); + SimpleOnlineSession restored = roundTrip(session); + assertNull(restored.getStatus()); + assertNull(restored.getUserAgent()); + assertNull(restored.getSystemHost()); + } + + @Test public void stoppedAndExpiredSessionsStayRejectedAfterRoundTrip() throws Exception { + SimpleOnlineSession stopped = new SimpleOnlineSession(); + stopped.stop(); + SimpleOnlineSession restoredStopped = roundTrip(stopped); + assertThrows(StoppedSessionException.class, restoredStopped::validate); + SimpleOnlineSession expired = new SimpleOnlineSession(); + expired.setTimeout(1); + expired.setLastAccessTime(new Date(0)); + SimpleOnlineSession restoredExpired = roundTrip(expired); + assertThrows(ExpiredSessionException.class, restoredExpired::validate); + } + + @Test public void explicitDirtyStateCanBeResetWithoutLosingAttributes() { + SimpleOnlineSession session = new SimpleOnlineSession(); + assertFalse(session.isAttributeChanged()); + session.setAttribute("principal", "alice"); + session.markAttributeChanged(); + assertTrue(session.isAttributeChanged()); + session.resetAttributeChanged(); + assertFalse(session.isAttributeChanged()); + assertEquals("alice", session.removeAttribute("principal")); + assertNull(session.getAttribute("principal")); + } + + private static SimpleOnlineSession roundTrip(SimpleOnlineSession session) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream output = new ObjectOutputStream(bytes)) { + output.writeObject(session); + } + try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + return (SimpleOnlineSession) input.readObject(); + } + } +} From 9ba0257eb486c70f1258f3934ef0462fec29abcc Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:12:16 +0800 Subject: [PATCH 2/3] fix: enforce configured realm strategies and isolate authentication results --- ...edentialsRetryLimitCredentialsMatcher.java | 4 +- .../credential/DefaultCredentialsMatcher.java | 2 +- .../pam/AtLeastTwoAuthenticatorStrategy.java | 7 +- .../pam/DefaultModularRealmAuthenticator.java | 64 +----- .../pam/OnlyOneAuthenticatorStrategy.java | 19 +- .../authc/pam/RealmAuthenticationInfo.java | 57 +++++ .../biz/AuthenticationStrategySafetyTest.java | 206 ++++++++++++++++++ .../biz/CredentialsMatcherSafetyTest.java | 130 +++++++++++ 8 files changed, 426 insertions(+), 63 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/RealmAuthenticationInfo.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/CredentialsMatcherSafetyTest.java diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java index 5645a1b3..6d488242 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialsRetryLimitCredentialsMatcher.java @@ -109,11 +109,11 @@ public void setCredentialsRetryCacheName(String credentialsRetryCacheName) { this.credentialsRetryCacheName = credentialsRetryCacheName; } - public void setCredentialsRetryTimes(Cache credentialsRetryTimes) { + public synchronized void setCredentialsRetryTimes(Cache credentialsRetryTimes) { this.credentialsRetryTimes = credentialsRetryTimes; } - private Cache getCredentialsRetryCacheLazy() { + private synchronized Cache getCredentialsRetryCacheLazy() { if (this.credentialsRetryTimes == null) { this.credentialsRetryTimes = createCredentialsRetryCache(); } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/DefaultCredentialsMatcher.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/DefaultCredentialsMatcher.java index 5db4eb14..3a487628 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/DefaultCredentialsMatcher.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/DefaultCredentialsMatcher.java @@ -56,7 +56,7 @@ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo if (matches) { cacheManager.getCache(getCredentialsRetryCacheName()).remove(token.getPrincipal()); } - return credentialsMatch(token, info); + return matches; } //匹配用户输入的token的凭证(未加密)与系统提供的凭证(已加密) diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/AtLeastTwoAuthenticatorStrategy.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/AtLeastTwoAuthenticatorStrategy.java index 16b20d83..f419f642 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/AtLeastTwoAuthenticatorStrategy.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/AtLeastTwoAuthenticatorStrategy.java @@ -18,7 +18,6 @@ import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy; import org.apache.shiro.realm.Realm; import org.apache.shiro.util.CollectionUtils; @@ -34,7 +33,7 @@ public class AtLeastTwoAuthenticatorStrategy extends AbstractAuthenticationStrat @Override public AuthenticationInfo beforeAllAttempts(Collection realms, AuthenticationToken token) throws AuthenticationException { //返回一个权限的认证信息 - return new SimpleAuthenticationInfo(); + return new RealmAuthenticationInfo(); } @Override @@ -60,7 +59,9 @@ public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, A @Override public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException { - if (aggregate == null || CollectionUtils.isEmpty(aggregate.getPrincipals()) || aggregate.getPrincipals().getRealmNames().size() < 2) { + if (aggregate == null || CollectionUtils.isEmpty(aggregate.getPrincipals()) || aggregate.getPrincipals().getRealmNames().size() < 2 + || (aggregate instanceof RealmAuthenticationInfo + && ((RealmAuthenticationInfo) aggregate).getSuccessfulRealms() < 2)) { throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " + "could not be authenticated by any configured realms. Please ensure that at least two realm can " + "authenticate these tokens."); diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/DefaultModularRealmAuthenticator.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/DefaultModularRealmAuthenticator.java index 2d37d1f9..8c3910fb 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/DefaultModularRealmAuthenticator.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/DefaultModularRealmAuthenticator.java @@ -15,67 +15,27 @@ */ package org.apache.shiro.biz.authc.pam; -import org.apache.commons.collections.CollectionUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.pam.ModularRealmAuthenticator; import org.apache.shiro.realm.Realm; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; -import java.util.Iterator; -import java.util.List; public class DefaultModularRealmAuthenticator extends ModularRealmAuthenticator { - private static final Logger logger = LoggerFactory.getLogger(DefaultModularRealmAuthenticator.class); - - @Override - protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) - throws AuthenticationException { - - this.assertRealmsConfigured(); - - Collection realms = this.getRealms(); - - if (CollectionUtils.isEmpty(realms)) { - throw new IllegalStateException("Configuration error: No realms support token type:" + authenticationToken.getClass()); - } - - if (realms.size() == 1) { - return this.doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); - } else { - //获得匹配的Realm - List supportRealms = this.filterSupportRealms(realms, authenticationToken); - if(CollectionUtils.isEmpty(supportRealms)) { - throw new IllegalStateException("Configuration error: No realms support token type:" + authenticationToken.getClass()); - }else if(supportRealms.size() == 1) { - //只有一个匹配 - return this.doSingleRealmAuthentication(supportRealms.iterator().next(), authenticationToken); - }else { - //具有多个匹配,此时提醒开发者有可能会导致验证时的用户自定义异常丢失 - if(logger.isWarnEnabled()) { - logger.warn("token类型为"+authenticationToken.getClass().getName()+"有超多一个对应的Realm处理,有可能会导致认证时用户自定义认证异常丢失,请检查核对配置文件!!!"); - } - return this.doMultiRealmAuthentication(realms, authenticationToken); - } - } - } - - private List filterSupportRealms(Collection realms, AuthenticationToken authenticationToken) { - List supportRealms = new ArrayList(realms); - Iterator it = supportRealms.iterator(); - while(it.hasNext()) { - Realm r = it.next(); - if(!r.supports(authenticationToken)) { - it.remove(); - } - } - return supportRealms; - } - - + @Override + protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) + throws AuthenticationException { + assertRealmsConfigured(); + // Snapshot the configured set, not the supporting subset: strategies apply + // whenever multiple realms are configured, as in ModularRealmAuthenticator. + Collection realms = new ArrayList<>(getRealms()); + if (realms.size() == 1) { + return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken); + } + return doMultiRealmAuthentication(realms, authenticationToken); + } } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java index 5d721273..3bd0754a 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java @@ -18,7 +18,6 @@ import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; -import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy; import org.apache.shiro.biz.utils.StringUtils2; import org.apache.shiro.realm.Realm; @@ -40,7 +39,7 @@ public class OnlyOneAuthenticatorStrategy extends AbstractAuthenticationStrategy public AuthenticationInfo beforeAllAttempts(Collection realms, AuthenticationToken token) throws AuthenticationException { // 返回一个权限的认证信息 - return new SimpleAuthenticationInfo(); + return new RealmAuthenticationInfo(); } /** 在每个Realm之前调用 */ @@ -65,7 +64,9 @@ public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, A info = singleRealmInfo; } else { info = merge(singleRealmInfo, aggregateInfo); - if (info.getPrincipals().getRealmNames().size() > 1) { + if (info.getPrincipals().getRealmNames().size() > 1 + || (info instanceof RealmAuthenticationInfo + && ((RealmAuthenticationInfo) info).getSuccessfulRealms() > 1)) { LOG.debug("RealmNames:" + StringUtils2.join(info.getPrincipals().getRealmNames(), ",")); throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " + "could not be authenticated by any configured realms. Please ensure that only one realm can " @@ -80,6 +81,14 @@ public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, A @Override public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException { - return aggregate; - } + if (aggregate == null || aggregate.getPrincipals() == null + || aggregate.getPrincipals().isEmpty() + || aggregate.getPrincipals().getRealmNames().size() != 1 + || (aggregate instanceof RealmAuthenticationInfo + && ((RealmAuthenticationInfo) aggregate).getSuccessfulRealms() != 1)) { + throw new AuthenticationException("Exactly one realm must authenticate the token."); + } + return aggregate; + } + } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/RealmAuthenticationInfo.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/RealmAuthenticationInfo.java new file mode 100644 index 00000000..3f2c4f30 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/RealmAuthenticationInfo.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2018 (https://github.com/loong10k). + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.shiro.biz.authc.pam; + +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.SaltedAuthenticationInfo; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.subject.SimplePrincipalCollection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Set; + +/** An invocation-local aggregate that never mutates a realm's cached principals. */ +final class RealmAuthenticationInfo extends SimpleAuthenticationInfo { + private static final long serialVersionUID = 1L; + private int successfulRealms; + + int getSuccessfulRealms() { + return successfulRealms; + } + + @Override + public void merge(AuthenticationInfo info) { + if (info == null || info.getPrincipals() == null || info.getPrincipals().isEmpty()) { + return; + } + SimpleAuthenticationInfo snapshot = new SimpleAuthenticationInfo(); + snapshot.setPrincipals(new SimplePrincipalCollection(info.getPrincipals())); + Object credentials = info.getCredentials(); + if (credentials instanceof Set) { + credentials = new LinkedHashSet<>((Set) credentials); + } else if (credentials instanceof Collection) { + credentials = new ArrayList<>((Collection) credentials); + } + snapshot.setCredentials(credentials); + if (info instanceof SaltedAuthenticationInfo) { + snapshot.setCredentialsSalt(((SaltedAuthenticationInfo) info).getCredentialsSalt()); + } + super.merge(snapshot); + successfulRealms++; + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java new file mode 100644 index 00000000..2582ecf6 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2018 (https://github.com/loong10k). + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.shiro.biz; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.shiro.authc.*; +import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy; +import org.apache.shiro.biz.authc.pam.*; +import org.apache.shiro.mgt.DefaultSecurityManager; +import org.apache.shiro.realm.*; +import org.apache.shiro.subject.Subject; +import org.junit.Test; +import static org.junit.Assert.*; + +public class AuthenticationStrategySafetyTest { + private final UsernamePasswordToken token = new UsernamePasswordToken("alice", "secret"); + + @Test public void twoRealmPolicyRejectsSingleSupportingPasswordRealmAtSubjectLogin() { + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("password"), new SwitchableRealm("other", false, false)); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + } + @Test public void twoRealmPolicyRejectsZeroOrOneSuccessAndAcceptsTwo() { + for (int successes = 0; successes <= 2; successes++) { + DefaultModularRealmAuthenticator authenticator = auth(new SwitchableRealm("one", true, successes > 0), new SwitchableRealm("two", true, successes > 1)); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + if (successes < 2) assertSubjectRejected(authenticator); + else assertSubjectAccepted(authenticator); + } + } + @Test public void onlyOneRejectsZeroAndTwoSuccessesButAcceptsOne() { + for (int successes = 0; successes <= 2; successes++) { + DefaultModularRealmAuthenticator authenticator = auth(new SwitchableRealm("one", true, successes > 0), new SwitchableRealm("two", true, successes > 1)); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + if (successes != 1) assertSubjectRejected(authenticator); + else assertSubjectAccepted(authenticator); + } + } + @Test public void zeroSuccessEmitsFailureAndNeverSuccess() { + DefaultModularRealmAuthenticator authenticator = auth(new SwitchableRealm("one", true, false), new SwitchableRealm("two", true, false)); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + AtomicInteger successes = new AtomicInteger(); + AtomicInteger failures = new AtomicInteger(); + authenticator.setAuthenticationListeners(Collections.singletonList(new AuthenticationListener() { + public void onSuccess(AuthenticationToken token, AuthenticationInfo info) { successes.incrementAndGet(); } + public void onFailure(AuthenticationToken token, AuthenticationException failure) { failures.incrementAndGet(); } + public void onLogout(org.apache.shiro.subject.PrincipalCollection principals) { } + })); + assertThrows(AuthenticationException.class, () -> authenticator.authenticate(token)); + assertEquals(0, successes.get()); + assertEquals(1, failures.get()); + } + @Test public void onlyOneRejectsNullEmptyAndMultipleRealmAggregates() { + OnlyOneAuthenticatorStrategy strategy = new OnlyOneAuthenticatorStrategy(); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, null)); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, new SimpleAuthenticationInfo())); + SimpleAuthenticationInfo multiple = new SimpleAuthenticationInfo("alice", "secret", "one"); + multiple.merge(new SimpleAuthenticationInfo("alice", "secret", "two")); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, multiple)); + } + @Test public void oneConfiguredRealmKeepsUpstreamNoStrategyContract() { + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("one")); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + assertSubjectAccepted(authenticator); + assertThrows(IncorrectCredentialsException.class, + () -> authenticator.authenticate(new UsernamePasswordToken("alice", "wrong"))); + } + @Test public void configuredStrategiesRunEvenWithOneSupportingRealm() { + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("one"), new SwitchableRealm("two", false, false)); + AtomicInteger calls = new AtomicInteger(); + LockedAccountException denied = new LockedAccountException("strategy denied"); + authenticator.setAuthenticationStrategy(new AbstractAuthenticationStrategy() { + @Override public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) { + calls.incrementAndGet(); throw denied; + } + }); + assertSame(denied, assertThrows(LockedAccountException.class, () -> authenticator.authenticate(token))); + assertEquals(1, calls.get()); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + assertSubjectAccepted(authenticator); + } + @Test public void changingRealmSupportBetweenAttemptsDoesNotBypassPolicy() { + SwitchableRealm second = new SwitchableRealm("two", true, true); + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("one"), second); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + assertSubjectAccepted(authenticator); + second.supported = false; + assertSubjectRejected(authenticator); + second.supported = true; + assertSubjectAccepted(authenticator); + authenticator.setRealms(Collections.singletonList(passwordRealm("one"))); + assertSubjectAccepted(authenticator); + } + @Test public void unsupportedAndUnknownAccountRemainRejected() { + for (boolean supported : new boolean[]{false, true}) { + DefaultModularRealmAuthenticator authenticator = auth(new SwitchableRealm("one", supported, false), new SwitchableRealm("two", supported, false)); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + } + assertThrows(UnknownAccountException.class, () -> auth(new SimpleAccountRealm("empty")).authenticate(token)); + } + @Test public void sameNamedRealmsCannotSatisfyOnlyOneByCollapsingTheirNames() { + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("same"), passwordRealm("same")); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + } + @Test public void multiRealmFailuresFollowStrategyWhileSingleRealmPreservesSpecificException() { + Realm locked = new Realm() { + public String getName() { return "locked"; } + public boolean supports(AuthenticationToken token) { return true; } + public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) { throw new LockedAccountException("locked"); } + }; + assertThrows(LockedAccountException.class, () -> auth(locked).authenticate(token)); + DefaultModularRealmAuthenticator multi = auth(locked, new SwitchableRealm("unsupported", false, false)); + multi.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + AuthenticationException failure = assertThrows(AuthenticationException.class, () -> multi.authenticate(token)); + assertEquals(AuthenticationException.class, failure.getClass()); + } + @Test public void aggregationDoesNotMutateCachedPrincipalsCredentialsOrSalt() { + org.apache.shiro.lang.util.ByteSource salt = org.apache.shiro.lang.util.ByteSource.Util.bytes("test-salt"); + SimpleAuthenticationInfo first = new SimpleAuthenticationInfo("alice", new ArrayList<>(Collections.singletonList("first")), salt, "one"); + SimpleAuthenticationInfo second = new SimpleAuthenticationInfo("alice", "second", "two"); + AtLeastTwoAuthenticatorStrategy strategy = new AtLeastTwoAuthenticatorStrategy(); + AuthenticationInfo aggregate = strategy.beforeAllAttempts(Collections.emptyList(), token); + aggregate = strategy.afterAttempt(null, token, first, aggregate, null); + aggregate = strategy.afterAttempt(null, token, second, aggregate, null); + aggregate = strategy.afterAllAttempts(token, aggregate); + assertEquals(Collections.singleton("one"), first.getPrincipals().getRealmNames()); + assertEquals(Collections.singletonList("first"), first.getCredentials()); + SimpleAuthenticationInfo upstreamAggregate = new SimpleAuthenticationInfo(); + upstreamAggregate.merge(new SimpleAuthenticationInfo("alice", "first", salt, "one")); + assertEquals(upstreamAggregate.getCredentialsSalt(), ((SaltedAuthenticationInfo) aggregate).getCredentialsSalt()); + assertEquals(salt, first.getCredentialsSalt()); + assertTrue(((Collection) aggregate.getCredentials()).containsAll(Arrays.asList("first", "second"))); + } + @Test public void strategyStateIsIsolatedAcrossConcurrentAttempts() throws Exception { + OnlyOneAuthenticatorStrategy strategy = new OnlyOneAuthenticatorStrategy(); + java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newFixedThreadPool(4); + try { + java.util.List> results = new ArrayList<>(); + for (int i = 0; i < 12; i++) { + final boolean secondSucceeds = i % 2 == 0; + results.add(pool.submit(() -> { + DefaultModularRealmAuthenticator authenticator = auth(passwordRealm("one"), new SwitchableRealm("two", true, secondSucceeds)); + authenticator.setAuthenticationStrategy(strategy); + try { authenticator.authenticate(token); return !secondSucceeds; } + catch (AuthenticationException expected) { return secondSucceeds; } + })); + } + for (java.util.concurrent.Future result : results) assertTrue(result.get(5, java.util.concurrent.TimeUnit.SECONDS)); + } finally { pool.shutdownNow(); } + } + private void assertSubjectRejected(DefaultModularRealmAuthenticator authenticator) { + DefaultSecurityManager manager = new DefaultSecurityManager(); + manager.setAuthenticator(authenticator); + Subject subject = new Subject.Builder(manager).buildSubject(); + try { + assertThrows(AuthenticationException.class, () -> subject.login(token)); + assertFalse(subject.isAuthenticated()); + } finally { subject.logout(); manager.destroy(); } + } + private void assertSubjectAccepted(DefaultModularRealmAuthenticator authenticator) { + DefaultSecurityManager manager = new DefaultSecurityManager(); + manager.setAuthenticator(authenticator); + Subject subject = new Subject.Builder(manager).buildSubject(); + try { + subject.login(token); + assertTrue(subject.isAuthenticated()); + assertEquals("alice", subject.getPrincipal()); + } finally { subject.logout(); manager.destroy(); } + } + private static SimpleAccountRealm passwordRealm(String name) { + SimpleAccountRealm realm = new SimpleAccountRealm(name); + realm.addAccount("alice", "secret"); + return realm; + } + private static DefaultModularRealmAuthenticator auth(Realm... realms) { + DefaultModularRealmAuthenticator authenticator = new DefaultModularRealmAuthenticator(); + authenticator.setRealms(Arrays.asList(realms)); + return authenticator; + } + private static final class SwitchableRealm implements Realm { + private final String name; private boolean supported; private final boolean succeeds; + private SwitchableRealm(String name, boolean supported, boolean succeeds) { this.name=name; this.supported=supported; this.succeeds=succeeds; } + public String getName() { return name; } + public boolean supports(AuthenticationToken token) { return supported; } + public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) { + if (!succeeds) throw new IncorrectCredentialsException("local rejection"); + return new SimpleAuthenticationInfo("alice", "secret", name); + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/CredentialsMatcherSafetyTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CredentialsMatcherSafetyTest.java new file mode 100644 index 00000000..7ae68a56 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CredentialsMatcherSafetyTest.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2018 (https://github.com/loong10k). + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.shiro.biz; + +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.shiro.authc.*; +import org.apache.shiro.authc.credential.CredentialsMatcher; +import org.apache.shiro.biz.authc.credential.*; +import org.apache.shiro.cache.*; +import org.apache.shiro.crypto.hash.SimpleHash; +import org.junit.Test; +import static org.junit.Assert.*; + +public class CredentialsMatcherSafetyTest { + @Test public void successResetsOnlyItsPrincipalAndFailuresDoNotReset() { + for (boolean hashed : new boolean[]{false, true}) { + MapCache cache = cache(); + CredentialsMatcher matcher = matcher(hashed, cache); + assertFalse(matcher.doCredentialsMatch(token("alice", "wrong"), account(hashed))); + assertFalse(matcher.doCredentialsMatch(token("bob", "wrong"), account(hashed))); + assertTrue(matcher.doCredentialsMatch(token("alice", "secret"), account(hashed))); + assertNull(cache.get("alice")); + assertEquals(1, cache.get("bob").get()); + assertFalse(matcher.doCredentialsMatch(token("alice", "wrong"), account(hashed))); + assertEquals(1, cache.get("alice").get()); + } + } + @Test public void protectedComparisonIsCalledOnceAndFirstRejectionIsFinal() { + AtomicInteger calls = new AtomicInteger(); + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher() { + @Override protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo info) { return calls.incrementAndGet() > 1; } + }; + MapCache cache = cache(); + matcher.setCacheManager(manager(cache)); + assertFalse(matcher.doCredentialsMatch(token("alice", "secret"), account(false))); + assertEquals(1, calls.get()); + assertEquals(1, cache.get("alice").get()); + } + @Test public void comparisonExceptionPreservesAttemptAndPropagatesUnchanged() { + IllegalStateException failure = new IllegalStateException("local verifier failure"); + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher() { + @Override protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo info) { throw failure; } + }; + MapCache cache = cache(); + matcher.setCacheManager(manager(cache)); + assertSame(failure, assertThrows(IllegalStateException.class, () -> matcher.doCredentialsMatch(token("alice", "secret"), account(false)))); + assertEquals(1, cache.get("alice").get()); + } + @Test public void successfulProtectedComparisonRunsOnceAndClearsCounter() { + AtomicInteger calls = new AtomicInteger(); + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher() { + @Override protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo info) { calls.incrementAndGet(); return true; } + }; + MapCache cache = cache(); + matcher.setCacheManager(manager(cache)); + assertTrue(matcher.doCredentialsMatch(token("alice", "secret"), account(false))); + assertEquals(1, calls.get()); + assertNull(cache.get("alice")); + } + @Test public void lazyCacheIsCreatedOnceAndSafelyPublishedAcrossPrincipals() throws Exception { + AtomicInteger creations = new AtomicInteger(); + CountDownLatch creating = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + MapCache cache = cache(); + CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher() { + @Override protected Cache createCredentialsRetryCache() { + if (creations.incrementAndGet() == 1) { + creating.countDown(); + try { assertTrue(release.await(5, TimeUnit.SECONDS)); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(e); } + } + return cache; + } + }; + matcher.setHashAlgorithmName("SHA-256"); + FutureTask a = new FutureTask<>(() -> matcher.doCredentialsMatch(token("alice", "wrong"), account(true))); + FutureTask b = new FutureTask<>(() -> matcher.doCredentialsMatch(token("bob", "wrong"), account(true))); + Thread first = new Thread(a, "lazy-first"); + Thread second = new Thread(b, "lazy-second"); + first.start(); + try { + assertTrue(creating.await(5, TimeUnit.SECONDS)); + second.start(); + long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (second.isAlive() && second.getState() != Thread.State.BLOCKED && System.nanoTime() < end) Thread.yield(); + assertTrue(!second.isAlive() || second.getState() == Thread.State.BLOCKED); + } finally { release.countDown(); } + assertFalse(a.get(5, TimeUnit.SECONDS)); + assertFalse(b.get(5, TimeUnit.SECONDS)); + assertEquals(1, creations.get()); + assertEquals(1, cache.get("alice").get()); + assertEquals(1, cache.get("bob").get()); + } + private static CredentialsMatcher matcher(boolean hashed, MapCache cache) { + if (hashed) { + CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher(); + matcher.setHashAlgorithmName("SHA-256"); + matcher.setCredentialsRetryTimes(cache); + return matcher; + } + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher(); + matcher.setCacheManager(manager(cache)); + return matcher; + } + private static UsernamePasswordToken token(String principal, String password) { return new UsernamePasswordToken(principal, password); } + private static AuthenticationInfo account(boolean hashed) { + return new SimpleAuthenticationInfo("alice", hashed ? new SimpleHash("SHA-256", "secret").toHex() : "secret", "realm"); + } + private static MapCache cache() { return new MapCache<>("test", new ConcurrentHashMap<>()); } + private static CacheManager manager(Cache cache) { + return new CacheManager() { + @SuppressWarnings("unchecked") public Cache getCache(String name) { return (Cache) cache; } + }; + } +} From 1c04f43396d89603182d186845d6fca735e4a8be Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:20:00 +0800 Subject: [PATCH 3/3] fix: reject malformed realm results and test cached authentication boundaries --- .../pam/OnlyOneAuthenticatorStrategy.java | 6 ++ .../biz/AuthenticationStrategySafetyTest.java | 81 +++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java index 3bd0754a..3da9f187 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/pam/OnlyOneAuthenticatorStrategy.java @@ -56,6 +56,12 @@ public AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, @Override public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException { + // A non-null realm result must identify an account. Reject malformed + // results explicitly rather than leaking a null pointer from aggregation. + if (singleRealmInfo != null && (singleRealmInfo.getPrincipals() == null + || singleRealmInfo.getPrincipals().isEmpty())) { + throw new AuthenticationException("Realm returned authentication information without principals."); + } AuthenticationInfo info; if (singleRealmInfo == null) { info = aggregateInfo; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java index 2582ecf6..b2a663fa 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java @@ -164,6 +164,87 @@ public void onLogout(org.apache.shiro.subject.PrincipalCollection principals) { for (java.util.concurrent.Future result : results) assertTrue(result.get(5, java.util.concurrent.TimeUnit.SECONDS)); } finally { pool.shutdownNow(); } } + @Test public void oneSuccessfulRealmCannotPretendToBeTwoByReturningTwoRealmNames() { + SimpleAuthenticationInfo misleading = new SimpleAuthenticationInfo("alice", "secret", "one"); + ((org.apache.shiro.subject.MutablePrincipalCollection) misleading.getPrincipals()).add("alice", "claimed-two"); + DefaultModularRealmAuthenticator authenticator = auth(new CachedRealm("one", misleading), new SwitchableRealm("two", true, false)); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + } + @Test public void emptyRealmResultsRejectWithAuthenticationFailureRatherThanNullPointer() { + SimpleAuthenticationInfo nullPrincipals = new SimpleAuthenticationInfo(); + SimpleAuthenticationInfo emptyPrincipals = new SimpleAuthenticationInfo(); + emptyPrincipals.setPrincipals(new org.apache.shiro.subject.SimplePrincipalCollection()); + for (SimpleAuthenticationInfo empty : Arrays.asList(nullPrincipals, emptyPrincipals)) { + DefaultModularRealmAuthenticator authenticator = auth(new CachedRealm("one", empty), new CachedRealm("two", empty)); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + AuthenticationException failure = assertThrows(AuthenticationException.class, () -> authenticator.authenticate(token)); + assertNull("strategy must explicitly reject instead of wrapping a null pointer", failure.getCause()); + assertSubjectRejected(authenticator); + } + } + @Test public void malformedRealmResultRejectsEvenAlongsideValidRealm() { + for (boolean emptyFirst : new boolean[]{false, true}) { + Realm empty = new CachedRealm("empty", new SimpleAuthenticationInfo()); + Realm valid = passwordRealm("valid"); + DefaultModularRealmAuthenticator authenticator = emptyFirst ? auth(empty, valid) : auth(valid, empty); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + } + } + @Test public void onlyOneCallbackExplicitlyRejectsMalformedRealmResult() { + OnlyOneAuthenticatorStrategy strategy = new OnlyOneAuthenticatorStrategy(); + AuthenticationInfo aggregate = strategy.beforeAllAttempts(Collections.emptyList(), token); + assertThrows(AuthenticationException.class, + () -> strategy.afterAttempt(null, token, new SimpleAuthenticationInfo(), aggregate, null)); + assertThrows(AuthenticationException.class, () -> strategy.afterAllAttempts(token, aggregate)); + } + @Test public void reusedCachedSetCredentialsAndPrincipalsRemainIsolatedBetweenRequests() { + Set firstCredentials = Collections.unmodifiableSet(new LinkedHashSet<>(Collections.singleton("first"))); + Set secondCredentials = Collections.unmodifiableSet(new LinkedHashSet<>(Collections.singleton("second"))); + SimpleAuthenticationInfo first = new SimpleAuthenticationInfo("alice", firstCredentials, "one"); + SimpleAuthenticationInfo second = new SimpleAuthenticationInfo("alice", secondCredentials, "two"); + CachedRealm firstRealm = new CachedRealm("one", first); + CachedRealm secondRealm = new CachedRealm("two", second); + DefaultModularRealmAuthenticator authenticator = auth(firstRealm, secondRealm); + authenticator.setAuthenticationStrategy(new AtLeastTwoAuthenticatorStrategy()); + AuthenticationInfo merged = authenticator.authenticate(token); + assertTrue(merged.getCredentials() instanceof Set); + assertEquals(new LinkedHashSet<>(Arrays.asList("first", "second")), merged.getCredentials()); + assertNotSame(firstCredentials, merged.getCredentials()); + assertCachedUnchanged(first, second); + secondRealm.supported = false; + assertSubjectRejected(authenticator); + assertCachedUnchanged(first, second); + } + @Test public void onlyOneFailureDoesNotPolluteCachedInfoOrTheNextRequest() { + SimpleAuthenticationInfo first = new SimpleAuthenticationInfo("alice", Collections.unmodifiableSet(Collections.singleton("first")), "one"); + SimpleAuthenticationInfo second = new SimpleAuthenticationInfo("alice", Collections.unmodifiableSet(Collections.singleton("second")), "two"); + CachedRealm firstRealm = new CachedRealm("one", first); + CachedRealm secondRealm = new CachedRealm("two", second); + DefaultModularRealmAuthenticator authenticator = auth(firstRealm, secondRealm); + authenticator.setAuthenticationStrategy(new OnlyOneAuthenticatorStrategy()); + assertSubjectRejected(authenticator); + assertCachedUnchanged(first, second); + secondRealm.supported = false; + assertSubjectAccepted(authenticator); + assertCachedUnchanged(first, second); + } + private static void assertCachedUnchanged(AuthenticationInfo first, AuthenticationInfo second) { + assertEquals(Collections.singleton("one"), first.getPrincipals().getRealmNames()); + assertEquals(Collections.singleton("two"), second.getPrincipals().getRealmNames()); + assertEquals(Collections.singleton("first"), first.getCredentials()); + assertEquals(Collections.singleton("second"), second.getCredentials()); + } + private static final class CachedRealm implements Realm { + private final String name; + private final AuthenticationInfo cached; + private boolean supported = true; + private CachedRealm(String name, AuthenticationInfo cached) { this.name = name; this.cached = cached; } + public String getName() { return name; } + public boolean supports(AuthenticationToken token) { return supported; } + public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) { return cached; } + } private void assertSubjectRejected(DefaultModularRealmAuthenticator authenticator) { DefaultSecurityManager manager = new DefaultSecurityManager(); manager.setAuthenticator(authenticator);