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 01/50] 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 02/50] 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 03/50] 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); From 53b701e08794261e5a96d7a1d4c6c20eaecff950 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:04:50 +0800 Subject: [PATCH 04/50] Verify the JWT issuer parser isolation fix in Shiro CI --- .github/workflows/main-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index b23e0b36..b02ae947 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -20,7 +20,7 @@ jobs: uses: actions/checkout@v7 with: repository: easy-4-java/jwt-issuer - ref: 6b1a4de65a12a155e98e957ea82e446ef6420b36 + ref: c6edbf6a56a0c8ae6409b9fc1b0ef9639c4063d1 path: .ci-dependencies/jwt-issuer - name: Verify and install JWT issuer run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -f .ci-dependencies/jwt-issuer/pom.xml clean install From dec5b27ef9526bb14f69568ab9748eb8c6e7751f Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:14:52 +0800 Subject: [PATCH 05/50] Route Shiro credential checks through an atomic retry store --- .../credential/CredentialRetryStore.java | 49 ++++++++++++++ .../credential/CredentialRetrySupport.java | 22 +++++++ ...edentialsRetryLimitCredentialsMatcher.java | 18 +++++ .../credential/DefaultCredentialsMatcher.java | 18 +++++ .../biz/CredentialsMatcherSafetyTest.java | 65 +++++++++++++++++++ 5 files changed, 172 insertions(+) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java new file mode 100644 index 00000000..dcd203e2 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java @@ -0,0 +1,49 @@ +package org.apache.shiro.biz.authc.credential; + +import java.util.Objects; +import lombok.Getter; + +/** + * Shared credential retry state for one configured retry cache namespace. + * Implementations use the cache provider's atomic operations and expiration policy. + */ +public interface CredentialRetryStore { + + /** + * Atomically starts or increments the current window for a principal. Creation uses + * the configured expiration policy and an independent window identifier. Incrementing + * an existing window preserves its expiration and saturates at {@link Integer#MAX_VALUE}. + * + * @param principal stable key for the principal in this cache namespace + * @return the window identifier and count after reserving this attempt + */ + Attempt reserve(Object principal); + + /** + * Atomically clears the principal's window if it still has the specified identifier. + * + * @param principal stable key for the principal in this cache namespace + * @param windowId identifier returned by the attempt reservation + */ + void clearIfCurrent(Object principal, String windowId); + + /** Data returned by a successful reservation. */ + @Getter + final class Attempt { + + private final String windowId; + private final int count; + + /** + * @param windowId identifier unique to this principal's retry window + * @param count attempt count after the reservation, starting at one + */ + public Attempt(String windowId, int count) { + this.windowId = Objects.requireNonNull(windowId, "windowId"); + if (count < 1) { + throw new IllegalArgumentException("Attempt count must be positive"); + } + this.count = count; + } + } +} diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java new file mode 100644 index 00000000..4c469a46 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetrySupport.java @@ -0,0 +1,22 @@ +package org.apache.shiro.biz.authc.credential; + +import java.util.function.BooleanSupplier; +import org.apache.shiro.authc.ExcessiveAttemptsException; + +final class CredentialRetrySupport { + + private CredentialRetrySupport() { + } + + static boolean match(CredentialRetryStore store, Object principal, int limit, BooleanSupplier credentialsMatch) { + CredentialRetryStore.Attempt attempt = store.reserve(principal); + if (attempt.getCount() >= limit) { + throw new ExcessiveAttemptsException(); + } + boolean matches = credentialsMatch.getAsBoolean(); + if (matches) { + store.clearIfCurrent(principal, attempt.getWindowId()); + } + return matches; + } +} 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 6d488242..23997a4a 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 @@ -22,6 +22,7 @@ import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheManager; +import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; /** @@ -54,8 +55,25 @@ public class CredentialsRetryLimitCredentialsMatcher extends HashedCredentialsMa */ protected String credentialsRetryCacheName = CREDENTIALS_RETRY_CACHE_NAME; + private volatile CredentialRetryStore credentialRetryStore; + + /** + * Configures atomic retry accounting for this matcher's retry cache namespace. + * + * @param store provider-backed store, or null to use the existing Shiro cache integration + */ + public void setCredentialRetryStore(CredentialRetryStore store) { + this.credentialRetryStore = store; + } + @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { + CredentialRetryStore store = credentialRetryStore; + if (Objects.nonNull(store)) { + return CredentialRetrySupport.match(store, token.getPrincipal(), getCredentialsRetryTimesLimit(), + () -> super.doCredentialsMatch(token, info)); + } + AtomicInteger retryCount = getCachedRetryTimes(token.getPrincipal()); if (retryCount == null) { 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 3a487628..437e1fcd 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 @@ -27,6 +27,7 @@ import org.slf4j.LoggerFactory; import java.util.Arrays; +import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; /** @@ -47,8 +48,25 @@ public class DefaultCredentialsMatcher extends CodecSupport implements Credentia protected CacheManager cacheManager; + private volatile CredentialRetryStore credentialRetryStore; + + /** + * Configures atomic retry accounting for this matcher's retry cache namespace. + * + * @param store provider-backed store, or null to use the existing Shiro cache integration + */ + public void setCredentialRetryStore(CredentialRetryStore store) { + this.credentialRetryStore = store; + } + @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { + CredentialRetryStore store = credentialRetryStore; + if (Objects.nonNull(store)) { + return CredentialRetrySupport.match(store, token.getPrincipal(), getRetryLimit(), + () -> credentialsMatch(token, info)); + } + // check retry checkCredentialsRetry(token); // credentials match 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 index 7ae68a56..e7343d7c 100644 --- 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 @@ -106,6 +106,71 @@ public class CredentialsMatcherSafetyTest { assertEquals(1, cache.get("alice").get()); assertEquals(1, cache.get("bob").get()); } + @Test + public void configuredStoresShareLimitsAcrossMatcherInstancesAndResetOnSuccess() { + for (boolean hashed : new boolean[]{false, true}) { + TestRetryStore store = new TestRetryStore(); + CredentialsMatcher first = matcher(hashed, store); + CredentialsMatcher second = matcher(hashed, store); + + assertFalse(first.doCredentialsMatch(token("alice", "wrong"), account(hashed))); + assertFalse(second.doCredentialsMatch(token("alice", "wrong"), account(hashed))); + assertThrows(ExcessiveAttemptsException.class, + () -> second.doCredentialsMatch(token("alice", "secret"), account(hashed))); + assertTrue(first.doCredentialsMatch(token("bob", "secret"), account(hashed))); + assertEquals(3, store.attempts.get("alice").getCount()); + assertNull(store.attempts.get("bob")); + } + } + + @Test + public void lateSuccessfulComparisonCannotClearARenewedWindow() { + TestRetryStore store = new TestRetryStore(); + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher() { + @Override + protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo info) { + store.attempts.put(token.getPrincipal(), new CredentialRetryStore.Attempt("new-window", 1)); + return true; + } + }; + matcher.setCredentialRetryStore(store); + + assertTrue(matcher.doCredentialsMatch(token("alice", "secret"), account(false))); + assertEquals("new-window", store.attempts.get("alice").getWindowId()); + assertEquals(1, store.attempts.get("alice").getCount()); + } + + private static CredentialsMatcher matcher(boolean hashed, CredentialRetryStore store) { + if (hashed) { + CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher(); + matcher.setHashAlgorithmName("SHA-256"); + matcher.setCredentialsRetryTimesLimit(3); + matcher.setCredentialRetryStore(store); + return matcher; + } + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher(); + matcher.setRetryLimit(3); + matcher.setCredentialRetryStore(store); + return matcher; + } + + private static final class TestRetryStore implements CredentialRetryStore { + private final Map attempts = new ConcurrentHashMap<>(); + + @Override + public Attempt reserve(Object principal) { + return attempts.compute(principal, (key, previous) -> Objects.isNull(previous) + ? new Attempt(UUID.randomUUID().toString(), 1) + : new Attempt(previous.getWindowId(), previous.getCount() + 1)); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + attempts.computeIfPresent(principal, (key, current) -> + windowId.equals(current.getWindowId()) ? null : current); + } + } + private static CredentialsMatcher matcher(boolean hashed, MapCache cache) { if (hashed) { CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher(); From 29d2e68e672cc42d97b2493ebfbd7241359bc75f Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:22:09 +0800 Subject: [PATCH 06/50] Preserve Shiro retry windows with atomic Redis operations --- .github/workflows/main-ci.yml | 12 +- .../redis/RedisCredentialRetryStore.java | 96 ++++++++++++ ...isCredentialRetryStoreIntegrationTest.java | 141 ++++++++++++++++++ 3 files changed, 248 insertions(+), 1 deletion(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index b02ae947..44ef302f 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -10,6 +10,14 @@ jobs: verify: runs-on: ubuntu-latest timeout-minutes: 30 + services: + redis: + image: redis:8.4.0 + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 3s + --health-retries 5 steps: - uses: actions/checkout@v7 - uses: actions/setup-java@v5 @@ -25,7 +33,9 @@ jobs: - name: Verify and install JWT issuer run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -f .ci-dependencies/jwt-issuer/pom.xml clean install - name: Verify Shiro extension - run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" clean verify + env: + RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }} + run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" clean verify - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java new file mode 100644 index 00000000..b2df2382 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -0,0 +1,96 @@ +package org.apache.shiro.biz.cache.redis; + +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; + +/** + * Credential retry state held in a Redis hash. Each principal uses one key, so + * both operations are atomic on a single Redis Cluster slot. + */ +public final class RedisCredentialRetryStore implements CredentialRetryStore { + + private static final String RESERVE = """ + local window = redis.call('HGET', KEYS[1], 'window') + if not window then + redis.call('HSET', KEYS[1], 'window', ARGV[1], 'count', 1) + if ARGV[2] ~= '0' then + redis.call('PEXPIRE', KEYS[1], ARGV[2]) + end + return ARGV[1] .. ':1' + end + local count = redis.call('HGET', KEYS[1], 'count') + if tonumber(count) < 2147483647 then + count = redis.call('HINCRBY', KEYS[1], 'count', 1) + end + return window .. ':' .. count + """; + private static final String CLEAR = """ + if redis.call('HGET', KEYS[1], 'window') == ARGV[1] then + redis.call('DEL', KEYS[1]) + return '1' + end + return '0' + """; + + private final ScriptExecutor executor; + private final String namespace; + private final Function principalKey; + private final String expiryMillis; + + /** + * @param executor Redis client operation for scripts returning a UTF-8 bulk string + * @param namespace dedicated retry hash namespace, shared by all instances and separate from legacy keys + * @param principalKey stable, unambiguous principal encoding, identical on every instance + * @param expiry existing provider expiry for new windows, or zero for persistent windows + */ + public RedisCredentialRetryStore(ScriptExecutor executor, String namespace, + Function principalKey, Duration expiry) { + this.executor = Objects.requireNonNull(executor, "executor"); + this.namespace = Objects.requireNonNull(namespace, "namespace"); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + Objects.requireNonNull(expiry, "expiry"); + long millis = expiry.toMillis(); + if (namespace.isBlank() || expiry.isNegative() || (millis == 0 && !expiry.isZero())) { + throw new IllegalArgumentException("Retry state requires a namespace and a nonnegative millisecond expiry"); + } + this.expiryMillis = Long.toString(millis); + } + + @Override + public Attempt reserve(Object principal) { + String result = executor.eval(RESERVE, List.of(key(principal)), + List.of(UUID.randomUUID().toString(), expiryMillis)); + int separator = result.lastIndexOf(':'); + if (separator < 1) { + throw new IllegalStateException("Unexpected Redis retry reservation response"); + } + return new Attempt(result.substring(0, separator), Integer.parseInt(result.substring(separator + 1))); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + executor.eval(CLEAR, List.of(key(principal)), List.of(windowId)); + } + + private String key(Object principal) { + String encoded = Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + return namespace + ":" + encoded; + } + + /** Executes one script on the primary Redis node owning its key. */ + @FunctionalInterface + public interface ScriptExecutor { + + /** + * @param script Lua script to execute + * @param keys Redis keys supplied via KEYS + * @param args script arguments supplied via ARGV + * @return decoded bulk string from Redis + */ + String eval(String script, List keys, List args); + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..485394f5 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,141 @@ +package org.apache.shiro.biz.cache.redis; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class RedisCredentialRetryStoreIntegrationTest { + + private List redisCommand; + private final String namespace = "test:shiro-retry:" + UUID.randomUUID(); + + @Before + public void requireIsolatedRedis() { + String socket = System.getProperty("shiro.redis.test.socket"); + String container = System.getProperty("shiro.redis.test.container"); + assumeTrue("Supply an isolated Redis socket or container", Objects.nonNull(socket) || Objects.nonNull(container)); + redisCommand = Objects.nonNull(socket) + ? List.of("redis-cli", "--raw", "-s", socket) + : List.of("docker", "exec", container, "redis-cli", "--raw"); + } + + @Test + public void independentAdaptersShareAnAtomicCounterWithoutExtendingTtl() throws Exception { + RedisCredentialRetryStore first = newStore(Duration.ofSeconds(20)); + RedisCredentialRetryStore second = newStore(Duration.ofSeconds(20)); + CredentialRetryStore.Attempt initial = first.reserve("alice"); + assertEquals(1, initial.getCount()); + long before = Long.parseLong(redis("PEXPIRETIME", key("alice"))); + assertTrue(before > 0); + + ExecutorService threads = Executors.newFixedThreadPool(6); + try { + List> requests = new ArrayList<>(); + for (int index = 0; index < 16; index++) { + RedisCredentialRetryStore selected = index % 2 == 0 ? first : second; + requests.add(() -> selected.reserve("alice")); + } + + Set counts = new HashSet<>(); + for (Future result : threads.invokeAll(requests)) { + CredentialRetryStore.Attempt attempt = result.get(); + assertEquals(initial.getWindowId(), attempt.getWindowId()); + assertTrue(counts.add(attempt.getCount())); + } + for (int count = 2; count <= 17; count++) { + assertTrue(counts.contains(count)); + } + long after = Long.parseLong(redis("PEXPIRETIME", key("alice"))); + assertEquals("provider expiration deadline must be preserved", before, after); + } finally { + threads.shutdownNow(); + } + } + + @Test + public void staleSuccessCannotClearNewWindowAfterRedisExpiry() throws Exception { + RedisCredentialRetryStore store = newStore(Duration.ofSeconds(20)); + CredentialRetryStore.Attempt first = store.reserve("alice"); + redis("PEXPIRE", key("alice"), "1"); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + while (!"0".equals(redis("EXISTS", key("alice"))) && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals("0", redis("EXISTS", key("alice"))); + + CredentialRetryStore.Attempt second = store.reserve("alice"); + assertEquals(1, second.getCount()); + assertNotEquals(first.getWindowId(), second.getWindowId()); + store.clearIfCurrent("alice", first.getWindowId()); + assertEquals(2, store.reserve("alice").getCount()); + store.clearIfCurrent("alice", second.getWindowId()); + assertEquals(1, store.reserve("alice").getCount()); + } + + @Test + public void preservesConfiguredPersistenceAndSaturatesCount() { + RedisCredentialRetryStore store = newStore(Duration.ZERO); + store.reserve("alice"); + redis("HSET", key("alice"), "count", Integer.toString(Integer.MAX_VALUE)); + assertEquals(Integer.MAX_VALUE, store.reserve("alice").getCount()); + assertEquals("-1", redis("PTTL", key("alice"))); + } + + private RedisCredentialRetryStore newStore(Duration expiry) { + return new RedisCredentialRetryStore(this::eval, namespace, Object::toString, expiry); + } + + private String key(String principal) { + return namespace + ":" + principal; + } + + private String eval(String script, List keys, List args) { + List command = new ArrayList<>(Arrays.asList("EVAL", script, Integer.toString(keys.size()))); + command.addAll(keys); + command.addAll(args); + return redis(command.toArray(new String[0])); + } + + private String redis(String... args) { + List command = new ArrayList<>(redisCommand); + command.addAll(Arrays.asList(args)); + + try { + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(5, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Redis fixture command timed out"); + } + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).strip(); + if (process.exitValue() != 0 || output.startsWith("ERR ")) { + throw new IllegalStateException("Redis fixture command failed: " + output); + } + return output; + } catch (IOException e) { + throw new IllegalStateException("Unable to run Redis fixture", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while running Redis fixture", e); + } + } +} From 6ff281921232c71e35e96f0f6905ba829538c0e5 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:27:58 +0800 Subject: [PATCH 07/50] Add atomic Shiro retries for fixed-window JCache providers --- shiro-extension-core/pom.xml | 12 ++ .../credential/CredentialRetryStore.java | 5 +- .../jcache/JCacheCredentialRetryStore.java | 78 ++++++++ ...heCredentialRetryStoreIntegrationTest.java | 166 ++++++++++++++++++ 4 files changed, 260 insertions(+), 1 deletion(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index a41b6009..8b83581d 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -74,6 +74,18 @@ lombok provided + + javax.cache + cache-api + 1.1.1 + provided + + + com.hazelcast + hazelcast + 3.12.13 + test + junit junit diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java index dcd203e2..fcdf47ab 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java @@ -1,5 +1,6 @@ package org.apache.shiro.biz.authc.credential; +import java.io.Serializable; import java.util.Objects; import lombok.Getter; @@ -29,7 +30,9 @@ public interface CredentialRetryStore { /** Data returned by a successful reservation. */ @Getter - final class Attempt { + final class Attempt implements Serializable { + + private static final long serialVersionUID = 1L; private final String windowId; private final int count; diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java new file mode 100644 index 00000000..aa638f4e --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -0,0 +1,78 @@ +package org.apache.shiro.biz.cache.jcache; + +import java.util.Objects; +import java.util.UUID; +import javax.cache.Cache; +import javax.cache.configuration.CompleteConfiguration; +import javax.cache.expiry.Duration; +import javax.cache.expiry.ExpiryPolicy; +import javax.cache.processor.EntryProcessor; +import javax.cache.processor.MutableEntry; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; + +/** + * Shared retry state in a dedicated JCache with a fixed creation expiry. + * The cache provider executes each state change atomically against one entry. + */ +public final class JCacheCredentialRetryStore implements CredentialRetryStore { + + private final Cache cache; + + /** + * @param cache shared retry cache using store-by-value and a nonzero creation expiry + * or eternal expiry. Its expiry policy must leave the deadline unchanged + * on both access and update. All cluster members must have this module. + */ + public JCacheCredentialRetryStore(Cache cache) { + this.cache = Objects.requireNonNull(cache, "cache"); + CompleteConfiguration configuration = cache.getConfiguration(CompleteConfiguration.class); + ExpiryPolicy policy = configuration.getExpiryPolicyFactory().create(); + Duration creation = policy.getExpiryForCreation(); + if (!configuration.isStoreByValue() || Objects.isNull(creation) || creation.isZero() + || Objects.nonNull(policy.getExpiryForUpdate()) || Objects.nonNull(policy.getExpiryForAccess())) { + throw new IllegalArgumentException("Retry cache must store by value and preserve its creation expiry"); + } + } + + @Override + public Attempt reserve(Object principal) { + return cache.invoke(principal, Reserve.INSTANCE, UUID.randomUUID().toString()); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + cache.invoke(principal, Clear.INSTANCE, Objects.requireNonNull(windowId, "windowId")); + } + + private enum Reserve implements EntryProcessor { + INSTANCE; + + @Override + public Attempt process(MutableEntry entry, Object... arguments) { + Attempt current = entry.getValue(); + Attempt next; + if (Objects.isNull(current)) { + next = new Attempt((String) arguments[0], 1); + } else if (current.getCount() == Integer.MAX_VALUE) { + return current; + } else { + next = new Attempt(current.getWindowId(), current.getCount() + 1); + } + entry.setValue(next); + return next; + } + } + + private enum Clear implements EntryProcessor { + INSTANCE; + + @Override + public Void process(MutableEntry entry, Object... arguments) { + Attempt current = entry.getValue(); + if (Objects.nonNull(current) && current.getWindowId().equals(arguments[0])) { + entry.remove(); + } + return null; + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..1870827c --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,166 @@ +package org.apache.shiro.biz.cache.jcache; + +import com.hazelcast.cache.impl.HazelcastServerCachingProvider; +import com.hazelcast.config.Config; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.cache.Cache; +import javax.cache.CacheManager; +import javax.cache.configuration.Factory; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.expiry.CreatedExpiryPolicy; +import javax.cache.expiry.Duration; +import javax.cache.expiry.EternalExpiryPolicy; +import javax.cache.expiry.ExpiryPolicy; +import javax.cache.expiry.ModifiedExpiryPolicy; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class JCacheCredentialRetryStoreIntegrationTest { + + private static HazelcastInstance firstMember; + private static HazelcastInstance secondMember; + private static CacheManager firstManager; + private static CacheManager secondManager; + + @BeforeClass + public static void startCluster() throws IOException { + String cluster = "shiro-retry-" + UUID.randomUUID(); + int firstPort; + int secondPort; + try (ServerSocket first = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); + ServerSocket second = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + firstPort = first.getLocalPort(); + secondPort = second.getLocalPort(); + } + firstMember = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); + secondMember = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); + assertEquals(2, firstMember.getCluster().getMembers().size()); + firstManager = HazelcastServerCachingProvider.createCachingProvider(firstMember).getCacheManager(); + secondManager = HazelcastServerCachingProvider.createCachingProvider(secondMember).getCacheManager(); + } + + @AfterClass + public static void stopCluster() { + if (secondMember != null) { + secondMember.getLifecycleService().terminate(); + } + if (firstMember != null) { + firstMember.getLifecycleService().terminate(); + } + } + + @Test + public void incrementsAtomicallyAcrossMembersAndSaturates() throws Exception { + Cache cache = createCache("atomic", EternalExpiryPolicy.factoryOf()); + JCacheCredentialRetryStore first = new JCacheCredentialRetryStore(cache); + JCacheCredentialRetryStore second = new JCacheCredentialRetryStore( + secondManager.getCache("atomic", Object.class, Attempt.class)); + ExecutorService threads = Executors.newFixedThreadPool(6); + try { + List> attempts = new ArrayList<>(); + for (int index = 0; index < 20; index++) { + JCacheCredentialRetryStore selected = index % 2 == 0 ? first : second; + attempts.add(() -> selected.reserve("alice")); + } + + Set windows = new HashSet<>(); + Set counts = new HashSet<>(); + for (Future future : threads.invokeAll(attempts, 10, TimeUnit.SECONDS)) { + Attempt attempt = future.get(); + windows.add(attempt.getWindowId()); + assertTrue(counts.add(attempt.getCount())); + } + assertEquals(1, windows.size()); + assertEquals(20, counts.size()); + assertEquals(20, cache.get("alice").getCount()); + cache.put("alice", new Attempt(cache.get("alice").getWindowId(), Integer.MAX_VALUE)); + assertEquals(Integer.MAX_VALUE, second.reserve("alice").getCount()); + } finally { + threads.shutdownNow(); + } + } + + @Test + public void preservesExpiryAcrossUpdatesAndRejectsStaleReset() throws Exception { + Cache cache = createCache("expiration", + CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 3))); + JCacheCredentialRetryStore first = new JCacheCredentialRetryStore(cache); + JCacheCredentialRetryStore second = new JCacheCredentialRetryStore( + secondManager.getCache("expiration", Object.class, Attempt.class)); + + Attempt initial = first.reserve("alice"); + long start = System.nanoTime(); + awaitElapsed(start, 1400); + assertEquals(2, second.reserve("alice").getCount()); + awaitElapsed(start, 3300); + assertNull(cache.get("alice")); + + Attempt renewed = second.reserve("alice"); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + first.clearIfCurrent("alice", initial.getWindowId()); + assertEquals(2, first.reserve("alice").getCount()); + second.clearIfCurrent("alice", renewed.getWindowId()); + assertNull(cache.get("alice")); + } + + @Test + public void rejectsCacheWhosePolicyRestartsExpiryOnUpdate() { + Cache cache = createCache("sliding", + ModifiedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 20))); + assertThrows(IllegalArgumentException.class, () -> new JCacheCredentialRetryStore(cache)); + } + + private static void awaitElapsed(long start, long millis) throws InterruptedException { + long remaining = TimeUnit.MILLISECONDS.toNanos(millis) - (System.nanoTime() - start); + if (remaining > 0) { + TimeUnit.NANOSECONDS.sleep(remaining); + } + } + + private static Cache createCache(String name, Factory policy) { + return firstManager.createCache(name, new MutableConfiguration() + .setTypes(Object.class, Attempt.class).setExpiryPolicyFactory(policy).setStoreByValue(true)); + } + + private static Config member(String cluster, int ownPort, int otherPort) { + Config configuration = new Config(); + configuration.getGroupConfig().setName(cluster); + configuration.setProperty("hazelcast.logging.type", "none"); + configuration.setProperty("hazelcast.operation.thread.count", "2"); + configuration.setProperty("hazelcast.operation.generic.thread.count", "2"); + configuration.setProperty("hazelcast.io.thread.count", "2"); + configuration.setProperty("hazelcast.event.thread.count", "2"); + configuration.setProperty("hazelcast.wait.seconds.before.join", "0"); + configuration.setProperty("hazelcast.socket.bind.any", "false"); + NetworkConfig network = configuration.getNetworkConfig(); + network.setPort(ownPort).setPortAutoIncrement(false); + network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + network.getJoin().getMulticastConfig().setEnabled(false); + network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + return configuration; + } +} From 9ebe0ffdc1b8a52978a3e72317e6829e340ba989 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:35:46 +0800 Subject: [PATCH 08/50] Add native Ehcache 3 credential retry storage --- shiro-extension-core/pom.xml | 6 + .../credential/CredentialRetryStore.java | 2 + .../ehcache/Ehcache3CredentialRetryStore.java | 117 ++++++++++++++++++ ...e3CredentialRetryStoreIntegrationTest.java | 108 ++++++++++++++++ 4 files changed, 233 insertions(+) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index 8b83581d..bf35e788 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -74,6 +74,12 @@ lombok provided + + org.ehcache + ehcache + 3.6.0 + provided + javax.cache cache-api diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java index fcdf47ab..248550a9 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java @@ -2,6 +2,7 @@ import java.io.Serializable; import java.util.Objects; +import lombok.EqualsAndHashCode; import lombok.Getter; /** @@ -30,6 +31,7 @@ public interface CredentialRetryStore { /** Data returned by a successful reservation. */ @Getter + @EqualsAndHashCode final class Attempt implements Serializable { private static final long serialVersionUID = 1L; diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java new file mode 100644 index 00000000..73923b90 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -0,0 +1,117 @@ +package org.apache.shiro.biz.cache.ehcache; + +import java.time.Duration; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; +import org.ehcache.Cache; +import org.ehcache.expiry.ExpiryPolicy; + +/** + * Credential retry state backed by native Ehcache 3 conditional operations. + * A clustered cache must provide strong consistency for its shared retry region. + * + * @param cache key type + */ +public final class Ehcache3CredentialRetryStore implements CredentialRetryStore { + + private static final int MAX_CONFLICTS = 128; + + private final Cache cache; + private final Function principalKey; + + /** + * @param cache dedicated retry cache configured with {@link #fixedWindowExpiry(Duration)} + * or Ehcache's eternal expiry + * @param principalKey consistent principal key encoding for all callers sharing the cache + */ + public Ehcache3CredentialRetryStore(Cache cache, Function principalKey) { + this.cache = Objects.requireNonNull(cache, "cache"); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + ExpiryPolicy expiry = cache.getRuntimeConfiguration().getExpiryPolicy(); + if (!(expiry instanceof FixedWindowExpiry) && !ExpiryPolicy.NO_EXPIRY.equals(expiry)) { + throw new IllegalArgumentException("Retry cache must preserve its creation expiry"); + } + } + + /** + * Returns an expiry policy for a dedicated retry cache. + * + * @param window configured duration for a newly created retry window + * @return policy that retains the first deadline on reads and updates + */ + public static ExpiryPolicy fixedWindowExpiry(Duration window) { + Objects.requireNonNull(window, "window"); + if (window.isZero() || window.isNegative()) { + throw new IllegalArgumentException("Retry window must be positive"); + } + return new FixedWindowExpiry(window); + } + + @Override + public Attempt reserve(Object principal) { + K key = key(principal); + for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { + Attempt current = cache.get(key); + if (Objects.isNull(current)) { + Attempt initial = new Attempt(UUID.randomUUID().toString(), 1); + if (Objects.isNull(cache.putIfAbsent(key, initial))) { + return initial; + } + } else { + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } + Attempt next = new Attempt(current.getWindowId(), current.getCount() + 1); + if (cache.replace(key, current, next)) { + return next; + } + } + } + throw new CacheException("Unable to reserve credential attempt within the conflict limit"); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + K key = key(principal); + Objects.requireNonNull(windowId, "windowId"); + for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { + Attempt current = cache.get(key); + if (Objects.isNull(current) || !windowId.equals(current.getWindowId()) || cache.remove(key, current)) { + return; + } + } + throw new CacheException("Unable to clear credential retry state within the conflict limit"); + } + + private K key(Object principal) { + return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + } + + private static final class FixedWindowExpiry implements ExpiryPolicy { + + private final Duration window; + + private FixedWindowExpiry(Duration window) { + this.window = window; + } + + @Override + public Duration getExpiryForCreation(Object key, Attempt value) { + return window; + } + + @Override + public Duration getExpiryForAccess(Object key, Supplier value) { + return null; + } + + @Override + public Duration getExpiryForUpdate(Object key, Supplier previous, Attempt next) { + return null; + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..cf6f9611 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,108 @@ +package org.apache.shiro.biz.cache.ehcache; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.ehcache.Cache; +import org.ehcache.CacheManager; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.MemoryUnit; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.impl.internal.TimeSourceConfiguration; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class Ehcache3CredentialRetryStoreIntegrationTest { + + @Test + public void reservesUniqueCountsWithSerializedValuesAndSaturates() throws Exception { + try (CacheManager manager = manager(new AtomicLong(10_000), ExpiryPolicy.NO_EXPIRY)) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore first = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + Ehcache3CredentialRetryStore second = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + ExecutorService threads = Executors.newFixedThreadPool(6); + try { + List> requests = new ArrayList<>(); + for (int index = 0; index < 24; index++) { + Ehcache3CredentialRetryStore store = index % 2 == 0 ? first : second; + requests.add(() -> store.reserve("alice")); + } + Set counts = new HashSet<>(); + Set windows = new HashSet<>(); + for (Future future : threads.invokeAll(requests, 5, TimeUnit.SECONDS)) { + Attempt result = future.get(); + assertTrue(counts.add(result.getCount())); + windows.add(result.getWindowId()); + } + assertEquals(24, counts.size()); + assertEquals(1, windows.size()); + Attempt current = cache.get("alice"); + assertEquals(24, current.getCount()); + cache.put("alice", new Attempt(current.getWindowId(), Integer.MAX_VALUE)); + assertEquals(Integer.MAX_VALUE, first.reserve("alice").getCount()); + } finally { + threads.shutdownNow(); + } + } + } + + @Test + public void preservesOriginalDeadlineAndIgnoresResetFromExpiredWindow() { + AtomicLong time = new AtomicLong(10_000); + try (CacheManager manager = manager(time, Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + Attempt initial = store.reserve("alice"); + time.set(12_000); + assertEquals(2, store.reserve("alice").getCount()); + time.set(12_999); + assertEquals(3, store.reserve("alice").getCount()); + time.set(13_001); + assertNull(cache.get("alice")); + + Attempt renewed = store.reserve("alice"); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + assertEquals(1, renewed.getCount()); + store.clearIfCurrent("alice", initial.getWindowId()); + assertEquals(2, store.reserve("alice").getCount()); + store.clearIfCurrent("alice", renewed.getWindowId()); + assertNull(cache.get("alice")); + } + } + + @Test + public void rejectsPoliciesThatReplaceExpiryOnWrites() { + try (CacheManager manager = manager(new AtomicLong(10_000), + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(5)))) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + assertThrows(IllegalArgumentException.class, + () -> new Ehcache3CredentialRetryStore<>(cache, Object::toString)); + } + } + + private static CacheManager manager(AtomicLong time, ExpiryPolicy policy) { + return CacheManagerBuilder.newCacheManagerBuilder() + .using(new TimeSourceConfiguration(time::get)) + .withCache("retry", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, Attempt.class, ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(policy)) + .build(true); + } +} From 2275469d5a381fab43ac8b375106c473ad9bbbd2 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:44:40 +0800 Subject: [PATCH 09/50] Keep Ehcache 2 credential retries atomic across nodes --- shiro-extension-core/pom.xml | 6 + .../ehcache/Ehcache2CredentialRetryStore.java | 83 ++++++++++++ ...e2CredentialRetryStoreIntegrationTest.java | 127 ++++++++++++++++++ 3 files changed, 216 insertions(+) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index bf35e788..f63b6a02 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -74,6 +74,12 @@ lombok provided + + net.sf.ehcache + ehcache-core + 2.6.11 + provided + org.ehcache ehcache diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java new file mode 100644 index 00000000..f86c0ed8 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java @@ -0,0 +1,83 @@ +package org.apache.shiro.biz.cache.ehcache; + +import java.io.Serializable; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration.Consistency; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; + +/** + * Credential retry state backed by Ehcache 2 key locks. Shared deployments require + * a strongly consistent Terracotta region. + * + * @param serializable key used by the cache + */ +public final class Ehcache2CredentialRetryStore implements CredentialRetryStore { + + private final Ehcache cache; + private final Function principalKey; + + /** + * @param cache dedicated retry region with the application's TTL and TTI + * @param principalKey consistent principal key encoding for all callers sharing the cache + */ + public Ehcache2CredentialRetryStore(Ehcache cache, Function principalKey) { + this.cache = Objects.requireNonNull(cache, "cache"); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + CacheConfiguration configuration = cache.getCacheConfiguration(); + if (configuration.isTerracottaClustered() && configuration.getTerracottaConsistency() != Consistency.STRONG) { + throw new IllegalArgumentException("Clustered retry cache must use strong consistency"); + } + } + + @Override + public Attempt reserve(Object principal) { + K key = key(principal); + cache.acquireWriteLockOnKey(key); + try { + Element entry = cache.get(key); + if (Objects.isNull(entry)) { + Attempt initial = new Attempt(UUID.randomUUID().toString(), 1); + cache.put(new Element(key, initial)); + return initial; + } + + Attempt current = (Attempt) entry.getObjectValue(); + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } + + Attempt next = new Attempt(current.getWindowId(), current.getCount() + 1); + // The replacement keeps the original TTL origin and counts this read as idle activity. + cache.put(new Element(key, next, entry.getVersion(), entry.getCreationTime(), + entry.getLastAccessTime(), 0L, false, entry.getTimeToLive(), entry.getTimeToIdle(), + entry.getLastUpdateTime())); + return next; + } finally { + cache.releaseWriteLockOnKey(key); + } + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + K key = key(principal); + Objects.requireNonNull(windowId, "windowId"); + cache.acquireWriteLockOnKey(key); + try { + Element entry = cache.getQuiet(key); + if (Objects.nonNull(entry) && windowId.equals(((Attempt) entry.getObjectValue()).getWindowId())) { + cache.remove(key); + } + } finally { + cache.releaseWriteLockOnKey(key); + } + } + + private K key(Object principal) { + return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..2d544f03 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,127 @@ +package org.apache.shiro.biz.cache.ehcache; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.Configuration; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.After; +import org.junit.Test; + +public class Ehcache2CredentialRetryStoreIntegrationTest { + + private final CacheManager manager = CacheManager.newInstance(new Configuration()); + + @After + public void closeCache() { + manager.shutdown(); + } + + @Test + public void storesShareAtomicCountsThroughCopyOnReadCache() throws Exception { + Cache cache = cache(0, 0); + Ehcache2CredentialRetryStore first = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + Ehcache2CredentialRetryStore second = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + ExecutorService workers = Executors.newFixedThreadPool(8); + CountDownLatch start = new CountDownLatch(1); + try { + List> pending = new ArrayList<>(); + for (int i = 0; i < 64; i++) { + Ehcache2CredentialRetryStore store = i % 2 == 0 ? first : second; + pending.add(workers.submit(() -> { + start.await(); + return store.reserve("principal"); + })); + } + start.countDown(); + String windowId = pending.get(0).get(10, TimeUnit.SECONDS).getWindowId(); + Set counts = new HashSet<>(); + for (Future future : pending) { + Attempt attempt = future.get(10, TimeUnit.SECONDS); + assertEquals(windowId, attempt.getWindowId()); + counts.add(attempt.getCount()); + } + assertEquals(64, counts.size()); + assertTrue(counts.contains(1)); + assertTrue(counts.contains(64)); + + first.clearIfCurrent("principal", windowId); + Attempt next = second.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(windowId, next.getWindowId()); + first.clearIfCurrent("principal", windowId); + assertEquals(2, second.reserve("principal").getCount()); + } finally { + workers.shutdownNow(); + } + } + + @Test + public void incrementsPreserveCreationDeadlineAndRefreshConfiguredIdlePeriod() throws Exception { + Cache cache = cache(30, 10); + Ehcache2CredentialRetryStore store = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + + long created = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); + Element existing = new Element("principal", new Attempt("first", 1), 1, created, created, 0, + false, 30, 10, created); + cache.put(existing); + Element before = cache.getQuiet("principal"); + Thread.sleep(20); + assertEquals(2, store.reserve("principal").getCount()); + Element after = cache.getQuiet("principal"); + assertEquals(created, after.getCreationTime()); + assertEquals(30, after.getTimeToLive()); + assertEquals(10, after.getTimeToIdle()); + assertTrue(after.getLastAccessTime() > before.getLastAccessTime()); + + long closeToDeadline = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(29); + cache.put(new Element("ending", new Attempt("ending", 1), 1, closeToDeadline, closeToDeadline, 0, + false, 30, 10, closeToDeadline)); + assertEquals(2, store.reserve("ending").getCount()); + assertEquals(closeToDeadline + TimeUnit.SECONDS.toMillis(30), cache.getQuiet("ending").getExpirationTime()); + } + + @Test + public void idleOnlyWindowExpiresAndStaleResetDoesNotRefreshIt() throws Exception { + Cache cache = cache(0, 1); + Ehcache2CredentialRetryStore store = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + Attempt first = store.reserve("principal"); + long expiry = cache.getQuiet("principal").getExpirationTime(); + store.clearIfCurrent("principal", "stale"); + assertEquals(expiry, cache.getQuiet("principal").getExpirationTime()); + + long timeout = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.currentTimeMillis() <= expiry && System.nanoTime() < timeout) { + Thread.sleep(10); + } + assertNull(cache.getQuiet("principal")); + Attempt next = store.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(first.getWindowId(), next.getWindowId()); + } + + private Cache cache(int ttl, int tti) { + Cache cache = new Cache(new CacheConfiguration("retry-state", 100) + .timeToLiveSeconds(ttl) + .timeToIdleSeconds(tti) + .copyOnRead(true) + .copyOnWrite(true)); + manager.addCache(cache); + return cache; + } +} From 129af846510e353c5406adaceb2f655f57ee92c0 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:51:34 +0800 Subject: [PATCH 10/50] Preserve native Hazelcast retry window across atomic updates --- shiro-extension-core/pom.xml | 4 +- .../HazelcastCredentialRetryStore.java | 111 ++++++++++++ ...stCredentialRetryStoreIntegrationTest.java | 165 ++++++++++++++++++ ...heCredentialRetryStoreIntegrationTest.java | 7 +- 4 files changed, 282 insertions(+), 5 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index f63b6a02..86e16bae 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -95,8 +95,8 @@ com.hazelcast hazelcast - 3.12.13 - test + 5.3.7 + provided junit diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java new file mode 100644 index 00000000..0aa53159 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java @@ -0,0 +1,111 @@ +package org.apache.shiro.biz.cache.hazelcast; + +import com.hazelcast.core.EntryView; +import com.hazelcast.map.EntryProcessor; +import com.hazelcast.map.ExtendedMapEntry; +import com.hazelcast.map.IMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; + +/** + * Shared retry state in a dedicated Hazelcast 5.2+ IMap. The partition owner + * reserves an attempt atomically, using the map's TTL and max-idle policy. + * + * @param cache key type + */ +public final class HazelcastCredentialRetryStore implements CredentialRetryStore { + + private static final int MAX_CONFLICTS = 128; + + private final IMap map; + private final Function principalKey; + + /** + * @param map dedicated retry map. Cluster members must have this module on their classpath. + * @param principalKey consistent principal key encoding for all callers sharing the map + */ + public HazelcastCredentialRetryStore(IMap map, Function principalKey) { + this.map = Objects.requireNonNull(map, "map"); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + } + + @Override + public Attempt reserve(Object principal) { + return map.executeOnKey(key(principal), new Reserve<>(UUID.randomUUID().toString())); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + K key = key(principal); + Objects.requireNonNull(windowId, "windowId"); + for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { + EntryView entry = map.getEntryView(key); + if (Objects.isNull(entry) || !windowId.equals(entry.getValue().getWindowId()) + || map.remove(key, entry.getValue())) { + return; + } + } + throw new CacheException("Unable to clear credential retry state within the conflict limit"); + } + + private K key(Object principal) { + return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + } + + private static final class Reserve implements EntryProcessor { + + private static final long serialVersionUID = 1L; + + private final String initialWindowId; + private transient Attempt updated; + + private Reserve(String initialWindowId) { + this.initialWindowId = initialWindowId; + } + + @Override + public Attempt process(Map.Entry entry) { + updated = null; + Attempt current = entry.getValue(); + if (Objects.isNull(current)) { + updated = new Attempt(initialWindowId, 1); + } else if (current.getCount() == Integer.MAX_VALUE) { + return current; + } else { + updated = new Attempt(current.getWindowId(), current.getCount() + 1); + } + ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(updated); + return updated; + } + + @Override + public EntryProcessor getBackupProcessor() { + if (Objects.isNull(updated)) { + return null; + } + // Replicate the primary's result even if the backup entry was absent. + return new CopyReservation<>(updated); + } + } + + private static final class CopyReservation implements EntryProcessor { + + private static final long serialVersionUID = 1L; + + private final Attempt attempt; + + private CopyReservation(Attempt attempt) { + this.attempt = attempt; + } + + @Override + public Attempt process(Map.Entry entry) { + ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(attempt); + return attempt; + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..c1e8f67a --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,165 @@ +package org.apache.shiro.biz.cache.hazelcast; + +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.EntryView; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.map.IMap; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class HazelcastCredentialRetryStoreIntegrationTest { + + private static HazelcastInstance first; + private static HazelcastInstance second; + + @BeforeClass + public static void startCluster() throws IOException { + String cluster = "shiro-map-" + UUID.randomUUID(); + int firstPort; + int secondPort; + try (ServerSocket a = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); + ServerSocket b = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + firstPort = a.getLocalPort(); + secondPort = b.getLocalPort(); + } + first = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); + second = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); + assertEquals(2, first.getCluster().getMembers().size()); + } + + @AfterClass + public static void stopCluster() { + if (second != null) { + second.getLifecycleService().terminate(); + } + if (first != null) { + first.getLifecycleService().terminate(); + } + } + + @Test + public void reservesUniqueCountsAcrossMembersAndSaturates() throws Exception { + IMap map = first.getMap("atomic"); + HazelcastCredentialRetryStore firstStore = new HazelcastCredentialRetryStore<>(map, Object::toString); + HazelcastCredentialRetryStore secondStore = store(second, "atomic"); + ExecutorService workers = Executors.newFixedThreadPool(6); + try { + List> attempts = new ArrayList<>(); + for (int i = 0; i < 48; i++) { + HazelcastCredentialRetryStore selected = i % 2 == 0 ? firstStore : secondStore; + attempts.add(() -> selected.reserve("principal")); + } + Set windows = new HashSet<>(); + Set counts = new HashSet<>(); + for (Future result : workers.invokeAll(attempts, 10, TimeUnit.SECONDS)) { + Attempt attempt = result.get(); + windows.add(attempt.getWindowId()); + assertTrue(counts.add(attempt.getCount())); + } + assertEquals(1, windows.size()); + assertEquals(48, counts.size()); + assertEquals(48, map.get("principal").getCount()); + map.put("principal", new Attempt(windows.iterator().next(), Integer.MAX_VALUE)); + assertEquals(Integer.MAX_VALUE, secondStore.reserve("principal").getCount()); + } finally { + workers.shutdownNow(); + } + } + + @Test + public void incrementsRetainOriginalTtlAndStaleClearPreservesNewWindow() throws Exception { + IMap map = first.getMap("ttl"); + HazelcastCredentialRetryStore firstStore = store(first, "ttl"); + HazelcastCredentialRetryStore secondStore = store(second, "ttl"); + + Attempt initial = firstStore.reserve("principal"); + long originalDeadline = map.getEntryView("principal").getExpirationTime(); + awaitDeadline(originalDeadline - 1500); + assertEquals(2, secondStore.reserve("principal").getCount()); + assertEquals(originalDeadline, map.getEntryView("principal").getExpirationTime()); + awaitDeadline(originalDeadline + 100); + + Attempt renewed = secondStore.reserve("principal"); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + firstStore.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, secondStore.reserve("principal").getCount()); + firstStore.clearIfCurrent("principal", renewed.getWindowId()); + assertNull(map.getEntryView("principal")); + } + + @Test + public void reservationRefreshesIdleTimeAndStaleClearKeepsTheIdleDeadline() throws Exception { + IMap map = first.getMap("idle"); + HazelcastCredentialRetryStore firstStore = store(first, "idle"); + HazelcastCredentialRetryStore secondStore = store(second, "idle"); + + Attempt initial = firstStore.reserve("principal"); + long creationDeadline = map.getEntryView("principal").getExpirationTime(); + awaitDeadline(creationDeadline - 1000); + assertEquals(2, secondStore.reserve("principal").getCount()); + EntryView accessed = map.getEntryView("principal"); + assertTrue(accessed.getExpirationTime() > creationDeadline); + firstStore.clearIfCurrent("principal", "stale"); + assertEquals(accessed.getExpirationTime(), map.getEntryView("principal").getExpirationTime()); + + awaitDeadline(accessed.getExpirationTime() + 100); + Attempt next = secondStore.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + } + + private static HazelcastCredentialRetryStore store(HazelcastInstance member, String name) { + return new HazelcastCredentialRetryStore<>(member.getMap(name), Object::toString); + } + + private static void awaitDeadline(long deadline) throws InterruptedException { + long remaining = deadline - System.currentTimeMillis(); + if (remaining > 0) { + Thread.sleep(remaining); + } + } + + private static Config member(String cluster, int ownPort, int otherPort) { + Config config = new Config().setClusterName(cluster); + config.setProperty("hazelcast.logging.type", "none"); + config.setProperty("hazelcast.operation.thread.count", "2"); + config.setProperty("hazelcast.operation.generic.thread.count", "2"); + config.setProperty("hazelcast.io.thread.count", "2"); + config.setProperty("hazelcast.event.thread.count", "2"); + config.setProperty("hazelcast.wait.seconds.before.join", "0"); + config.setProperty("hazelcast.socket.bind.any", "false"); + config.addMapConfig(new MapConfig("ttl").setTimeToLiveSeconds(3).setMaxIdleSeconds(10)); + config.addMapConfig(new MapConfig("idle").setMaxIdleSeconds(2)); + NetworkConfig network = config.getNetworkConfig(); + network.setPort(ownPort).setPortAutoIncrement(false); + network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + network.getJoin().getAutoDetectionConfig().setEnabled(false); + network.getJoin().getMulticastConfig().setEnabled(false); + network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + return config; + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index 1870827c..5af4a109 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -58,8 +58,8 @@ public static void startCluster() throws IOException { firstMember = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); secondMember = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); assertEquals(2, firstMember.getCluster().getMembers().size()); - firstManager = HazelcastServerCachingProvider.createCachingProvider(firstMember).getCacheManager(); - secondManager = HazelcastServerCachingProvider.createCachingProvider(secondMember).getCacheManager(); + firstManager = new HazelcastServerCachingProvider(firstMember).getCacheManager(); + secondManager = new HazelcastServerCachingProvider(secondMember).getCacheManager(); } @AfterClass @@ -148,7 +148,7 @@ private static Cache createCache(String name, Factory Date: Wed, 18 Nov 2026 18:57:24 +0800 Subject: [PATCH 11/50] Preserve Redisson retry TTL and idle expiry across clients --- .github/workflows/main-ci.yml | 5 +- shiro-extension-core/pom.xml | 6 + .../redis/RedisCredentialRetryStore.java | 84 ++++++++-- .../RedissonCredentialRetryStore.java | 45 ++++++ ...onCredentialRetryStoreIntegrationTest.java | 149 ++++++++++++++++++ 5 files changed, 274 insertions(+), 15 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 44ef302f..64ab7470 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -13,6 +13,8 @@ jobs: services: redis: image: redis:8.4.0 + ports: + - 6379/tcp options: >- --health-cmd "redis-cli ping" --health-interval 5s @@ -35,7 +37,8 @@ jobs: - name: Verify Shiro extension env: RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }} - run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" clean verify + RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} + run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redisson.test.port="${RETRY_REDIS_PORT}" clean verify - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index 86e16bae..4e4fc9eb 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -92,6 +92,12 @@ 1.1.1 provided + + org.redisson + redisson + 3.12.5 + provided + com.hazelcast hazelcast diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java index b2df2382..124b5498 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -14,17 +14,46 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { private static final String RESERVE = """ - local window = redis.call('HGET', KEYS[1], 'window') + local key = KEYS[1] + local window = redis.call('HGET', key, 'window') + local idle = ARGV[3] + if window then + idle = redis.call('HGET', key, 'idleMillis') + end + local idleDeadline + local ttlDeadline = '0' + if idle and idle ~= '0' then + redis.replicate_commands() + local time = redis.call('TIME') + local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) + idleDeadline = now + tonumber(idle) + if window then + ttlDeadline = redis.call('HGET', key, 'ttlDeadline') + elseif ARGV[2] ~= '0' then + ttlDeadline = string.format('%.0f', now + tonumber(ARGV[2])) + end + if ttlDeadline ~= '0' then + idleDeadline = math.min(idleDeadline, tonumber(ttlDeadline)) + end + end + local count if not window then - redis.call('HSET', KEYS[1], 'window', ARGV[1], 'count', 1) - if ARGV[2] ~= '0' then - redis.call('PEXPIRE', KEYS[1], ARGV[2]) + window = ARGV[1] + count = 1 + redis.call('HSET', key, 'window', window, 'count', count) + if idleDeadline then + redis.call('HSET', key, 'idleMillis', idle, 'ttlDeadline', ttlDeadline) + elseif ARGV[2] ~= '0' then + redis.call('PEXPIRE', key, ARGV[2]) + end + else + count = redis.call('HGET', key, 'count') + if tonumber(count) < 2147483647 then + count = redis.call('HINCRBY', key, 'count', 1) end - return ARGV[1] .. ':1' end - local count = redis.call('HGET', KEYS[1], 'count') - if tonumber(count) < 2147483647 then - count = redis.call('HINCRBY', KEYS[1], 'count', 1) + if idleDeadline then + redis.call('PEXPIREAT', key, string.format('%.0f', idleDeadline)) end return window .. ':' .. count """; @@ -40,6 +69,7 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { private final String namespace; private final Function principalKey; private final String expiryMillis; + private final String idleMillis; /** * @param executor Redis client operation for scripts returning a UTF-8 bulk string @@ -49,21 +79,47 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { */ public RedisCredentialRetryStore(ScriptExecutor executor, String namespace, Function principalKey, Duration expiry) { + this(executor, namespace, principalKey, expiry, Duration.ZERO); + } + + /** + * @param executor Redis client operation for scripts returning a UTF-8 bulk string + * @param namespace dedicated retry hash namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param expiry maximum lifetime of a new window, or zero for no lifetime limit + * @param maxIdle idle period refreshed by a reservation, or zero for no idle limit + */ + public RedisCredentialRetryStore(ScriptExecutor executor, String namespace, + Function principalKey, Duration expiry, Duration maxIdle) { this.executor = Objects.requireNonNull(executor, "executor"); this.namespace = Objects.requireNonNull(namespace, "namespace"); this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); - Objects.requireNonNull(expiry, "expiry"); - long millis = expiry.toMillis(); - if (namespace.isBlank() || expiry.isNegative() || (millis == 0 && !expiry.isZero())) { - throw new IllegalArgumentException("Retry state requires a namespace and a nonnegative millisecond expiry"); + if (namespace.isBlank()) { + throw new IllegalArgumentException("Retry state requires a namespace"); + } + long ttl = toMillis(expiry, "expiry"); + long idle = toMillis(maxIdle, "maxIdle"); + // Allow room for the current epoch time while keeping Lua arithmetic exact. + if (idle > 0 && (ttl > (1L << 52) || idle > (1L << 52))) { + throw new IllegalArgumentException("Retry duration is too large for an idle expiry policy"); + } + this.expiryMillis = Long.toString(ttl); + this.idleMillis = Long.toString(idle); + } + + private static long toMillis(Duration duration, String name) { + Objects.requireNonNull(duration, name); + long millis = duration.toMillis(); + if (duration.isNegative() || (millis == 0 && !duration.isZero())) { + throw new IllegalArgumentException(name + " must be zero or a positive millisecond duration"); } - this.expiryMillis = Long.toString(millis); + return millis; } @Override public Attempt reserve(Object principal) { String result = executor.eval(RESERVE, List.of(key(principal)), - List.of(UUID.randomUUID().toString(), expiryMillis)); + List.of(UUID.randomUUID().toString(), expiryMillis, idleMillis)); int separator = result.lastIndexOf(':'); if (separator < 1) { throw new IllegalStateException("Unexpected Redis retry reservation response"); diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java new file mode 100644 index 00000000..291989ac --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java @@ -0,0 +1,45 @@ +package org.apache.shiro.biz.cache.redisson; + +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.redisson.api.RScript; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.StringCodec; + +/** + * Shared retry state using Redisson's Redis connection and the configured TTL and idle period. + */ +public final class RedissonCredentialRetryStore implements CredentialRetryStore { + + private final RedisCredentialRetryStore delegate; + + /** + * @param client the configured Redisson client + * @param namespace dedicated retry namespace shared by all clients + * @param principalKey stable principal encoding shared by all clients + * @param ttl configured maximum lifetime, or zero for no TTL + * @param maxIdle configured idle timeout, or zero for no idle timeout + */ + public RedissonCredentialRetryStore(RedissonClient client, String namespace, + Function principalKey, Duration ttl, Duration maxIdle) { + RScript scripts = Objects.requireNonNull(client, "client").getScript(StringCodec.INSTANCE); + this.delegate = new RedisCredentialRetryStore( + (script, keys, args) -> scripts.eval(keys.get(0), RScript.Mode.READ_WRITE, script, + RScript.ReturnType.VALUE, List.copyOf(keys), args.toArray()), + namespace, principalKey, ttl, maxIdle); + } + + @Override + public Attempt reserve(Object principal) { + return delegate.reserve(principal); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + delegate.clearIfCurrent(principal, windowId); + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..ff7ce3dd --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,149 @@ +package org.apache.shiro.biz.cache.redisson; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.redisson.Redisson; +import org.redisson.api.RScript; +import org.redisson.api.RedissonClient; +import org.redisson.client.codec.StringCodec; +import org.redisson.config.Config; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class RedissonCredentialRetryStoreIntegrationTest { + + private static RedissonClient firstClient; + private static RedissonClient secondClient; + + private final String namespace = "test:redisson-retry:" + UUID.randomUUID(); + + @BeforeClass + public static void connectTwoClients() { + String port = System.getProperty("shiro.redisson.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + firstClient = client(port); + secondClient = client(port); + } + + @AfterClass + public static void disconnectClients() { + if (Objects.nonNull(secondClient)) { + secondClient.shutdown(); + } + if (Objects.nonNull(firstClient)) { + firstClient.shutdown(); + } + } + + @Test + public void independentClientsReserveUniqueCountsAndPreserveTtl() throws Exception { + RedissonCredentialRetryStore first = store(firstClient, Duration.ofSeconds(15), Duration.ZERO); + RedissonCredentialRetryStore second = store(secondClient, Duration.ofSeconds(15), Duration.ZERO); + Attempt initial = first.reserve("principal"); + long deadline = deadline(); + ExecutorService workers = Executors.newFixedThreadPool(6); + try { + List> requests = new ArrayList<>(); + for (int i = 0; i < 32; i++) { + RedissonCredentialRetryStore selected = i % 2 == 0 ? first : second; + requests.add(() -> selected.reserve("principal")); + } + Set counts = new HashSet<>(); + for (Future result : workers.invokeAll(requests, 10, TimeUnit.SECONDS)) { + Attempt attempt = result.get(); + assertEquals(initial.getWindowId(), attempt.getWindowId()); + assertTrue(counts.add(attempt.getCount())); + } + for (int count = 2; count <= 33; count++) { + assertTrue(counts.contains(count)); + } + assertEquals(deadline, deadline()); + first.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(-2L, deadline()); + } finally { + workers.shutdownNow(); + } + } + + @Test + public void idleRefreshIsCappedByTtlAndStaleClearDoesNotRefreshIt() throws Exception { + RedissonCredentialRetryStore first = store(firstClient, Duration.ofMillis(3000), Duration.ofMillis(2300)); + RedissonCredentialRetryStore second = store(secondClient, Duration.ofMillis(3000), Duration.ofMillis(2300)); + Attempt initial = first.reserve("principal"); + long idleDeadline = deadline(); + awaitDeadline(idleDeadline - 1250); + + assertEquals(2, second.reserve("principal").getCount()); + long cappedDeadline = deadline(); + assertEquals(700, cappedDeadline - idleDeadline); + first.clearIfCurrent("principal", "stale"); + assertEquals(cappedDeadline, deadline()); + + awaitDeadline(cappedDeadline + 50); + Attempt next = second.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + first.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, second.reserve("principal").getCount()); + } + + @Test + public void idleOnlyWindowExpiresAndZeroPoliciesStayPersistent() throws Exception { + RedissonCredentialRetryStore idleOnly = store(firstClient, Duration.ZERO, Duration.ofMillis(1200)); + Attempt initial = idleOnly.reserve("principal"); + long deadline = deadline(); + awaitDeadline(deadline - 600); + assertEquals(2, idleOnly.reserve("principal").getCount()); + assertTrue(deadline() > deadline); + awaitDeadline(deadline() + 50); + assertEquals(-2L, deadline()); + + RedissonCredentialRetryStore persistent = store(secondClient, Duration.ZERO, Duration.ZERO); + Attempt next = persistent.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + assertEquals(-1L, deadline()); + } + + private RedissonCredentialRetryStore store(RedissonClient client, Duration ttl, Duration idle) { + return new RedissonCredentialRetryStore(client, namespace, Object::toString, ttl, idle); + } + + private long deadline() { + return firstClient.getScript(StringCodec.INSTANCE).eval(RScript.Mode.READ_WRITE, + "return redis.call('PEXPIRETIME', KEYS[1])", + RScript.ReturnType.INTEGER, List.of(namespace + ":principal")); + } + + private static void awaitDeadline(long deadline) throws InterruptedException { + long millis = deadline - System.currentTimeMillis(); + if (millis > 0) { + Thread.sleep(millis); + } + } + + private static RedissonClient client(String port) { + Config config = new Config().setCodec(StringCodec.INSTANCE).setThreads(2).setNettyThreads(2); + config.useSingleServer().setAddress("redis://127.0.0.1:" + port) + .setConnectionMinimumIdleSize(1).setConnectionPoolSize(4) + .setSubscriptionConnectionMinimumIdleSize(1).setSubscriptionConnectionPoolSize(2); + return Redisson.create(config); + } +} From 17161554fd3f5ae4a2fe8d16e4ecf971385eff62 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:03:26 +0800 Subject: [PATCH 12/50] Use J2Cache Jedis for atomic credential retry windows --- .github/workflows/main-ci.yml | 2 +- shiro-extension-core/pom.xml | 6 + .../J2CacheRedisCredentialRetryStore.java | 113 +++++++++++++++++ ...isCredentialRetryStoreIntegrationTest.java | 120 ++++++++++++++++++ ...onCredentialRetryStoreIntegrationTest.java | 2 +- 5 files changed, 241 insertions(+), 2 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 64ab7470..8ed9de0f 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -38,7 +38,7 @@ jobs: env: RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }} RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} - run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redisson.test.port="${RETRY_REDIS_PORT}" clean verify + run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" clean verify - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index 4e4fc9eb..edf7b842 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -92,6 +92,12 @@ 1.1.1 provided + + net.oschina.j2cache + j2cache-core + 2.8.5-release + provided + org.redisson redisson diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java new file mode 100644 index 00000000..a950e508 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java @@ -0,0 +1,113 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.redis.ReadonlyRedisCacheProvider; +import net.oschina.j2cache.redis.RedisCacheProvider; +import net.oschina.j2cache.redis.RedisClient; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.apache.shiro.cache.CacheException; +import redis.clients.jedis.BinaryJedisCommands; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.ShardedJedis; + +/** + * Credential retry state in the Redis second-level store of a J2Cache channel. + * Reservations go directly to Redis so each application observes the shared count. + */ +public final class J2CacheRedisCredentialRetryStore implements CredentialRetryStore { + + private final RedisCredentialRetryStore delegate; + + /** + * @param channel channel using the writable Jedis provider + * @param config the configuration used to create the channel + * @param region existing retry region whose expiry policy is reused + * @param namespace dedicated retry namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + */ + public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, + String namespace, Function principalKey) { + RedisCacheProvider provider = writableProvider(channel); + if ("cluster".equals(config.getL2CacheProperties().getProperty("mode"))) { + throw new IllegalArgumentException("J2Cache Cluster mode requires its native JedisCluster script client"); + } + RedisClient client = provider.getRedisClient(); + this.delegate = new RedisCredentialRetryStore( + (script, keys, args) -> eval(client, script, keys, args), + namespace, principalKey, expiry(channel, config, region)); + } + + /** + * @param channel channel using the writable Jedis Cluster provider + * @param config the configuration used to create the channel + * @param region existing retry region whose expiry policy is reused + * @param namespace dedicated retry namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param cluster caller-managed script client connected to the same Redis cluster + */ + public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, + String namespace, Function principalKey, + JedisCluster cluster) { + writableProvider(channel); + Objects.requireNonNull(cluster, "cluster"); + this.delegate = new RedisCredentialRetryStore( + (script, keys, args) -> (String) cluster.eval(script, keys, args), + namespace, principalKey, expiry(channel, config, region)); + } + + @Override + public Attempt reserve(Object principal) { + return delegate.reserve(principal); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + delegate.clearIfCurrent(principal, windowId); + } + + private static RedisCacheProvider writableProvider(CacheChannel channel) { + if (channel.getL2Provider() instanceof RedisCacheProvider provider + && !(provider instanceof ReadonlyRedisCacheProvider)) { + return provider; + } + throw new IllegalArgumentException("J2Cache retry state requires a writable Jedis provider"); + } + + private static Duration expiry(CacheChannel channel, J2CacheConfig config, String region) { + if (!config.isSyncTtlToRedis() + || "hash".equalsIgnoreCase(config.getL2CacheProperties().getProperty("storage"))) { + return Duration.ZERO; + } + // Resolve the region through the channel so defaults and its existing listener are applied. + channel.check(region, "__shiro_retry_region_probe__" + UUID.randomUUID()); + long seconds = channel.regions().stream() + .filter(candidate -> region.equals(candidate.getName())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("J2Cache retry region TTL is unavailable")) + .getTtl(); + return Duration.ofSeconds(Math.max(0L, seconds)); + } + + private static String eval(RedisClient client, String script, List keys, List args) { + try { + BinaryJedisCommands connection = client.get(); + if (connection instanceof Jedis jedis) { + return (String) jedis.eval(script, keys, args); + } + if (connection instanceof ShardedJedis sharded) { + return (String) sharded.getShard(keys.get(0)).eval(script, keys, args); + } + throw new CacheException("The J2Cache Redis connection does not expose script execution"); + } finally { + client.release(); + } + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..4c267d6b --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,120 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.CacheProviderHolder; +import net.oschina.j2cache.J2CacheConfig; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.Jedis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class J2CacheRedisCredentialRetryStoreIntegrationTest { + + private static final String REGION = "credential-retry"; + private final String namespace = "test:j2cache-retry:" + UUID.randomUUID(); + private int port; + + @Before + public void requireIsolatedRedis() { + String configured = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(configured)); + port = Integer.parseInt(configured); + } + + @Test + public void twoChannelsShareCountsAndPreserveTheSyncedRegionDeadline() throws Exception { + J2CacheConfig config = config(true, "generic"); + try (CacheChannel first = open(config); CacheChannel second = open(config); + Jedis redis = new Jedis("127.0.0.1", port)) { + var a = store(first, config); + var b = store(second, config); + Attempt initial = a.reserve("principal"); + long deadline = expiry(redis); + assertTrue(deadline > 0L); + assertTrue(redis.pttl(key()) <= 2_000L); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + var left = workers.submit(() -> a.reserve("principal")); + var right = workers.submit(() -> b.reserve("principal")); + Attempt secondAttempt = left.get(5, TimeUnit.SECONDS); + Attempt thirdAttempt = right.get(5, TimeUnit.SECONDS); + assertEquals(5, secondAttempt.getCount() + thirdAttempt.getCount()); + assertEquals(initial.getWindowId(), secondAttempt.getWindowId()); + assertEquals(initial.getWindowId(), thirdAttempt.getWindowId()); + } finally { + workers.shutdownNow(); + } + assertEquals(deadline, expiry(redis)); + long remaining = deadline - System.currentTimeMillis(); + if (remaining >= 0) { + Thread.sleep(remaining + 40); + } + Attempt next = b.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + a.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, b.reserve("principal").getCount()); + } + } + + @Test + public void retainsPersistenceWhenTtlSyncIsDisabledOrRedisUsesHashStorage() { + try (Jedis redis = new Jedis("127.0.0.1", port)) { + for (J2CacheConfig config : new J2CacheConfig[] {config(false, "generic"), config(true, "hash")}) { + try (CacheChannel channel = open(config)) { + var store = store(channel, config); + Attempt initial = store.reserve("principal"); + assertEquals(-1L, expiry(redis)); + store.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(-2L, expiry(redis)); + } + } + } + } + + private J2CacheRedisCredentialRetryStore store(CacheChannel channel, J2CacheConfig config) { + return new J2CacheRedisCredentialRetryStore(channel, config, REGION, namespace, Object::toString); + } + + private long expiry(Jedis redis) { + return (Long) redis.eval("return redis.call('PEXPIRETIME', KEYS[1])", 1, key()); + } + + private String key() { + return namespace + ":principal"; + } + + private J2CacheConfig config(boolean syncTtl, String storage) { + J2CacheConfig config = new J2CacheConfig(); + config.setL1CacheName("caffeine"); + config.setL2CacheName("redis"); + config.setSyncTtlToRedis(syncTtl); + config.getL1CacheProperties().setProperty("region." + REGION, "100, 2s"); + config.getL2CacheProperties().setProperty("hosts", "127.0.0.1:" + port); + config.getL2CacheProperties().setProperty("namespace", namespace + ":legacy"); + config.getL2CacheProperties().setProperty("storage", storage); + return config; + } + + private static CacheChannel open(J2CacheConfig config) { + return new CacheChannel(config, CacheProviderHolder.init(config, (region, key) -> { })) { + @Override + protected void sendClearCmd(String region) { + } + + @Override + protected void sendEvictCmd(String region, String... keys) { + } + }; + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java index ff7ce3dd..6d820118 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java @@ -36,7 +36,7 @@ public class RedissonCredentialRetryStoreIntegrationTest { @BeforeClass public static void connectTwoClients() { - String port = System.getProperty("shiro.redisson.test.port"); + String port = System.getProperty("shiro.redis.test.port"); assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); firstClient = client(port); secondClient = client(port); From dd5e41220f16c79f6aeedd14c88d348e30e2f502 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:10:46 +0800 Subject: [PATCH 13/50] Add atomic retry windows for J2Cache Lettuce --- shiro-extension-core/pom.xml | 6 + .../J2CacheLettuceCredentialRetryStore.java | 48 +++++++ .../J2CacheRedisCredentialRetryStore.java | 21 +-- .../biz/cache/j2cache/J2CacheRetryExpiry.java | 29 +++++ ...ceCredentialRetryStoreIntegrationTest.java | 121 ++++++++++++++++++ ...isCredentialRetryStoreIntegrationTest.java | 17 +-- .../biz/cache/j2cache/J2CacheTestChannel.java | 34 +++++ 7 files changed, 242 insertions(+), 34 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheTestChannel.java diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index edf7b842..000819a4 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -98,6 +98,12 @@ 2.8.5-release provided + + io.lettuce + lettuce-core + 5.3.7.RELEASE + provided + org.redisson redisson diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java new file mode 100644 index 00000000..ba9ae0cc --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java @@ -0,0 +1,48 @@ +package org.apache.shiro.biz.cache.j2cache; + +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.sync.RedisScriptingCommands; +import java.util.Objects; +import java.util.function.Function; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.lettuce.LettuceCacheProvider; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; + +/** Credential retry state in an existing J2Cache region backed by Lettuce. */ +public final class J2CacheLettuceCredentialRetryStore implements CredentialRetryStore { + + private final RedisCredentialRetryStore delegate; + + /** + * @param channel channel using J2Cache's Lettuce L2 provider + * @param config the configuration used to create the channel + * @param region existing retry region whose expiry policy is reused + * @param namespace dedicated retry namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param commands caller-managed UTF-8 scripting connection to the same Redis database or cluster + */ + public J2CacheLettuceCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, + String namespace, Function principalKey, + RedisScriptingCommands commands) { + if (!(channel.getL2Provider() instanceof LettuceCacheProvider)) { + throw new IllegalArgumentException("J2Cache retry state requires a Lettuce L2 provider"); + } + Objects.requireNonNull(commands, "commands"); + this.delegate = new RedisCredentialRetryStore( + (script, keys, args) -> commands.eval(script, ScriptOutputType.VALUE, + keys.toArray(String[]::new), args.toArray(String[]::new)), + namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "hash")); + } + + @Override + public Attempt reserve(Object principal) { + return delegate.reserve(principal); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + delegate.clearIfCurrent(principal, windowId); + } +} diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java index a950e508..bd50d6fa 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java @@ -1,9 +1,7 @@ package org.apache.shiro.biz.cache.j2cache; -import java.time.Duration; import java.util.List; import java.util.Objects; -import java.util.UUID; import java.util.function.Function; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.J2CacheConfig; @@ -42,7 +40,7 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf RedisClient client = provider.getRedisClient(); this.delegate = new RedisCredentialRetryStore( (script, keys, args) -> eval(client, script, keys, args), - namespace, principalKey, expiry(channel, config, region)); + namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); } /** @@ -60,7 +58,7 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf Objects.requireNonNull(cluster, "cluster"); this.delegate = new RedisCredentialRetryStore( (script, keys, args) -> (String) cluster.eval(script, keys, args), - namespace, principalKey, expiry(channel, config, region)); + namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); } @Override @@ -81,21 +79,6 @@ private static RedisCacheProvider writableProvider(CacheChannel channel) { throw new IllegalArgumentException("J2Cache retry state requires a writable Jedis provider"); } - private static Duration expiry(CacheChannel channel, J2CacheConfig config, String region) { - if (!config.isSyncTtlToRedis() - || "hash".equalsIgnoreCase(config.getL2CacheProperties().getProperty("storage"))) { - return Duration.ZERO; - } - // Resolve the region through the channel so defaults and its existing listener are applied. - channel.check(region, "__shiro_retry_region_probe__" + UUID.randomUUID()); - long seconds = channel.regions().stream() - .filter(candidate -> region.equals(candidate.getName())) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException("J2Cache retry region TTL is unavailable")) - .getTtl(); - return Duration.ofSeconds(Math.max(0L, seconds)); - } - private static String eval(RedisClient client, String script, List keys, List args) { try { BinaryJedisCommands connection = client.get(); diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java new file mode 100644 index 00000000..03685c65 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java @@ -0,0 +1,29 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.time.Duration; +import java.util.UUID; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; + +/** Resolves the Redis L2 expiry J2Cache applies when writing through a region. */ +final class J2CacheRetryExpiry { + + private J2CacheRetryExpiry() { + } + + static Duration resolve(CacheChannel channel, J2CacheConfig config, String region, String defaultStorage) { + String storage = config.getL2CacheProperties().getProperty("storage", defaultStorage); + if (!config.isSyncTtlToRedis() || "hash".equalsIgnoreCase(storage)) { + return Duration.ZERO; + } + + // Resolve the region through the channel so defaults and its existing listener are applied. + channel.check(region, "__shiro_retry_region_probe__" + UUID.randomUUID()); + long seconds = channel.regions().stream() + .filter(candidate -> region.equals(candidate.getName())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("J2Cache retry region TTL is unavailable")) + .getTtl(); + return Duration.ofSeconds(Math.max(0L, seconds)); + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..d7728ad6 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,121 @@ +package org.apache.shiro.biz.cache.j2cache; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class J2CacheLettuceCredentialRetryStoreIntegrationTest { + + private static final String REGION = "credential-retry"; + private final String namespace = "test:j2cache-lettuce-retry:" + UUID.randomUUID(); + private int port; + + @Before + public void requireIsolatedRedis() { + String configured = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(configured)); + port = Integer.parseInt(configured); + } + + @Test + public void independentConnectionsPreserveTheSyncedRegionDeadline() throws Exception { + J2CacheConfig config = config(true, "generic"); + RedisClient client = client(); + try (CacheChannel channel = J2CacheTestChannel.open(config); StatefulRedisConnection first = client.connect(); + StatefulRedisConnection second = client.connect()) { + var a = store(channel, config, first); + var b = store(channel, config, second); + Attempt initial = a.reserve("principal"); + long deadline = expiry(first); + assertTrue(deadline > 0L); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + var left = workers.submit(() -> a.reserve("principal")); + var right = workers.submit(() -> b.reserve("principal")); + Attempt leftAttempt = left.get(5, TimeUnit.SECONDS); + Attempt rightAttempt = right.get(5, TimeUnit.SECONDS); + assertNotEquals(leftAttempt.getCount(), rightAttempt.getCount()); + assertEquals(5, leftAttempt.getCount() + rightAttempt.getCount()); + assertEquals(initial.getWindowId(), leftAttempt.getWindowId()); + assertEquals(initial.getWindowId(), rightAttempt.getWindowId()); + } finally { + workers.shutdownNow(); + } + assertEquals(deadline, expiry(second)); + long remaining = deadline - System.currentTimeMillis(); + if (remaining >= 0) { + Thread.sleep(remaining + 40); + } + Attempt next = b.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + a.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, b.reserve("principal").getCount()); + } finally { + client.shutdown(); + } + } + + @Test + public void disabledSynchronizationAndDefaultHashStorageStayPersistent() { + RedisClient client = client(); + try (StatefulRedisConnection connection = client.connect()) { + for (J2CacheConfig config : new J2CacheConfig[] {config(false, "generic"), config(true, null)}) { + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + var store = store(channel, config, connection); + Attempt initial = store.reserve("principal"); + assertEquals(-1L, expiry(connection)); + store.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(-2L, expiry(connection)); + } + } + } finally { + client.shutdown(); + } + } + + private J2CacheLettuceCredentialRetryStore store(CacheChannel channel, J2CacheConfig config, + StatefulRedisConnection connection) { + return new J2CacheLettuceCredentialRetryStore(channel, config, REGION, namespace, Object::toString, + connection.sync()); + } + + private long expiry(StatefulRedisConnection connection) { + return connection.sync().eval("return redis.call('PEXPIRETIME', KEYS[1])", + ScriptOutputType.INTEGER, namespace + ":principal"); + } + + private RedisClient client() { + return RedisClient.create("redis://127.0.0.1:" + port); + } + + private J2CacheConfig config(boolean syncTtl, String storage) { + J2CacheConfig config = new J2CacheConfig(); + config.setL1CacheName("caffeine"); + config.setL2CacheName("lettuce"); + config.setSyncTtlToRedis(syncTtl); + config.getL1CacheProperties().setProperty("region." + REGION, "100, 2s"); + config.getL2CacheProperties().setProperty("hosts", "127.0.0.1:" + port); + config.getL2CacheProperties().setProperty("password", ""); + config.getL2CacheProperties().setProperty("namespace", namespace + ":legacy"); + if (Objects.nonNull(storage)) { + config.getL2CacheProperties().setProperty("storage", storage); + } + return config; + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java index 4c267d6b..731fc9da 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java @@ -6,7 +6,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.oschina.j2cache.CacheChannel; -import net.oschina.j2cache.CacheProviderHolder; import net.oschina.j2cache.J2CacheConfig; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.Before; @@ -34,7 +33,7 @@ public void requireIsolatedRedis() { @Test public void twoChannelsShareCountsAndPreserveTheSyncedRegionDeadline() throws Exception { J2CacheConfig config = config(true, "generic"); - try (CacheChannel first = open(config); CacheChannel second = open(config); + try (CacheChannel first = J2CacheTestChannel.open(config); CacheChannel second = J2CacheTestChannel.open(config); Jedis redis = new Jedis("127.0.0.1", port)) { var a = store(first, config); var b = store(second, config); @@ -71,7 +70,7 @@ public void twoChannelsShareCountsAndPreserveTheSyncedRegionDeadline() throws Ex public void retainsPersistenceWhenTtlSyncIsDisabledOrRedisUsesHashStorage() { try (Jedis redis = new Jedis("127.0.0.1", port)) { for (J2CacheConfig config : new J2CacheConfig[] {config(false, "generic"), config(true, "hash")}) { - try (CacheChannel channel = open(config)) { + try (CacheChannel channel = J2CacheTestChannel.open(config)) { var store = store(channel, config); Attempt initial = store.reserve("principal"); assertEquals(-1L, expiry(redis)); @@ -105,16 +104,4 @@ private J2CacheConfig config(boolean syncTtl, String storage) { config.getL2CacheProperties().setProperty("storage", storage); return config; } - - private static CacheChannel open(J2CacheConfig config) { - return new CacheChannel(config, CacheProviderHolder.init(config, (region, key) -> { })) { - @Override - protected void sendClearCmd(String region) { - } - - @Override - protected void sendEvictCmd(String region, String... keys) { - } - }; - } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheTestChannel.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheTestChannel.java new file mode 100644 index 00000000..01184034 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheTestChannel.java @@ -0,0 +1,34 @@ +package org.apache.shiro.biz.cache.j2cache; + +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.CacheProviderHolder; +import net.oschina.j2cache.J2CacheConfig; + +/** Starts and closes both providers for an isolated J2Cache test channel. */ +final class J2CacheTestChannel extends CacheChannel { + + private final CacheProviderHolder providers; + + static CacheChannel open(J2CacheConfig config) { + return new J2CacheTestChannel(config, CacheProviderHolder.init(config, (region, key) -> { })); + } + + private J2CacheTestChannel(J2CacheConfig config, CacheProviderHolder providers) { + super(config, providers); + this.providers = providers; + } + + @Override + protected void sendClearCmd(String region) { + } + + @Override + protected void sendEvictCmd(String region, String... keys) { + } + + @Override + public void close() { + super.close(); + providers.shutdown(); + } +} From 780c0538c2e9eef996c0a635927ae6e9dd465f44 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:18:38 +0800 Subject: [PATCH 14/50] Keep J2Cache Memcached retry windows atomic --- .github/workflows/main-ci.yml | 7 +- shiro-extension-core/pom.xml | 6 + .../J2CacheMemcachedCredentialRetryStore.java | 155 ++++++++++++++++++ .../biz/cache/j2cache/J2CacheRetryExpiry.java | 7 +- ...edCredentialRetryStoreIntegrationTest.java | 154 +++++++++++++++++ 5 files changed, 326 insertions(+), 3 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 8ed9de0f..d697c6ca 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -20,6 +20,10 @@ jobs: --health-interval 5s --health-timeout 3s --health-retries 5 + memcached: + image: memcached:1.6.45-alpine + ports: + - 11211/tcp steps: - uses: actions/checkout@v7 - uses: actions/setup-java@v5 @@ -38,7 +42,8 @@ jobs: env: RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }} RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} - run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" clean verify + RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }} + run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" -Dshiro.memcached.test.port="${RETRY_MEMCACHED_PORT}" clean verify - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index 000819a4..3addefc3 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -98,6 +98,12 @@ 2.8.5-release provided + + com.googlecode.xmemcached + xmemcached + 2.4.5 + provided + io.lettuce lettuce-core diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java new file mode 100644 index 00000000..b173a8ac --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -0,0 +1,155 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.memcached.XmemcachedCacheProvider; +import net.rubyeye.xmemcached.GetsResponse; +import net.rubyeye.xmemcached.MemcachedClient; +import net.rubyeye.xmemcached.exception.MemcachedException; +import net.rubyeye.xmemcached.transcoders.StringTranscoder; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; + +/** Credential retry state in the Memcached second level of a J2Cache channel. */ +public final class J2CacheMemcachedCredentialRetryStore implements CredentialRetryStore { + + private static final int MAX_RELATIVE_SECONDS = 30 * 24 * 60 * 60; + private static final int EXPIRED_TIMESTAMP = MAX_RELATIVE_SECONDS + 1; + private static final int MAX_CONFLICTS = 128; + private static final StringTranscoder STRINGS = new StringTranscoder(StandardCharsets.UTF_8.name()); + + private final MemcachedClient client; + private final String keyPrefix; + private final Function principalKey; + private final long regionExpiry; + + /** + * @param channel channel using the xmemcached L2 provider + * @param config configuration used to create the channel, with L2 expiry synchronization enabled + * @param region existing retry region whose expiry policy is reused + * @param namespace dedicated retry namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param client caller-managed client on the same Memcached servers, using the same key routing + */ + public J2CacheMemcachedCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, + String namespace, Function principalKey, + MemcachedClient client) { + if (!(channel.getL2Provider() instanceof XmemcachedCacheProvider) || !config.isSyncTtlToRedis()) { + throw new IllegalArgumentException("Memcached retry state requires an L2 provider with TTL synchronization"); + } + this.client = Objects.requireNonNull(client, "client"); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + this.keyPrefix = "shiro-retry:" + digest(Objects.requireNonNull(namespace, "namespace")) + ":"; + this.regionExpiry = J2CacheRetryExpiry.regionSeconds(channel, region); + if (regionExpiry < 0 || regionExpiry > Integer.MAX_VALUE + || (regionExpiry > MAX_RELATIVE_SECONDS && regionExpiry <= Instant.now().getEpochSecond())) { + throw new IllegalArgumentException("The retry region has an invalid Memcached expiry"); + } + } + + @Override + public Attempt reserve(Object principal) { + String key = key(principal); + try { + for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { + GetsResponse current = client.gets(key, STRINGS); + if (Objects.isNull(current)) { + Window initial = new Window(new Attempt(UUID.randomUUID().toString(), 1), initialDeadline()); + if (client.add(key, initial.expiresAt(), initial.encode(), STRINGS)) { + return initial.attempt(); + } + } else { + Window window = Window.decode(current.getValue()); + Attempt attempt = window.attempt(); + if (attempt.getCount() == Integer.MAX_VALUE) { + return attempt; + } + Window next = new Window(new Attempt(attempt.getWindowId(), attempt.getCount() + 1), + window.expiresAt()); + if (client.cas(key, next.expiresAt(), next.encode(), STRINGS, current.getCas())) { + return next.attempt(); + } + } + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new CacheException("Interrupted while reserving a Memcached retry attempt", exception); + } catch (TimeoutException | MemcachedException exception) { + throw new CacheException("Failed to reserve a Memcached retry attempt", exception); + } + throw new CacheException("Unable to reserve a Memcached retry attempt within the conflict limit"); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + String key = key(principal); + Objects.requireNonNull(windowId, "windowId"); + try { + for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { + GetsResponse current = client.gets(key, STRINGS); + if (Objects.isNull(current) || !windowId.equals(Window.decode(current.getValue()).attempt().getWindowId())) { + return; + } + // A past absolute expiry makes the CAS remove only the version that was read. + if (client.cas(key, EXPIRED_TIMESTAMP, current.getValue(), STRINGS, current.getCas())) { + return; + } + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new CacheException("Interrupted while clearing a Memcached retry window", exception); + } catch (TimeoutException | MemcachedException exception) { + throw new CacheException("Failed to clear a Memcached retry window", exception); + } + throw new CacheException("Unable to clear a Memcached retry window within the conflict limit"); + } + + private int initialDeadline() { + if (regionExpiry == 0) { + return 0; + } + long now = Instant.now().getEpochSecond(); + long expiry = regionExpiry <= MAX_RELATIVE_SECONDS ? now + regionExpiry : regionExpiry; + if (expiry <= now || expiry > Integer.MAX_VALUE) { + throw new CacheException("The retry region's Memcached expiry is out of range"); + } + return (int) expiry; + } + + private String key(Object principal) { + return keyPrefix + digest(Objects.requireNonNull(principalKey.apply(principal), "encoded principal")); + } + + private static String digest(String value) { + try { + byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private record Window(Attempt attempt, int expiresAt) { + + private String encode() { + return expiresAt + ":" + attempt.getCount() + ":" + attempt.getWindowId(); + } + + private static Window decode(String encoded) { + String[] fields = encoded.split(":", 3); + if (fields.length != 3) { + throw new CacheException("Unexpected Memcached retry window format"); + } + return new Window(new Attempt(fields[2], Integer.parseInt(fields[1])), Integer.parseInt(fields[0])); + } + } +} diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java index 03685c65..add9c48c 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java @@ -17,13 +17,16 @@ static Duration resolve(CacheChannel channel, J2CacheConfig config, String regio return Duration.ZERO; } + return Duration.ofSeconds(Math.max(0L, regionSeconds(channel, region))); + } + + static long regionSeconds(CacheChannel channel, String region) { // Resolve the region through the channel so defaults and its existing listener are applied. channel.check(region, "__shiro_retry_region_probe__" + UUID.randomUUID()); - long seconds = channel.regions().stream() + return channel.regions().stream() .filter(candidate -> region.equals(candidate.getName())) .findFirst() .orElseThrow(() -> new IllegalArgumentException("J2Cache retry region TTL is unavailable")) .getTtl(); - return Duration.ofSeconds(Math.max(0L, seconds)); } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..74032028 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,154 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.rubyeye.xmemcached.MemcachedClient; +import net.rubyeye.xmemcached.XMemcachedClientBuilder; +import net.rubyeye.xmemcached.command.BinaryCommandFactory; +import net.rubyeye.xmemcached.utils.AddrUtil; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class J2CacheMemcachedCredentialRetryStoreIntegrationTest { + + private static final String REGION = "credential-retry"; + private final String namespace = "test:memcached-retry:" + UUID.randomUUID(); + private String endpoint; + private MemcachedClient firstClient; + private MemcachedClient secondClient; + + @Before + public void connect() throws Exception { + String port = System.getProperty("shiro.memcached.test.port"); + assumeTrue("Supply an isolated Memcached port", Objects.nonNull(port)); + endpoint = "127.0.0.1:" + port; + firstClient = client(); + secondClient = client(); + } + + @After + public void disconnect() throws Exception { + try { + if (Objects.nonNull(secondClient)) { + secondClient.shutdown(); + } + } finally { + if (Objects.nonNull(firstClient)) { + firstClient.shutdown(); + } + } + } + + @Test + public void reservesUniqueCountsAcrossChannelsAndClearsOnlyTheMatchingWindow() throws Exception { + J2CacheConfig config = config(true, "0s"); + try (CacheChannel first = J2CacheTestChannel.open(config); CacheChannel second = J2CacheTestChannel.open(config)) { + var a = store(first, config, firstClient); + var b = store(second, config, secondClient); + String principal = "shared principal 用户"; + ExecutorService threads = Executors.newFixedThreadPool(8); + try { + List> requests = new ArrayList<>(); + for (int i = 0; i < 48; i++) { + var selected = i % 2 == 0 ? a : b; + requests.add(() -> selected.reserve(principal)); + } + Set counts = new HashSet<>(); + Set windows = new HashSet<>(); + for (Future result : threads.invokeAll(requests, 10, TimeUnit.SECONDS)) { + Attempt attempt = result.get(); + assertTrue(counts.add(attempt.getCount())); + windows.add(attempt.getWindowId()); + } + assertEquals(1, windows.size()); + assertEquals(48, counts.size()); + assertTrue(counts.contains(1)); + assertTrue(counts.contains(48)); + String initial = windows.iterator().next(); + a.clearIfCurrent(principal, initial); + Attempt renewed = b.reserve(principal); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial, renewed.getWindowId()); + a.clearIfCurrent(principal, initial); + assertEquals(2, b.reserve(principal).getCount()); + } finally { + threads.shutdownNow(); + } + } + } + + @Test + public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { + J2CacheConfig config = config(true, "4s"); + try (CacheChannel first = J2CacheTestChannel.open(config); CacheChannel second = J2CacheTestChannel.open(config)) { + var a = store(first, config, firstClient); + var b = store(second, config, secondClient); + + Attempt initial = a.reserve("principal"); + long start = System.nanoTime(); + awaitElapsed(start, 2000); + assertEquals(2, b.reserve("principal").getCount()); + awaitElapsed(start, 4500); + Attempt renewed = a.reserve("principal"); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + } + } + + @Test + public void rejectsConfigurationThatCannotStoreSharedCounters() { + J2CacheConfig config = config(false, "4s"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + assertThrows(IllegalArgumentException.class, () -> store(channel, config, firstClient)); + } + } + + private J2CacheMemcachedCredentialRetryStore store(CacheChannel channel, J2CacheConfig config, + MemcachedClient client) { + return new J2CacheMemcachedCredentialRetryStore(channel, config, REGION, namespace, Object::toString, client); + } + + private J2CacheConfig config(boolean syncTtl, String ttl) { + J2CacheConfig config = new J2CacheConfig(); + config.setL1CacheName("caffeine"); + config.setL2CacheName("memcached"); + config.setSyncTtlToRedis(syncTtl); + config.getL1CacheProperties().setProperty("region." + REGION, "100, " + ttl); + config.getL2CacheProperties().setProperty("servers", endpoint); + config.getL2CacheProperties().setProperty("connectionPoolSize", "1"); + config.getL2CacheProperties().setProperty("opTimeout", "3000"); + return config; + } + + private MemcachedClient client() throws Exception { + var builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(endpoint)); + builder.setCommandFactory(new BinaryCommandFactory()); + return builder.build(); + } + + private static void awaitElapsed(long start, long millis) throws InterruptedException { + long remaining = TimeUnit.MILLISECONDS.toNanos(millis) - (System.nanoTime() - start); + if (remaining > 0) { + TimeUnit.NANOSECONDS.sleep(remaining); + } + } +} From 81c1ae08ba7d5fbcd281e527e7f5054cb7638955 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:25:30 +0800 Subject: [PATCH 15/50] Bind Spring retry caches to atomic provider operations --- .github/workflows/main-ci.yml | 2 + shiro-extension-spring/pom.xml | 35 ++++ .../biz/cache/spring/SpringCacheManager.java | 20 ++ .../SpringDataRedisCredentialRetryStores.java | 57 +++++ .../SpringJCacheCredentialRetryStores.java | 31 +++ ...ngCredentialRetryStoreIntegrationTest.java | 196 ++++++++++++++++++ 6 files changed, 341 insertions(+) create mode 100644 shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java create mode 100644 shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java create mode 100644 shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index d697c6ca..75a6901b 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -50,6 +50,8 @@ jobs: test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/site/jacoco/jacoco.xml test -s shiro-extension-core/target/jacoco.exec test -s shiro-extension-core/target/site/jacoco/jacoco.xml + test -s shiro-extension-spring/target/jacoco.exec + test -s shiro-extension-spring/target/site/jacoco/jacoco.xml - uses: actions/upload-artifact@v7 if: always() with: diff --git a/shiro-extension-spring/pom.xml b/shiro-extension-spring/pom.xml index 65464ac1..13a1849b 100644 --- a/shiro-extension-spring/pom.xml +++ b/shiro-extension-spring/pom.xml @@ -65,5 +65,40 @@ lombok provided + + org.springframework.data + spring-data-redis + 2.7.18 + provided + + + javax.cache + cache-api + 1.1.1 + provided + + + io.lettuce + lettuce-core + 6.1.10.RELEASE + test + + + org.springframework + spring-context-support + ${spring.version} + provided + + + com.hazelcast + hazelcast + 5.3.7 + test + + + junit + junit + test + diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java index e8816257..f9fd3259 100644 --- a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringCacheManager.java @@ -15,12 +15,15 @@ */ package org.apache.shiro.biz.cache.spring; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; /** * Spring CacheManager Wrapper @@ -37,6 +40,23 @@ public SpringCacheManager(org.springframework.cache.CacheManager cacheManager){ this.delegator = cacheManager; } + /** + * Binds a retry store to the named cache through its provider-specific factory. + * + * @param cacheName the Spring cache region whose retry policy is used + * @param providerFactory factory that opens an atomic retry store for the cache provider + * @return the provider-backed retry store + */ + public CredentialRetryStore getCredentialRetryStore( + String cacheName, Function providerFactory) { + Objects.requireNonNull(providerFactory, "providerFactory"); + org.springframework.cache.Cache springCache = delegator.getCache(cacheName); + if (Objects.isNull(springCache)) { + throw new CacheException("Spring retry cache is unavailable: " + cacheName); + } + return Objects.requireNonNull(providerFactory.apply(springCache), "providerStore"); + } + @Override public Cache getCache(String cacheName) throws CacheException { SpringCache cache = this.CACHES.get(cacheName); diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java new file mode 100644 index 00000000..b52711d5 --- /dev/null +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java @@ -0,0 +1,57 @@ +package org.apache.shiro.biz.cache.spring; + +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Stream; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.springframework.cache.Cache; +import org.springframework.cache.transaction.TransactionAwareCacheDecorator; +import org.springframework.data.redis.cache.RedisCache; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** Creates retry stores for Spring Data Redis 2.7 cache regions. */ +public final class SpringDataRedisCredentialRetryStores { + + private static final StringRedisSerializer STRINGS = StringRedisSerializer.UTF_8; + + private SpringDataRedisCredentialRetryStores() { + } + + /** + * Uses the cache's configured TTL and dedicated retry keys in the same Redis database. + * + * @param cache Spring Data Redis cache whose expiry policy is used + * @param connectionFactory connection factory used by that Redis cache + * @param namespace dedicated retry namespace shared by application instances + * @param principalKey stable principal encoding shared by application instances + * @return an atomic Redis retry store + */ + public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey) { + Cache target = cache; + while (target instanceof TransactionAwareCacheDecorator decorator) { + target = decorator.getTargetCache(); + } + if (!(target instanceof RedisCache redisCache)) { + throw new IllegalArgumentException("Spring retry cache must be backed by Spring Data Redis"); + } + Objects.requireNonNull(connectionFactory, "connectionFactory"); + return new RedisCredentialRetryStore( + (script, keys, args) -> eval(connectionFactory, script, keys, args), + namespace, principalKey, redisCache.getCacheConfiguration().getTtl()); + } + + private static String eval(RedisConnectionFactory factory, String script, List keys, List args) { + byte[][] arguments = Stream.concat(keys.stream(), args.stream()).map(STRINGS::serialize).toArray(byte[][]::new); + try (RedisConnection connection = factory.getConnection()) { + byte[] result = connection.scriptingCommands().eval( + STRINGS.serialize(script), ReturnType.VALUE, keys.size(), arguments); + return STRINGS.deserialize(result); + } + } +} diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java new file mode 100644 index 00000000..e6cc0fc7 --- /dev/null +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java @@ -0,0 +1,31 @@ +package org.apache.shiro.biz.cache.spring; + +import javax.cache.configuration.Configuration; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.apache.shiro.biz.cache.jcache.JCacheCredentialRetryStore; +import org.springframework.cache.Cache; + +/** Creates retry stores for Spring cache regions backed by JCache. */ +public final class SpringJCacheCredentialRetryStores { + + private SpringJCacheCredentialRetryStores() { + } + + /** + * @param cache Spring cache exposing a dedicated JCache region for retry attempts + * @return a retry store using the provider's atomic entry processing and expiry + */ + @SuppressWarnings("unchecked") + public static CredentialRetryStore fromCache(Cache cache) { + if (!(cache.getNativeCache() instanceof javax.cache.Cache nativeCache)) { + throw new IllegalArgumentException("Spring retry cache must expose a JCache region"); + } + + Configuration configuration = nativeCache.getConfiguration(Configuration.class); + if (!configuration.getValueType().isAssignableFrom(Attempt.class)) { + throw new IllegalArgumentException("JCache retry region must accept credential retry attempts"); + } + return new JCacheCredentialRetryStore((javax.cache.Cache) nativeCache); + } +} diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..0d8a9cbd --- /dev/null +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,196 @@ +package org.apache.shiro.biz.cache.spring; + +import com.hazelcast.cache.impl.HazelcastServerCachingProvider; +import com.hazelcast.config.Config; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.expiry.EternalExpiryPolicy; +import org.apache.shiro.authc.ExcessiveAttemptsException; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher; +import org.apache.shiro.cache.CacheException; +import org.junit.Test; +import org.springframework.cache.concurrent.ConcurrentMapCache; +import org.springframework.cache.jcache.JCacheCacheManager; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class SpringCredentialRetryStoreIntegrationTest { + + private static final String REGION = "credential-retry"; + private static final StringRedisSerializer UTF_8 = StringRedisSerializer.UTF_8; + + @Test + public void springRedisManagersShareAnAtomicRetryWindowWithTheirConfiguredTtl() throws Exception { + String port = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + String namespace = "test:spring-retry:" + UUID.randomUUID(); + LettuceConnectionFactory first = connectionFactory(port); + LettuceConnectionFactory second = connectionFactory(port); + try { + CredentialRetryStore a = redisStore(first, namespace, false); + CredentialRetryStore b = redisStore(second, namespace, true); + Attempt initial = a.reserve("principal"); + long deadline = expiry(first, namespace); + assertTrue(deadline > System.currentTimeMillis()); + assertTrue(deadline <= System.currentTimeMillis() + 15_000); + + ExecutorService workers = Executors.newFixedThreadPool(6); + try { + List> requests = new ArrayList<>(); + for (int i = 0; i < 24; i++) { + CredentialRetryStore selected = i % 2 == 0 ? a : b; + requests.add(() -> selected.reserve("principal")); + } + Set counts = new HashSet<>(); + for (Future result : workers.invokeAll(requests, 10, TimeUnit.SECONDS)) { + Attempt attempt = result.get(); + assertEquals(initial.getWindowId(), attempt.getWindowId()); + assertTrue(counts.add(attempt.getCount())); + } + assertEquals(24, counts.size()); + assertTrue(counts.contains(2)); + assertTrue(counts.contains(25)); + } finally { + workers.shutdownNow(); + } + assertEquals(deadline, expiry(second, namespace)); + b.clearIfCurrent("principal", initial.getWindowId()); + Attempt renewed = a.reserve("principal"); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + b.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, a.reserve("principal").getCount()); + } finally { + second.destroy(); + first.destroy(); + } + } + + @Test + public void springRedisEnforcesTheRetryLimitAcrossMatcherInstances() { + String port = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + String namespace = "test:spring-matcher:" + UUID.randomUUID(); + LettuceConnectionFactory first = connectionFactory(port); + LettuceConnectionFactory second = connectionFactory(port); + try { + DefaultCredentialsMatcher a = new DefaultCredentialsMatcher(); + a.setRetryLimit(3); + a.setCredentialRetryStore(redisStore(first, namespace, false)); + DefaultCredentialsMatcher b = new DefaultCredentialsMatcher(); + b.setRetryLimit(3); + b.setCredentialRetryStore(redisStore(second, namespace, true)); + + var rejected = new UsernamePasswordToken("principal", "wrong"); + var account = new SimpleAuthenticationInfo("principal", "correct", "realm"); + assertFalse(a.doCredentialsMatch(rejected, account)); + assertFalse(b.doCredentialsMatch(rejected, account)); + assertThrows(ExcessiveAttemptsException.class, () -> a.doCredentialsMatch(rejected, account)); + } finally { + second.destroy(); + first.destroy(); + } + } + + @Test + public void unwrapsSpringJCacheThroughTheShiroCacheManager() { + Config config = new Config().setClusterName("shiro-spring-jcache-" + UUID.randomUUID()); + config.setProperty("hazelcast.logging.type", "none"); + config.setProperty("hazelcast.socket.bind.any", "false"); + config.setProperty("hazelcast.operation.thread.count", "2"); + config.setProperty("hazelcast.operation.generic.thread.count", "2"); + config.setProperty("hazelcast.io.thread.count", "2"); + config.setProperty("hazelcast.event.thread.count", "2"); + config.getNetworkConfig().getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + config.getNetworkConfig().getJoin().getAutoDetectionConfig().setEnabled(false); + config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + HazelcastInstance member = Hazelcast.newHazelcastInstance(config); + try (HazelcastServerCachingProvider provider = new HazelcastServerCachingProvider(member); + javax.cache.CacheManager nativeManager = provider.getCacheManager()) { + nativeManager.createCache(REGION, new MutableConfiguration() + .setTypes(Object.class, Attempt.class) + .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf())); + JCacheCacheManager spring = new JCacheCacheManager(nativeManager); + spring.afterPropertiesSet(); + SpringCacheManager shiro = new SpringCacheManager(spring); + CredentialRetryStore a = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache); + CredentialRetryStore b = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache); + Attempt initial = a.reserve("principal"); + assertEquals(initial.getWindowId(), b.reserve("principal").getWindowId()); + assertEquals(2, nativeManager.getCache(REGION, Object.class, Attempt.class).get("principal").getCount()); + b.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(1, a.reserve("principal").getCount()); + } finally { + member.getLifecycleService().terminate(); + } + } + + @Test + public void reportsMissingRegionsAndRejectsCachesWithoutTheExpectedProvider() { + SimpleCacheManager spring = new SimpleCacheManager(); + spring.setCaches(List.of(new ConcurrentMapCache(REGION))); + spring.afterPropertiesSet(); + SpringCacheManager shiro = new SpringCacheManager(spring); + assertThrows(CacheException.class, + () -> shiro.getCredentialRetryStore("missing", SpringJCacheCredentialRetryStores::fromCache)); + assertThrows(IllegalArgumentException.class, + () -> shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache)); + } + + private static LettuceConnectionFactory connectionFactory(String port) { + LettuceConnectionFactory factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port)); + factory.afterPropertiesSet(); + return factory; + } + + private static CredentialRetryStore redisStore(LettuceConnectionFactory factory, String namespace, + boolean transactionAware) { + var builder = RedisCacheManager.builder(factory) + .withCacheConfiguration(REGION, RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofSeconds(15))); + if (transactionAware) { + builder.transactionAware(); + } + RedisCacheManager spring = builder.build(); + spring.afterPropertiesSet(); + return new SpringCacheManager(spring).getCredentialRetryStore(REGION, + cache -> SpringDataRedisCredentialRetryStores.fromCache(cache, factory, namespace, Object::toString)); + } + + private static long expiry(LettuceConnectionFactory factory, String namespace) { + try (RedisConnection connection = factory.getConnection()) { + return connection.scriptingCommands().eval( + UTF_8.serialize("return redis.call('PEXPIRETIME', KEYS[1])"), + ReturnType.INTEGER, 1, UTF_8.serialize(namespace + ":principal")); + } + } +} From 5ea00c78d30ed8926080084a23fe77c14b4868bd Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:33:27 +0800 Subject: [PATCH 16/50] Support atomic retry windows with native Hazelcast 3.12 --- .github/workflows/main-ci.yml | 2 + pom.xml | 1 + shiro-extension-hazelcast3/pom.xml | 46 +++++ .../Hazelcast3CredentialRetryStore.java | 118 +++++++++++ ...t3CredentialRetryStoreIntegrationTest.java | 191 ++++++++++++++++++ 5 files changed, 358 insertions(+) create mode 100644 shiro-extension-hazelcast3/pom.xml create mode 100644 shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java create mode 100644 shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 75a6901b..9862cf69 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -52,6 +52,8 @@ jobs: test -s shiro-extension-core/target/site/jacoco/jacoco.xml test -s shiro-extension-spring/target/jacoco.exec test -s shiro-extension-spring/target/site/jacoco/jacoco.xml + test -s shiro-extension-hazelcast3/target/jacoco.exec + test -s shiro-extension-hazelcast3/target/site/jacoco/jacoco.xml - uses: actions/upload-artifact@v7 if: always() with: diff --git a/pom.xml b/pom.xml index a9162619..5f3c4d9a 100644 --- a/pom.xml +++ b/pom.xml @@ -643,6 +643,7 @@ shiro-extension-core + shiro-extension-hazelcast3 shiro-extension-spring diff --git a/shiro-extension-hazelcast3/pom.xml b/shiro-extension-hazelcast3/pom.xml new file mode 100644 index 00000000..8ed2933b --- /dev/null +++ b/shiro-extension-hazelcast3/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + + io.github.easy4j + shiro-extension + 2.0.x.20260630-SNAPSHOT + ../pom.xml + + + shiro-extension-hazelcast3 + ${project.groupId}:${project.artifactId} + Credential retry integration for native Hazelcast 3.12 IMap + + + 3.12.13 + + + + + io.github.easy4j + shiro-extension-core + ${revision} + + + com.hazelcast + hazelcast + ${hazelcast3.version} + provided + + + com.hazelcast + hazelcast-client + ${hazelcast3.version} + test + + + junit + junit + test + + + diff --git a/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java b/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java new file mode 100644 index 00000000..1e1fc496 --- /dev/null +++ b/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java @@ -0,0 +1,118 @@ +package org.apache.shiro.biz.cache.hazelcast3; + +import com.hazelcast.core.EntryView; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import java.io.Serializable; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; + +/** + * Shared retry state in a dedicated Hazelcast 3.12 IMap. The map's key lock + * guards each reservation and reset. + * + * @param cache key type + */ +public final class Hazelcast3CredentialRetryStore implements CredentialRetryStore { + + private static final long UNSET_DEADLINE = 0; + private static final long NO_DEADLINE = Long.MAX_VALUE; + + private final IMap map; + private final long maxIdleMillis; + private final Function principalKey; + + /** + * @param hazelcast member or thin client connected to the retry map's cluster + * @param mapName dedicated retry map managed exclusively by this store, with this module on all members + * @param maxIdleSeconds the map's configured max idle. The 3.12 client wire format omits this setting + * @param principalKey stable principal encoding shared by application instances + */ + public Hazelcast3CredentialRetryStore(HazelcastInstance hazelcast, String mapName, int maxIdleSeconds, + Function principalKey) { + if (maxIdleSeconds < 0) { + throw new IllegalArgumentException("The Hazelcast map max idle must be nonnegative"); + } + this.map = Objects.requireNonNull(hazelcast, "hazelcast").getMap(mapName); + this.maxIdleMillis = TimeUnit.SECONDS.toMillis(maxIdleSeconds); + this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + } + + @Override + public Attempt reserve(Object principal) { + K key = key(principal); + map.lock(key); + try { + EntryView entry = map.getEntryView(key); + long now = System.currentTimeMillis(); + if (Objects.isNull(entry)) { + return startWindow(key); + } + long deadline = ttlDeadline(entry); + if (expired(entry, deadline, now)) { + // Hazelcast suspends expiry on locked keys. Reinsert with the map defaults. + map.delete(key); + return startWindow(key); + } + + Attempt current = entry.getValue().attempt(); + Attempt next = current.getCount() == Integer.MAX_VALUE + ? current : new Attempt(current.getWindowId(), current.getCount() + 1); + // Hazelcast 3.12 stores creation, update and TTL metadata at whole-second precision. + long remainingSeconds = deadline == NO_DEADLINE ? 0 + : TimeUnit.MILLISECONDS.toSeconds(deadline) - TimeUnit.MILLISECONDS.toSeconds(now); + map.set(key, new Window(next, deadline), remainingSeconds, TimeUnit.SECONDS); + return next; + } finally { + map.unlock(key); + } + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + K key = key(principal); + Objects.requireNonNull(windowId, "windowId"); + map.lock(key); + try { + EntryView entry = map.getEntryView(key); + if (Objects.nonNull(entry) && windowId.equals(entry.getValue().attempt().getWindowId())) { + map.delete(key); + } + } finally { + map.unlock(key); + } + } + + private Attempt startWindow(K key) { + Attempt initial = new Attempt(UUID.randomUUID().toString(), 1); + map.set(key, new Window(initial, UNSET_DEADLINE)); + return initial; + } + + private K key(Object principal) { + return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + } + + private boolean expired(EntryView entry, long deadline, long now) { + long lastActivity = Math.max(entry.getCreationTime(), entry.getLastAccessTime()); + return deadline <= now || (maxIdleMillis > 0 && now - lastActivity >= maxIdleMillis); + } + + private static long ttlDeadline(EntryView entry) { + long saved = entry.getValue().ttlDeadline(); + if (saved != UNSET_DEADLINE) { + return saved; + } + + long ttl = entry.getTtl(); + return ttl <= 0 || ttl == NO_DEADLINE ? NO_DEADLINE : entry.getCreationTime() + ttl; + } + + private record Window(Attempt attempt, long ttlDeadline) implements Serializable { + + private static final long serialVersionUID = 1L; + } +} diff --git a/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java b/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..f231a20f --- /dev/null +++ b/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,191 @@ +package org.apache.shiro.biz.cache.hazelcast3; + +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.client.config.ClientConfig; +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.NetworkConfig; +import com.hazelcast.core.EntryView; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class Hazelcast3CredentialRetryStoreIntegrationTest { + + private static HazelcastInstance first; + private static HazelcastInstance second; + private static HazelcastInstance client; + + @BeforeClass + public static void startCluster() throws IOException { + String cluster = "shiro-hazelcast3-" + UUID.randomUUID(); + int firstPort; + int secondPort; + try (ServerSocket a = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); + ServerSocket b = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + firstPort = a.getLocalPort(); + secondPort = b.getLocalPort(); + } + + first = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); + second = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); + ClientConfig proxy = new ClientConfig(); + proxy.getGroupConfig().setName(cluster); + proxy.setProperty("hazelcast.logging.type", "none"); + proxy.getNetworkConfig().addAddress("127.0.0.1:" + secondPort); + client = HazelcastClient.newHazelcastClient(proxy); + assertEquals(2, client.getCluster().getMembers().size()); + } + + @AfterClass + public static void stopCluster() { + if (Objects.nonNull(client)) { + client.shutdown(); + } + if (Objects.nonNull(second)) { + second.getLifecycleService().terminate(); + } + if (Objects.nonNull(first)) { + first.getLifecycleService().terminate(); + } + } + + @Test + public void reservesUniqueCountsFromAMemberAndAThinClient() throws Exception { + Hazelcast3CredentialRetryStore memberStore = store(first, "atomic"); + Hazelcast3CredentialRetryStore clientStore = store(client, "atomic"); + ExecutorService workers = Executors.newFixedThreadPool(6); + try { + List> requests = new ArrayList<>(); + for (int i = 0; i < 48; i++) { + var selected = i % 2 == 0 ? memberStore : clientStore; + requests.add(() -> selected.reserve("principal")); + } + Set counts = new HashSet<>(); + Set windows = new HashSet<>(); + for (Future future : workers.invokeAll(requests, 10, TimeUnit.SECONDS)) { + Attempt attempt = future.get(); + assertTrue(counts.add(attempt.getCount())); + windows.add(attempt.getWindowId()); + } + assertEquals(1, windows.size()); + assertEquals(48, counts.size()); + assertTrue(counts.contains(1)); + assertTrue(counts.contains(48)); + assertEquals(49, clientStore.reserve("principal").getCount()); + } finally { + workers.shutdownNow(); + } + } + + @Test + public void preservesTheCreationTtlAndDiscardsStaleClears() throws Exception { + IMap map = first.getMap("ttl"); + var memberStore = store(first, "ttl"); + var clientStore = store(client, "ttl"); + + Attempt initial = memberStore.reserve("principal"); + long original = map.getEntryView("principal").getExpirationTime(); + await(original - 1600); + assertEquals(2, clientStore.reserve("principal").getCount()); + assertTrue(Math.abs(original - map.getEntryView("principal").getExpirationTime()) < 300); + await(original + 100); + Attempt renewed = clientStore.reserve("principal"); + assertEquals(1, renewed.getCount()); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + memberStore.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, clientStore.reserve("principal").getCount()); + memberStore.clearIfCurrent("principal", renewed.getWindowId()); + assertNull(map.getEntryView("principal")); + } + + @Test + public void refreshesMaxIdleOnlyForReservations() throws Exception { + IMap map = first.getMap("idle"); + var memberStore = store(first, "idle"); + var clientStore = store(client, "idle"); + Attempt initial = memberStore.reserve("principal"); + long firstDeadline = map.getEntryView("principal").getExpirationTime(); + await(firstDeadline - 1000); + assertEquals(2, clientStore.reserve("principal").getCount()); + EntryView after = map.getEntryView("principal"); + assertTrue(after.getExpirationTime() > firstDeadline); + clientStore.clearIfCurrent("principal", "old-window"); + assertEquals(after.getExpirationTime(), map.getEntryView("principal").getExpirationTime()); + + await(after.getExpirationTime() + 100); + Attempt next = memberStore.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + } + + @Test + public void preservesIdleExpiryForAThinClientWithStatisticsDisabled() throws Exception { + var idle = store(client, "idle-no-stats"); + Attempt first = idle.reserve("principal"); + long start = System.currentTimeMillis(); + await(start + 400); + assertEquals(2, idle.reserve("principal").getCount()); + await(start + 2600); + + Attempt renewed = idle.reserve("principal"); + assertEquals(1, renewed.getCount()); + assertNotEquals(first.getWindowId(), renewed.getWindowId()); + } + + private static Hazelcast3CredentialRetryStore store(HazelcastInstance instance, String mapName) { + int maxIdle = first.getConfig().findMapConfig(mapName).getMaxIdleSeconds(); + return new Hazelcast3CredentialRetryStore<>(instance, mapName, maxIdle, Object::toString); + } + + private static void await(long deadline) throws InterruptedException { + long remaining = deadline - System.currentTimeMillis(); + if (remaining > 0) { + Thread.sleep(remaining); + } + } + + private static Config member(String cluster, int ownPort, int otherPort) { + Config config = new Config(); + config.getGroupConfig().setName(cluster); + config.setProperty("hazelcast.logging.type", "none"); + config.setProperty("hazelcast.operation.thread.count", "2"); + config.setProperty("hazelcast.operation.generic.thread.count", "2"); + config.setProperty("hazelcast.io.thread.count", "2"); + config.setProperty("hazelcast.event.thread.count", "2"); + config.setProperty("hazelcast.wait.seconds.before.join", "0"); + config.setProperty("hazelcast.socket.bind.any", "false"); + config.addMapConfig(new MapConfig("ttl").setTimeToLiveSeconds(4).setMaxIdleSeconds(10)); + config.addMapConfig(new MapConfig("idle").setMaxIdleSeconds(2)); + config.addMapConfig(new MapConfig("idle-no-stats").setMaxIdleSeconds(2).setStatisticsEnabled(false)); + NetworkConfig network = config.getNetworkConfig(); + network.setPort(ownPort).setPortAutoIncrement(false); + network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); + network.getJoin().getMulticastConfig().setEnabled(false); + network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + return config; + } +} From 1d8045cb301874f54fd49abe358cec063f9edded Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:41:41 +0800 Subject: [PATCH 17/50] Expire stale Memcached retry windows before incrementing --- .../J2CacheMemcachedCredentialRetryStore.java | 21 ++++++++++----- ...edCredentialRetryStoreIntegrationTest.java | 27 +++++++++++++++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index b173a8ac..2c662d6c 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -63,18 +63,23 @@ public Attempt reserve(Object principal) { for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { GetsResponse current = client.gets(key, STRINGS); if (Objects.isNull(current)) { - Window initial = new Window(new Attempt(UUID.randomUUID().toString(), 1), initialDeadline()); + Window initial = newWindow(); if (client.add(key, initial.expiresAt(), initial.encode(), STRINGS)) { return initial.attempt(); } } else { Window window = Window.decode(current.getValue()); - Attempt attempt = window.attempt(); - if (attempt.getCount() == Integer.MAX_VALUE) { - return attempt; + Window next; + if (window.expiresAt() > 0 && Instant.now().getEpochSecond() >= window.expiresAt()) { + next = newWindow(); + } else { + Attempt attempt = window.attempt(); + if (attempt.getCount() == Integer.MAX_VALUE) { + return attempt; + } + next = new Window(new Attempt(attempt.getWindowId(), attempt.getCount() + 1), + window.expiresAt()); } - Window next = new Window(new Attempt(attempt.getWindowId(), attempt.getCount() + 1), - window.expiresAt()); if (client.cas(key, next.expiresAt(), next.encode(), STRINGS, current.getCas())) { return next.attempt(); } @@ -113,6 +118,10 @@ public void clearIfCurrent(Object principal, String windowId) { throw new CacheException("Unable to clear a Memcached retry window within the conflict limit"); } + private Window newWindow() { + return new Window(new Attempt(UUID.randomUUID().toString(), 1), initialDeadline()); + } + private int initialDeadline() { if (regionExpiry == 0) { return 0; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 74032028..5fc7857d 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -1,6 +1,10 @@ package org.apache.shiro.biz.cache.j2cache; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; import java.util.ArrayList; +import java.util.HexFormat; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -16,6 +20,7 @@ import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; +import net.rubyeye.xmemcached.transcoders.StringTranscoder; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.After; @@ -114,6 +119,28 @@ public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { } } + @Test + public void startsANewWindowIfMemcachedStillReturnsAnExpiredWindow() throws Exception { + J2CacheConfig config = config(true, "4s"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + var store = store(channel, config, firstClient); + String key = "shiro-retry:" + digest(namespace) + ":" + digest("principal"); + long expiredAt = Instant.now().getEpochSecond() - 1; + assertTrue(firstClient.set(key, 20, expiredAt + ":8:old-window", new StringTranscoder())); + + Attempt initial = store.reserve("principal"); + assertEquals(1, initial.getCount()); + assertNotEquals("old-window", initial.getWindowId()); + store.clearIfCurrent("principal", "old-window"); + assertEquals(2, store.reserve("principal").getCount()); + } + } + + private static String digest(String value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } + @Test public void rejectsConfigurationThatCannotStoreSharedCounters() { J2CacheConfig config = config(false, "4s"); From 3c98f7975868fa930788904d00201dc9c3f7ff3d Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:41:41 +0800 Subject: [PATCH 18/50] Preserve dynamic retry expiry in Spring Data Redis 4 --- .github/workflows/main-ci.yml | 2 + pom.xml | 1 + .../redis/RedisCredentialRetryStore.java | 81 ++++++++- shiro-extension-spring-redis4/pom.xml | 42 +++++ ...SpringDataRedis4CredentialRetryStores.java | 67 +++++++ ...4CredentialRetryStoresIntegrationTest.java | 172 ++++++++++++++++++ 6 files changed, 359 insertions(+), 6 deletions(-) create mode 100644 shiro-extension-spring-redis4/pom.xml create mode 100644 shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java create mode 100644 shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 9862cf69..31e6dc46 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -54,6 +54,8 @@ jobs: test -s shiro-extension-spring/target/site/jacoco/jacoco.xml test -s shiro-extension-hazelcast3/target/jacoco.exec test -s shiro-extension-hazelcast3/target/site/jacoco/jacoco.xml + test -s shiro-extension-spring-redis4/target/jacoco.exec + test -s shiro-extension-spring-redis4/target/site/jacoco/jacoco.xml - uses: actions/upload-artifact@v7 if: always() with: diff --git a/pom.xml b/pom.xml index 5f3c4d9a..d806faa5 100644 --- a/pom.xml +++ b/pom.xml @@ -645,5 +645,6 @@ shiro-extension-core shiro-extension-hazelcast3 shiro-extension-spring + shiro-extension-spring-redis4 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java index 124b5498..2250e3b6 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -57,6 +57,28 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { end return window .. ':' .. count """; + private static final String RESERVE_DYNAMIC = """ + local key = KEYS[1] + local window = redis.call('HGET', key, 'window') + if not window then + if ARGV[2] == '' then + return '' + end + redis.call('HSET', key, 'window', ARGV[1], 'count', 1) + if ARGV[2] ~= '0' then + redis.call('PEXPIRE', key, ARGV[2]) + end + return ARGV[1] .. ':1' + end + local count = redis.call('HGET', key, 'count') + if tonumber(count) < 2147483647 then + count = redis.call('HINCRBY', key, 'count', 1) + end + if ARGV[3] ~= '0' then + redis.call('PEXPIRE', key, ARGV[3]) + end + return window .. ':' .. count + """; private static final String CLEAR = """ if redis.call('HGET', KEYS[1], 'window') == ARGV[1] then redis.call('DEL', KEYS[1]) @@ -68,8 +90,7 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { private final ScriptExecutor executor; private final String namespace; private final Function principalKey; - private final String expiryMillis; - private final String idleMillis; + private final Reservation reservation; /** * @param executor Redis client operation for scripts returning a UTF-8 bulk string @@ -91,20 +112,63 @@ public RedisCredentialRetryStore(ScriptExecutor executor, String namespace, */ public RedisCredentialRetryStore(ScriptExecutor executor, String namespace, Function principalKey, Duration expiry, Duration maxIdle) { + this(executor, namespace, principalKey, fixedReservation(expiry, maxIdle)); + } + + /** + * Uses the provider's creation and access expiry functions with an atomic Redis reservation. + * + * @param executor Redis client operation for scripts returning a UTF-8 bulk string + * @param namespace dedicated retry hash namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param creationExpiry evaluated when a new retry window is needed. Zero creates a persistent window. + * @param accessExpiry evaluated for each reservation. Zero preserves the current expiry. + * @return a store using the supplied expiry functions + */ + public static RedisCredentialRetryStore withDynamicExpiry( + ScriptExecutor executor, String namespace, Function principalKey, + Function creationExpiry, Function accessExpiry) { + Objects.requireNonNull(creationExpiry, "creationExpiry"); + Objects.requireNonNull(accessExpiry, "accessExpiry"); + return new RedisCredentialRetryStore(executor, namespace, principalKey, (scripts, keys, principal) -> { + String window = UUID.randomUUID().toString(); + String accessMillis = dynamicMillis(accessExpiry.apply(principal)); + String result = scripts.eval(RESERVE_DYNAMIC, keys, List.of(window, "", accessMillis)); + if (result.isEmpty()) { + String creationMillis = dynamicMillis(creationExpiry.apply(principal)); + return scripts.eval(RESERVE_DYNAMIC, keys, List.of(window, creationMillis, accessMillis)); + } + return result; + }); + } + + private RedisCredentialRetryStore(ScriptExecutor executor, String namespace, + Function principalKey, Reservation reservation) { this.executor = Objects.requireNonNull(executor, "executor"); this.namespace = Objects.requireNonNull(namespace, "namespace"); this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); + this.reservation = reservation; if (namespace.isBlank()) { throw new IllegalArgumentException("Retry state requires a namespace"); } + } + + private static Reservation fixedReservation(Duration expiry, Duration maxIdle) { long ttl = toMillis(expiry, "expiry"); long idle = toMillis(maxIdle, "maxIdle"); // Allow room for the current epoch time while keeping Lua arithmetic exact. if (idle > 0 && (ttl > (1L << 52) || idle > (1L << 52))) { throw new IllegalArgumentException("Retry duration is too large for an idle expiry policy"); } - this.expiryMillis = Long.toString(ttl); - this.idleMillis = Long.toString(idle); + String expiryMillis = Long.toString(ttl); + String idleMillis = Long.toString(idle); + return (scripts, keys, principal) -> scripts.eval(RESERVE, keys, + List.of(UUID.randomUUID().toString(), expiryMillis, idleMillis)); + } + + private static String dynamicMillis(Duration duration) { + Objects.requireNonNull(duration, "duration"); + return Long.toString(duration.isNegative() ? 0 : duration.toMillis()); } private static long toMillis(Duration duration, String name) { @@ -118,8 +182,7 @@ private static long toMillis(Duration duration, String name) { @Override public Attempt reserve(Object principal) { - String result = executor.eval(RESERVE, List.of(key(principal)), - List.of(UUID.randomUUID().toString(), expiryMillis, idleMillis)); + String result = reservation.reserve(executor, List.of(key(principal)), principal); int separator = result.lastIndexOf(':'); if (separator < 1) { throw new IllegalStateException("Unexpected Redis retry reservation response"); @@ -137,6 +200,12 @@ private String key(Object principal) { return namespace + ":" + encoded; } + @FunctionalInterface + private interface Reservation { + + String reserve(ScriptExecutor executor, List keys, Object principal); + } + /** Executes one script on the primary Redis node owning its key. */ @FunctionalInterface public interface ScriptExecutor { diff --git a/shiro-extension-spring-redis4/pom.xml b/shiro-extension-spring-redis4/pom.xml new file mode 100644 index 00000000..bcaaa48c --- /dev/null +++ b/shiro-extension-spring-redis4/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + + io.github.easy4j + shiro-extension + 2.0.x.20260630-SNAPSHOT + ../pom.xml + + + shiro-extension-spring-redis4 + ${project.groupId}:${project.artifactId} + Credential retry integration for Spring Data Redis 4 + + + + io.github.easy4j + shiro-extension-core + ${revision} + + + org.springframework.data + spring-data-redis + 4.1.2 + provided + + + io.lettuce + lettuce-core + 7.5.2.RELEASE + test + + + junit + junit + test + + + diff --git a/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java b/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java new file mode 100644 index 00000000..aad6c991 --- /dev/null +++ b/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java @@ -0,0 +1,67 @@ +package org.apache.shiro.biz.cache.spring.redis4; + +import java.time.Duration; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Stream; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.springframework.cache.Cache; +import org.springframework.cache.transaction.TransactionAwareCacheDecorator; +import org.springframework.data.redis.cache.RedisCache; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheWriter.TtlFunction; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** Creates retry stores for Spring Data Redis 4 cache regions. */ +public final class SpringDataRedis4CredentialRetryStores { + + private static final StringRedisSerializer STRINGS = StringRedisSerializer.UTF_8; + + private SpringDataRedis4CredentialRetryStores() { + } + + /** + * Preserves the region's per-key TTL and optional time-to-idle behavior. + * + * @param cache Spring Data Redis cache whose expiry policy is used + * @param connectionFactory connection factory used by that Redis cache + * @param namespace dedicated retry namespace shared by application instances + * @param principalKey stable principal encoding shared by application instances + * @return an atomic Redis retry store + */ + public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey) { + Cache target = cache; + while (target instanceof TransactionAwareCacheDecorator decorator) { + target = decorator.getTargetCache(); + } + if (!(target instanceof RedisCache redisCache)) { + throw new IllegalArgumentException("Spring retry cache must be backed by Spring Data Redis"); + } + Objects.requireNonNull(connectionFactory, "connectionFactory"); + + RedisCacheConfiguration config = redisCache.getCacheConfiguration(); + TtlFunction ttl = config.getTtlFunction(); + Function accessExpiry = config.isTimeToIdleEnabled() + ? principal -> ttl.getTimeToLive(principal, null) : principal -> Duration.ZERO; + // The matcher historically inserted an AtomicInteger at zero before reserving its first attempt. + return RedisCredentialRetryStore.withDynamicExpiry( + (script, keys, args) -> eval(connectionFactory, script, keys, args), + namespace, principalKey, principal -> ttl.getTimeToLive(principal, new AtomicInteger()), accessExpiry); + } + + private static String eval(RedisConnectionFactory factory, String script, List keys, List args) { + byte[][] arguments = Stream.concat(keys.stream(), args.stream()).map(STRINGS::serialize).toArray(byte[][]::new); + try (RedisConnection connection = factory.getConnection()) { + byte[] result = connection.scriptingCommands().eval( + STRINGS.serialize(script), ReturnType.VALUE, keys.size(), arguments); + return STRINGS.deserialize(result); + } + } +} diff --git a/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java new file mode 100644 index 00000000..cfaf4677 --- /dev/null +++ b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java @@ -0,0 +1,172 @@ +package org.apache.shiro.biz.cache.spring.redis4; + +import java.time.Duration; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.cache.RedisCacheWriter.TtlFunction; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.ReturnType; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class SpringDataRedis4CredentialRetryStoresIntegrationTest { + + private static final String REGION = "credential-retry"; + private static final StringRedisSerializer UTF_8 = StringRedisSerializer.UTF_8; + private static LettuceConnectionFactory first; + private static LettuceConnectionFactory second; + + private final String namespace = "test:spring-redis4-retry:" + UUID.randomUUID(); + + @BeforeClass + public static void connect() { + String port = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + first = connectionFactory(port); + second = connectionFactory(port); + } + + @AfterClass + public static void disconnect() { + if (Objects.nonNull(second)) { + second.destroy(); + } + if (Objects.nonNull(first)) { + first.destroy(); + } + } + + @Test + public void evaluatesPerKeyTtlOnceWhenAWindowIsCreated() { + AtomicInteger creationCalls = new AtomicInteger(); + TtlFunction ttl = (key, value) -> { + assertEquals(0, ((AtomicInteger) value).get()); + creationCalls.incrementAndGet(); + return "brief".equals(key) ? Duration.ofSeconds(6) : Duration.ofSeconds(12); + }; + var config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(ttl); + CredentialRetryStore a = store(first, config); + CredentialRetryStore b = store(second, config); + Attempt initial = a.reserve("brief"); + long brief = expiry("brief"); + Attempt other = b.reserve("longer"); + long longer = expiry("longer"); + assertEquals(1, other.getCount()); + assertTrue(longer - brief >= 5500); + assertEquals(initial.getWindowId(), b.reserve("brief").getWindowId()); + assertEquals(brief, expiry("brief")); + assertEquals(2, creationCalls.get()); + } + + @Test + public void refreshesTimeToIdleWithReadPolicyAndPreservesTheNewWindowOnStaleClear() throws Exception { + TtlFunction ttl = (key, value) -> Objects.isNull(value) ? Duration.ofSeconds(9) : Duration.ofSeconds(4); + var config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(ttl).enableTimeToIdle(); + CredentialRetryStore a = store(first, config); + CredentialRetryStore b = store(second, config); + Attempt initial = a.reserve("principal"); + long starting = expiry("principal"); + assertTrue(starting > System.currentTimeMillis()); + assertTrue(starting - System.currentTimeMillis() <= 4000); + Thread.sleep(50); + assertEquals(2, b.reserve("principal").getCount()); + long renewed = expiry("principal"); + assertTrue(renewed - starting >= 4900); + + b.clearIfCurrent("principal", "old-window"); + assertEquals(renewed, expiry("principal")); + a.clearIfCurrent("principal", initial.getWindowId()); + Attempt next = b.reserve("principal"); + assertEquals(1, next.getCount()); + assertNotEquals(initial.getWindowId(), next.getWindowId()); + a.clearIfCurrent("principal", initial.getWindowId()); + assertEquals(2, b.reserve("principal").getCount()); + } + + @Test + public void keepsTtlWhenReadPolicyReturnsZeroAndTreatsSubmillisecondWritesAsPersistent() { + TtlFunction ttl = (key, value) -> Objects.isNull(value) ? Duration.ZERO + : ("persistent".equals(key) ? Duration.ofNanos(1) : Duration.ofSeconds(8)); + var config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(ttl).enableTimeToIdle(); + CredentialRetryStore store = store(first, config); + + store.reserve("ordinary"); + long deadline = expiry("ordinary"); + assertTrue(deadline > 0); + assertEquals(2, store.reserve("ordinary").getCount()); + assertEquals(deadline, expiry("ordinary")); + + store.reserve("persistent"); + assertEquals(-1L, expiry("persistent")); + } + + @Test + public void concurrentCreationAttemptsShareOneWindow() throws Exception { + CountDownLatch bothCreating = new CountDownLatch(2); + TtlFunction ttl = (key, value) -> { + bothCreating.countDown(); + try { + assertTrue(bothCreating.await(5, TimeUnit.SECONDS)); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new AssertionError(exception); + } + return Duration.ofSeconds(10); + }; + var config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(ttl); + CredentialRetryStore a = store(first, config); + CredentialRetryStore b = store(second, config); + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + var left = workers.submit(() -> a.reserve("principal")); + var right = workers.submit(() -> b.reserve("principal")); + Attempt firstAttempt = left.get(8, TimeUnit.SECONDS); + Attempt secondAttempt = right.get(8, TimeUnit.SECONDS); + assertNotEquals(firstAttempt.getCount(), secondAttempt.getCount()); + assertEquals(3, firstAttempt.getCount() + secondAttempt.getCount()); + assertEquals(firstAttempt.getWindowId(), secondAttempt.getWindowId()); + assertEquals(3, b.reserve("principal").getCount()); + } finally { + workers.shutdownNow(); + } + } + + private CredentialRetryStore store(LettuceConnectionFactory factory, RedisCacheConfiguration config) { + RedisCacheManager manager = RedisCacheManager.builder(factory) + .withCacheConfiguration(REGION, config).transactionAware().build(); + manager.afterPropertiesSet(); + return SpringDataRedis4CredentialRetryStores.fromCache( + manager.getCache(REGION), factory, namespace, Object::toString); + } + + private long expiry(String principal) { + try (RedisConnection connection = first.getConnection()) { + return connection.scriptingCommands().eval( + UTF_8.serialize("return redis.call('PEXPIRETIME', KEYS[1])"), + ReturnType.INTEGER, 1, UTF_8.serialize(namespace + ":" + principal)); + } + } + + private static LettuceConnectionFactory connectionFactory(String port) { + var factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port)); + factory.afterPropertiesSet(); + return factory; + } +} From c19d0534814b30f21c93fc8daabe7f8a1817bfd1 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:50:30 +0800 Subject: [PATCH 19/50] Bind Spring Boot retry stores to Shiro cache regions --- README.md | 6 +- README.zh-CN.md | 6 +- ...edentialsRetryLimitCredentialsMatcher.java | 7 + .../credential/DefaultCredentialsMatcher.java | 7 + shiro-extension-spring/pom.xml | 6 + ...CredentialRetryStoreAutoConfiguration.java | 70 ++++++++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + ...entialRetryStoreAutoConfigurationTest.java | 160 ++++++++++++++++++ ...ngCredentialRetryStoreIntegrationTest.java | 29 +++- 9 files changed, 283 insertions(+), 9 deletions(-) create mode 100644 shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java create mode 100644 shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports create mode 100644 shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java diff --git a/README.md b/README.md index 294a0f47..9edd7f0a 100644 --- a/README.md +++ b/README.md @@ -184,7 +184,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); ## 7. Configuration -This is a library: there are no configuration properties or prefixes. Behavior is configured through constructor/bean injection: +Configure behavior through constructors and beans. | Extension point | Configurable via | | :--- | :--- | @@ -194,6 +194,10 @@ This is a library: there are no configuration properties or prefixes. Behavior i | Filters (`HttpServletShiroFilter` and friends) | bean properties and the Shiro filter-chain definition | | i18n messages | bundled `org/apache/shiro/biz/messages*.properties`, `ShiroBizMessageSource` | +### Shared credential retry state in Spring Boot + +For a Spring-managed retry matcher with cache name `login`, declare a provider-backed `CredentialRetryStore` bean named `shiro.credential-retry.login`. Spring Boot binds it to `DefaultCredentialsMatcher` and `CredentialsRetryLimitCredentialsMatcher`, including instances held by Spring-managed realms. An explicitly assigned store takes precedence. Matchers without a matching bean keep their Shiro cache configuration. Use the same provider, retry namespace and principal key mapping across the instances that share the window. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index ed346754..b827b64d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -184,7 +184,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); ## 7. Configuration -这是库:没有配置属性与属性前缀。行为通过构造器/Bean 注入配置: +通过构造器和 Bean 配置扩展行为。 | 扩展点 | 配置方式 | | :--- | :--- | @@ -194,6 +194,10 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); | 过滤器(`HttpServletShiroFilter` 等) | Bean 属性与 Shiro 过滤器链定义 | | i18n 消息 | 随包 `org/apache/shiro/biz/messages*.properties`、`ShiroBizMessageSource` | +### Spring Boot 共享重试计数 + +如果匹配器的重试缓存名为 `login`,声明名为 `shiro.credential-retry.login` 的 `CredentialRetryStore` Bean。Spring Boot 会将它绑定到 `DefaultCredentialsMatcher` 和 `CredentialsRetryLimitCredentialsMatcher`,包括 Spring 管理的 Realm 内部创建的实例。手工指定的存储优先。缺少同名 Bean 时,匹配器沿用原 Shiro 缓存配置。共享重试窗口的应用实例应使用相同的缓存提供者、重试命名空间和主体键映射。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): 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 23997a4a..952080b8 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 @@ -66,6 +66,13 @@ public void setCredentialRetryStore(CredentialRetryStore store) { this.credentialRetryStore = store; } + /** + * @return the configured retry store, or null when using the Shiro retry cache + */ + public CredentialRetryStore getCredentialRetryStore() { + return credentialRetryStore; + } + @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { CredentialRetryStore store = credentialRetryStore; 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 437e1fcd..a6f14ef1 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 @@ -59,6 +59,13 @@ public void setCredentialRetryStore(CredentialRetryStore store) { this.credentialRetryStore = store; } + /** + * @return the configured retry store, or null when using the Shiro retry cache + */ + public CredentialRetryStore getCredentialRetryStore() { + return credentialRetryStore; + } + @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { CredentialRetryStore store = credentialRetryStore; diff --git a/shiro-extension-spring/pom.xml b/shiro-extension-spring/pom.xml index 13a1849b..15b477da 100644 --- a/shiro-extension-spring/pom.xml +++ b/shiro-extension-spring/pom.xml @@ -65,6 +65,12 @@ lombok provided + + org.springframework.boot + spring-boot-autoconfigure + 2.7.18 + provided + org.springframework.data spring-data-redis diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java new file mode 100644 index 00000000..5c59ade7 --- /dev/null +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfiguration.java @@ -0,0 +1,70 @@ +package org.apache.shiro.biz.authc.credential.spring; + +import java.util.Objects; +import java.util.function.Consumer; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.authc.credential.CredentialsRetryLimitCredentialsMatcher; +import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher; +import org.apache.shiro.realm.AuthenticatingRealm; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Role; +import org.springframework.core.Ordered; +import org.springframework.core.PriorityOrdered; +import org.springframework.util.StringUtils; + +/** + * Applies configured provider-backed stores to Spring-managed retry matchers. + * Declare a {@link CredentialRetryStore} bean named {@code shiro.credential-retry.} + * to enable the store for matchers using that cache name. + */ +@AutoConfiguration +public class CredentialRetryStoreAutoConfiguration { + + /** Bean name prefix followed by the matcher's retry cache name. */ + public static final String STORE_BEAN_PREFIX = "shiro.credential-retry."; + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + static CredentialRetryStoreBinder shiroCredentialRetryStoreBinder(BeanFactory beanFactory) { + return new CredentialRetryStoreBinder(beanFactory); + } + + static final class CredentialRetryStoreBinder implements BeanPostProcessor, PriorityOrdered { + + private final BeanFactory beanFactory; + + CredentialRetryStoreBinder(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + Object target = bean instanceof AuthenticatingRealm realm ? realm.getCredentialsMatcher() : bean; + if (target instanceof DefaultCredentialsMatcher matcher && Objects.isNull(matcher.getCredentialRetryStore())) { + bind(matcher.getCredentialsRetryCacheName(), matcher::setCredentialRetryStore); + } else if (target instanceof CredentialsRetryLimitCredentialsMatcher matcher + && Objects.isNull(matcher.getCredentialRetryStore())) { + bind(matcher.getCredentialsRetryCacheName(), matcher::setCredentialRetryStore); + } + return bean; + } + + @Override + public int getOrder() { + return Ordered.LOWEST_PRECEDENCE; + } + + private void bind(String cacheName, Consumer setter) { + if (StringUtils.hasText(cacheName)) { + String beanName = STORE_BEAN_PREFIX + cacheName; + if (beanFactory.containsBean(beanName)) { + setter.accept(beanFactory.getBean(beanName, CredentialRetryStore.class)); + } + } + } + } +} diff --git a/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..2de1ddfd --- /dev/null +++ b/shiro-extension-spring/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +org.apache.shiro.biz.authc.credential.spring.CredentialRetryStoreAutoConfiguration diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java new file mode 100644 index 00000000..a471a0db --- /dev/null +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/authc/credential/spring/CredentialRetryStoreAutoConfigurationTest.java @@ -0,0 +1,160 @@ +package org.apache.shiro.biz.authc.credential.spring; + +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.shiro.authc.ExcessiveAttemptsException; +import org.apache.shiro.authc.IncorrectCredentialsException; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.biz.authc.credential.CredentialsRetryLimitCredentialsMatcher; +import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher; +import org.apache.shiro.cache.MemoryConstrainedCacheManager; +import org.apache.shiro.realm.SimpleAccountRealm; +import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; + +public class CredentialRetryStoreAutoConfigurationTest { + + @Test + public void bootDiscoversBindingsForBothMatcherTypesByTheirCacheNames() { + var first = new RecordingStore(); + var second = new RecordingStore(); + try (var context = context()) { + context.registerBean(storeName("password"), CredentialRetryStore.class, () -> first); + context.registerBean(storeName("hashed"), CredentialRetryStore.class, () -> second); + context.registerBean("passwordMatcher", DefaultCredentialsMatcher.class, () -> passwordMatcher("password")); + context.registerBean(CredentialsRetryLimitCredentialsMatcher.class, this::hashedMatcher); + context.refresh(); + + var password = context.getBean(DefaultCredentialsMatcher.class); + var hashed = context.getBean(CredentialsRetryLimitCredentialsMatcher.class); + assertSame(first, password.getCredentialRetryStore()); + assertSame(second, hashed.getCredentialRetryStore()); + assertFalse(password.doCredentialsMatch( + new UsernamePasswordToken("principal", "wrong"), + new SimpleAuthenticationInfo("principal", "correct", "realm"))); + assertEquals(1, first.attempts.get()); + assertEquals(0, second.attempts.get()); + } + } + + @Test + public void keepsExplicitStoreAndUnconfiguredMatchers() { + var assigned = new RecordingStore(); + try (var context = context()) { + context.registerBean(storeName("manual"), CredentialRetryStore.class, RecordingStore::new); + context.registerBean("manual", DefaultCredentialsMatcher.class, () -> { + var matcher = passwordMatcher("manual"); + matcher.setCredentialRetryStore(assigned); + return matcher; + }); + context.registerBean("legacy", DefaultCredentialsMatcher.class, () -> { + var matcher = passwordMatcher("legacy"); + matcher.setCacheManager(new MemoryConstrainedCacheManager()); + matcher.setRetryLimit(2); + return matcher; + }); + context.registerBean(AllowAllCredentialsMatcher.class, AllowAllCredentialsMatcher::new); + context.refresh(); + + var manual = context.getBean("manual", DefaultCredentialsMatcher.class); + assertSame(assigned, manual.getCredentialRetryStore()); + + var legacy = context.getBean("legacy", DefaultCredentialsMatcher.class); + assertNull(legacy.getCredentialRetryStore()); + var rejected = new UsernamePasswordToken("principal", "wrong"); + var account = new SimpleAuthenticationInfo("principal", "correct", "realm"); + assertFalse(legacy.doCredentialsMatch(rejected, account)); + assertThrows(ExcessiveAttemptsException.class, () -> legacy.doCredentialsMatch(rejected, account)); + + context.getBean(AllowAllCredentialsMatcher.class); + } + } + + @Test + public void bindsAnInlineMatcherThroughItsSpringManagedRealm() { + var store = new RecordingStore(); + try (var context = context()) { + context.registerBean(storeName("inline"), CredentialRetryStore.class, () -> store); + context.registerBean(SimpleAccountRealm.class, () -> { + var realm = new SimpleAccountRealm(); + var matcher = passwordMatcher("inline"); + matcher.setRetryLimit(2); + realm.setCredentialsMatcher(matcher); + realm.addAccount("principal", "correct"); + return realm; + }); + context.refresh(); + + var realm = context.getBean(SimpleAccountRealm.class); + var rejected = new UsernamePasswordToken("principal", "wrong"); + assertThrows(IncorrectCredentialsException.class, () -> realm.getAuthenticationInfo(rejected)); + assertThrows(ExcessiveAttemptsException.class, () -> realm.getAuthenticationInfo(rejected)); + assertEquals(2, store.attempts.get()); + } + } + + @Test + public void reportsARegionBeanWithTheWrongTypeAtStartup() { + try (var context = context()) { + context.registerBean(storeName("password"), String.class, () -> "incorrect type"); + context.registerBean(DefaultCredentialsMatcher.class, () -> passwordMatcher("password")); + BeanCreationException failure = assertThrows(BeanCreationException.class, context::refresh); + assertEquals(BeanNotOfRequiredTypeException.class, failure.getMostSpecificCause().getClass()); + } + } + + private static AnnotationConfigApplicationContext context() { + var context = new AnnotationConfigApplicationContext(); + context.register(BootConfiguration.class); + return context; + } + + private static String storeName(String region) { + return CredentialRetryStoreAutoConfiguration.STORE_BEAN_PREFIX + region; + } + + private static DefaultCredentialsMatcher passwordMatcher(String region) { + var matcher = new DefaultCredentialsMatcher(); + matcher.setCredentialsRetryCacheName(region); + return matcher; + } + + private CredentialsRetryLimitCredentialsMatcher hashedMatcher() { + var matcher = new CredentialsRetryLimitCredentialsMatcher(); + matcher.setCredentialsRetryCacheName("hashed"); + return matcher; + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration(exclude = RedisAutoConfiguration.class) + static class BootConfiguration { + } + + private static final class RecordingStore implements CredentialRetryStore { + + private final AtomicInteger attempts = new AtomicInteger(); + + @Override + public Attempt reserve(Object principal) { + return new Attempt("window", attempts.incrementAndGet()); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + attempts.set(0); + } + } +} diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java index 0d8a9cbd..d90e5bef 100644 --- a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -24,11 +24,13 @@ import org.apache.shiro.biz.authc.credential.CredentialRetryStore; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.apache.shiro.biz.authc.credential.DefaultCredentialsMatcher; +import org.apache.shiro.biz.authc.credential.spring.CredentialRetryStoreAutoConfiguration; import org.apache.shiro.cache.CacheException; import org.junit.Test; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnection; @@ -102,13 +104,10 @@ public void springRedisEnforcesTheRetryLimitAcrossMatcherInstances() { String namespace = "test:spring-matcher:" + UUID.randomUUID(); LettuceConnectionFactory first = connectionFactory(port); LettuceConnectionFactory second = connectionFactory(port); - try { - DefaultCredentialsMatcher a = new DefaultCredentialsMatcher(); - a.setRetryLimit(3); - a.setCredentialRetryStore(redisStore(first, namespace, false)); - DefaultCredentialsMatcher b = new DefaultCredentialsMatcher(); - b.setRetryLimit(3); - b.setCredentialRetryStore(redisStore(second, namespace, true)); + try (var firstContext = matcherContext(first, namespace, false); + var secondContext = matcherContext(second, namespace, true)) { + var a = firstContext.getBean(DefaultCredentialsMatcher.class); + var b = secondContext.getBean(DefaultCredentialsMatcher.class); var rejected = new UsernamePasswordToken("principal", "wrong"); var account = new SimpleAuthenticationInfo("principal", "correct", "realm"); @@ -166,6 +165,22 @@ public void reportsMissingRegionsAndRejectsCachesWithoutTheExpectedProvider() { () -> shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache)); } + private static AnnotationConfigApplicationContext matcherContext( + LettuceConnectionFactory factory, String namespace, boolean transactionAware) { + var context = new AnnotationConfigApplicationContext(); + context.register(CredentialRetryStoreAutoConfiguration.class); + context.registerBean(CredentialRetryStoreAutoConfiguration.STORE_BEAN_PREFIX + REGION, + CredentialRetryStore.class, () -> redisStore(factory, namespace, transactionAware)); + context.registerBean(DefaultCredentialsMatcher.class, () -> { + var matcher = new DefaultCredentialsMatcher(); + matcher.setRetryLimit(3); + matcher.setCredentialsRetryCacheName(REGION); + return matcher; + }); + context.refresh(); + return context; + } + private static LettuceConnectionFactory connectionFactory(String port) { LettuceConnectionFactory factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port)); factory.afterPropertiesSet(); From a78fa5cb56d39f45c948dbe4a7d4a7176eb317bc Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:42:58 +0800 Subject: [PATCH 20/50] Preserve active Ehcache 2 credential retry windows during cutover --- README.md | 2 ++ README.zh-CN.md | 2 ++ .../ehcache/Ehcache2CredentialRetryStore.java | 29 ++++++++++++++----- ...e2CredentialRetryStoreIntegrationTest.java | 28 ++++++++++++++++++ 4 files changed, 54 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 9edd7f0a..44d698e8 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,8 @@ Configure behavior through constructors and beans. For a Spring-managed retry matcher with cache name `login`, declare a provider-backed `CredentialRetryStore` bean named `shiro.credential-retry.login`. Spring Boot binds it to `DefaultCredentialsMatcher` and `CredentialsRetryLimitCredentialsMatcher`, including instances held by Spring-managed realms. An explicitly assigned store takes precedence. Matchers without a matching bean keep their Shiro cache configuration. Use the same provider, retry namespace and principal key mapping across the instances that share the window. +For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index b827b64d..79f4bfdf 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -198,6 +198,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 如果匹配器的重试缓存名为 `login`,声明名为 `shiro.credential-retry.login` 的 `CredentialRetryStore` Bean。Spring Boot 会将它绑定到 `DefaultCredentialsMatcher` 和 `CredentialsRetryLimitCredentialsMatcher`,包括 Spring 管理的 Realm 内部创建的实例。手工指定的存储优先。缺少同名 Bean 时,匹配器沿用原 Shiro 缓存配置。共享重试窗口的应用实例应使用相同的缓存提供者、重试命名空间和主体键映射。 +对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java index f86c0ed8..5c2581e4 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java @@ -3,16 +3,19 @@ import java.io.Serializable; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.config.CacheConfiguration; import net.sf.ehcache.config.TerracottaConfiguration.Consistency; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; /** * Credential retry state backed by Ehcache 2 key locks. Shared deployments require * a strongly consistent Terracotta region. + * An existing legacy retry region can be reused after its legacy clients stop. * * @param serializable key used by the cache */ @@ -46,12 +49,21 @@ public Attempt reserve(Object principal) { return initial; } - Attempt current = (Attempt) entry.getObjectValue(); - if (current.getCount() == Integer.MAX_VALUE) { - return current; + Object value = entry.getObjectValue(); + Attempt next; + if (value instanceof AtomicInteger) { + int count = ((AtomicInteger) value).get(); + if (count < 0) { + throw new CacheException("Legacy credential retry count is negative"); + } + next = new Attempt(UUID.randomUUID().toString(), count == Integer.MAX_VALUE ? count : count + 1); + } else { + Attempt current = (Attempt) value; + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } + next = new Attempt(current.getWindowId(), current.getCount() + 1); } - - Attempt next = new Attempt(current.getWindowId(), current.getCount() + 1); // The replacement keeps the original TTL origin and counts this read as idle activity. cache.put(new Element(key, next, entry.getVersion(), entry.getCreationTime(), entry.getLastAccessTime(), 0L, false, entry.getTimeToLive(), entry.getTimeToIdle(), @@ -69,8 +81,11 @@ public void clearIfCurrent(Object principal, String windowId) { cache.acquireWriteLockOnKey(key); try { Element entry = cache.getQuiet(key); - if (Objects.nonNull(entry) && windowId.equals(((Attempt) entry.getObjectValue()).getWindowId())) { - cache.remove(key); + if (Objects.nonNull(entry)) { + Object value = entry.getObjectValue(); + if (value instanceof Attempt && windowId.equals(((Attempt) value).getWindowId())) { + cache.remove(key); + } } } finally { cache.releaseWriteLockOnKey(key); diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java index 2d544f03..231c19d9 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java @@ -14,6 +14,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; @@ -96,6 +97,33 @@ public void incrementsPreserveCreationDeadlineAndRefreshConfiguredIdlePeriod() t assertEquals(closeToDeadline + TimeUnit.SECONDS.toMillis(30), cache.getQuiet("ending").getExpirationTime()); } + @Test + public void adoptsLegacyCounterWithoutRestartingItsWindow() { + Cache cache = cache(30, 120); + Ehcache2CredentialRetryStore first = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + Ehcache2CredentialRetryStore second = new Ehcache2CredentialRetryStore<>(cache, Object::toString); + long createdAt = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(5); + cache.put(new Element("principal", new AtomicInteger(3), 1, createdAt, createdAt, 0, + false, 30, 120, createdAt)); + long expiry = cache.getQuiet("principal").getExpirationTime(); + + Attempt adopted = first.reserve("principal"); + assertEquals(4, adopted.getCount()); + Attempt next = second.reserve("principal"); + assertEquals(5, next.getCount()); + assertEquals(adopted.getWindowId(), next.getWindowId()); + Element updated = cache.getQuiet("principal"); + assertEquals(createdAt, updated.getCreationTime()); + assertEquals(expiry, updated.getExpirationTime()); + assertEquals(120, updated.getTimeToIdle()); + + cache.put(new Element("other-principal", new AtomicInteger(2))); + long otherExpiry = cache.getQuiet("other-principal").getExpirationTime(); + first.clearIfCurrent("other-principal", "stale"); + assertEquals(2, ((AtomicInteger) cache.getQuiet("other-principal").getObjectValue()).get()); + assertEquals(otherExpiry, cache.getQuiet("other-principal").getExpirationTime()); + } + @Test public void idleOnlyWindowExpiresAndStaleResetDoesNotRefreshIt() throws Exception { Cache cache = cache(0, 1); From 944ef42cd193a64e2cfa21b2a46a171c5d6023f8 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:51:19 +0800 Subject: [PATCH 21/50] Preserve active credential retry windows in Hazelcast cutover --- README.md | 2 + README.zh-CN.md | 2 + .../HazelcastCredentialRetryStore.java | 52 ++++++++++++------- ...stCredentialRetryStoreIntegrationTest.java | 28 ++++++++++ .../Hazelcast3CredentialRetryStore.java | 51 ++++++++++++------ ...t3CredentialRetryStoreIntegrationTest.java | 31 +++++++++++ 6 files changed, 133 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 44d698e8..58f2ac49 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,8 @@ For a Spring-managed retry matcher with cache name `login`, declare a provider-b For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. +For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index 79f4bfdf..118d5d6a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -200,6 +200,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 +Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java index 0aa53159..c12350ef 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; import org.apache.shiro.cache.CacheException; @@ -21,15 +22,18 @@ public final class HazelcastCredentialRetryStore implements CredentialRetrySt private static final int MAX_CONFLICTS = 128; - private final IMap map; + private final IMap map; private final Function principalKey; /** - * @param map dedicated retry map. Cluster members must have this module on their classpath. + * @param map dedicated retry map. Legacy retry maps can be reused after all legacy clients stop. + * Cluster members must have this module on their classpath. * @param principalKey consistent principal key encoding for all callers sharing the map */ - public HazelcastCredentialRetryStore(IMap map, Function principalKey) { - this.map = Objects.requireNonNull(map, "map"); + @SuppressWarnings("unchecked") + public HazelcastCredentialRetryStore(IMap map, Function principalKey) { + // Hazelcast IMap has no runtime value type. The processor accepts both retry formats. + this.map = (IMap) Objects.requireNonNull(map, "map"); this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); } @@ -43,9 +47,13 @@ public void clearIfCurrent(Object principal, String windowId) { K key = key(principal); Objects.requireNonNull(windowId, "windowId"); for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { - EntryView entry = map.getEntryView(key); - if (Objects.isNull(entry) || !windowId.equals(entry.getValue().getWindowId()) - || map.remove(key, entry.getValue())) { + EntryView entry = map.getEntryView(key); + if (Objects.isNull(entry)) { + return; + } + Object value = entry.getValue(); + if (!(value instanceof Attempt) || !windowId.equals(((Attempt) value).getWindowId()) + || map.remove(key, value)) { return; } } @@ -56,7 +64,7 @@ private K key(Object principal) { return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); } - private static final class Reserve implements EntryProcessor { + private static final class Reserve implements EntryProcessor { private static final long serialVersionUID = 1L; @@ -68,22 +76,30 @@ private Reserve(String initialWindowId) { } @Override - public Attempt process(Map.Entry entry) { + public Attempt process(Map.Entry entry) { updated = null; - Attempt current = entry.getValue(); - if (Objects.isNull(current)) { + Object value = entry.getValue(); + if (Objects.isNull(value)) { updated = new Attempt(initialWindowId, 1); - } else if (current.getCount() == Integer.MAX_VALUE) { - return current; + } else if (value instanceof AtomicInteger) { + int count = ((AtomicInteger) value).get(); + if (count < 0) { + throw new CacheException("Legacy credential retry count is negative"); + } + updated = new Attempt(initialWindowId, count == Integer.MAX_VALUE ? count : count + 1); } else { + Attempt current = (Attempt) value; + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } updated = new Attempt(current.getWindowId(), current.getCount() + 1); } - ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(updated); + ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(updated); return updated; } @Override - public EntryProcessor getBackupProcessor() { + public EntryProcessor getBackupProcessor() { if (Objects.isNull(updated)) { return null; } @@ -92,7 +108,7 @@ public EntryProcessor getBackupProcessor() { } } - private static final class CopyReservation implements EntryProcessor { + private static final class CopyReservation implements EntryProcessor { private static final long serialVersionUID = 1L; @@ -103,8 +119,8 @@ private CopyReservation(Attempt attempt) { } @Override - public Attempt process(Map.Entry entry) { - ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(attempt); + public Attempt process(Map.Entry entry) { + ((ExtendedMapEntry) entry).setValueWithoutChangingExpiryTime(attempt); return attempt; } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java index c1e8f67a..3e8d9b78 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -132,6 +133,33 @@ public void reservationRefreshesIdleTimeAndStaleClearKeepsTheIdleDeadline() thro assertNotEquals(initial.getWindowId(), next.getWindowId()); } + @Test + public void migratesLegacyCounterAndKeepsItsProviderDeadline() throws Exception { + String principal = "legacy"; + IMap map = first.getMap("ttl"); + map.set(principal, new AtomicInteger(2), 6, TimeUnit.SECONDS); + map.set(principal, new AtomicInteger(3), 6, TimeUnit.SECONDS); + long originalDeadline = map.getEntryView(principal).getExpirationTime(); + HazelcastCredentialRetryStore remoteStore = store(second, "ttl"); + HazelcastCredentialRetryStore memberStore = store(first, "ttl"); + + Attempt adopted = remoteStore.reserve(principal); + assertEquals(4, adopted.getCount()); + assertEquals(originalDeadline, map.getEntryView(principal).getExpirationTime()); + memberStore.clearIfCurrent(principal, "stale"); + Attempt next = memberStore.reserve(principal); + assertEquals(5, next.getCount()); + assertEquals(adopted.getWindowId(), next.getWindowId()); + assertEquals(originalDeadline, map.getEntryView(principal).getExpirationTime()); + + String unconverted = "unconverted"; + map.set(unconverted, new AtomicInteger(2), 6, TimeUnit.SECONDS); + long unconvertedDeadline = map.getEntryView(unconverted).getExpirationTime(); + remoteStore.clearIfCurrent(unconverted, "stale"); + assertEquals(unconvertedDeadline, map.getEntryView(unconverted).getExpirationTime()); + assertEquals(2, ((AtomicInteger) map.getEntryView(unconverted).getValue()).get()); + } + private static HazelcastCredentialRetryStore store(HazelcastInstance member, String name) { return new HazelcastCredentialRetryStore<>(member.getMap(name), Object::toString); } diff --git a/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java b/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java index 1e1fc496..6c3153f0 100644 --- a/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java +++ b/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java @@ -7,8 +7,10 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; /** * Shared retry state in a dedicated Hazelcast 3.12 IMap. The map's key lock @@ -21,13 +23,14 @@ public final class Hazelcast3CredentialRetryStore implements CredentialRetryS private static final long UNSET_DEADLINE = 0; private static final long NO_DEADLINE = Long.MAX_VALUE; - private final IMap map; + private final IMap map; private final long maxIdleMillis; private final Function principalKey; /** * @param hazelcast member or thin client connected to the retry map's cluster - * @param mapName dedicated retry map managed exclusively by this store, with this module on all members + * @param mapName dedicated retry map. Legacy retry maps can be reused after all legacy clients stop. + * This module must be available on all members. * @param maxIdleSeconds the map's configured max idle. The 3.12 client wire format omits this setting * @param principalKey stable principal encoding shared by application instances */ @@ -46,7 +49,7 @@ public Attempt reserve(Object principal) { K key = key(principal); map.lock(key); try { - EntryView entry = map.getEntryView(key); + EntryView entry = map.getEntryView(key); long now = System.currentTimeMillis(); if (Objects.isNull(entry)) { return startWindow(key); @@ -58,9 +61,19 @@ public Attempt reserve(Object principal) { return startWindow(key); } - Attempt current = entry.getValue().attempt(); - Attempt next = current.getCount() == Integer.MAX_VALUE - ? current : new Attempt(current.getWindowId(), current.getCount() + 1); + Object value = entry.getValue(); + Attempt next; + if (value instanceof AtomicInteger) { + int count = ((AtomicInteger) value).get(); + if (count < 0) { + throw new CacheException("Legacy credential retry count is negative"); + } + next = new Attempt(UUID.randomUUID().toString(), count == Integer.MAX_VALUE ? count : count + 1); + } else { + Attempt current = ((Window) value).attempt(); + next = current.getCount() == Integer.MAX_VALUE + ? current : new Attempt(current.getWindowId(), current.getCount() + 1); + } // Hazelcast 3.12 stores creation, update and TTL metadata at whole-second precision. long remainingSeconds = deadline == NO_DEADLINE ? 0 : TimeUnit.MILLISECONDS.toSeconds(deadline) - TimeUnit.MILLISECONDS.toSeconds(now); @@ -77,9 +90,12 @@ public void clearIfCurrent(Object principal, String windowId) { Objects.requireNonNull(windowId, "windowId"); map.lock(key); try { - EntryView entry = map.getEntryView(key); - if (Objects.nonNull(entry) && windowId.equals(entry.getValue().attempt().getWindowId())) { - map.delete(key); + EntryView entry = map.getEntryView(key); + if (Objects.nonNull(entry)) { + Object value = entry.getValue(); + if (value instanceof Window && windowId.equals(((Window) value).attempt().getWindowId())) { + map.delete(key); + } } } finally { map.unlock(key); @@ -96,19 +112,24 @@ private K key(Object principal) { return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); } - private boolean expired(EntryView entry, long deadline, long now) { + private boolean expired(EntryView entry, long deadline, long now) { long lastActivity = Math.max(entry.getCreationTime(), entry.getLastAccessTime()); return deadline <= now || (maxIdleMillis > 0 && now - lastActivity >= maxIdleMillis); } - private static long ttlDeadline(EntryView entry) { - long saved = entry.getValue().ttlDeadline(); - if (saved != UNSET_DEADLINE) { - return saved; + private static long ttlDeadline(EntryView entry) { + Object value = entry.getValue(); + if (value instanceof Window) { + long saved = ((Window) value).ttlDeadline(); + if (saved != UNSET_DEADLINE) { + return saved; + } } long ttl = entry.getTtl(); - return ttl <= 0 || ttl == NO_DEADLINE ? NO_DEADLINE : entry.getCreationTime() + ttl; + // Hazelcast 3.12 measures a written entry's TTL from its most recent update. + long ttlStart = Math.max(entry.getCreationTime(), entry.getLastUpdateTime()); + return ttl <= 0 || ttl > NO_DEADLINE - ttlStart ? NO_DEADLINE : ttlStart + ttl; } private record Window(Attempt attempt, long ttlDeadline) implements Serializable { diff --git a/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java b/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java index f231a20f..8d6d1bd8 100644 --- a/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java @@ -23,6 +23,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -156,6 +157,36 @@ public void preservesIdleExpiryForAThinClientWithStatisticsDisabled() throws Exc assertNotEquals(first.getWindowId(), renewed.getWindowId()); } + @Test + public void migratesLegacyCounterAndKeepsItsProviderDeadline() throws Exception { + String principal = "legacy"; + IMap map = first.getMap("ttl"); + map.set(principal, new AtomicInteger(2), 6, TimeUnit.SECONDS); + long created = map.getEntryView(principal).getCreationTime(); + await(created + 1100L); + map.set(principal, new AtomicInteger(3), 6, TimeUnit.SECONDS); + assertTrue("fixture must have a later update timestamp", map.getEntryView(principal).getLastUpdateTime() > created); + long originalDeadline = map.getEntryView(principal).getExpirationTime(); + Hazelcast3CredentialRetryStore remoteStore = store(client, "ttl"); + Hazelcast3CredentialRetryStore memberStore = store(first, "ttl"); + + Attempt adopted = remoteStore.reserve(principal); + assertEquals(4, adopted.getCount()); + assertEquals(originalDeadline, map.getEntryView(principal).getExpirationTime()); + memberStore.clearIfCurrent(principal, "stale"); + Attempt next = memberStore.reserve(principal); + assertEquals(5, next.getCount()); + assertEquals(adopted.getWindowId(), next.getWindowId()); + assertEquals(originalDeadline, map.getEntryView(principal).getExpirationTime()); + + String unconverted = "unconverted"; + map.set(unconverted, new AtomicInteger(2), 6, TimeUnit.SECONDS); + long unconvertedDeadline = map.getEntryView(unconverted).getExpirationTime(); + remoteStore.clearIfCurrent(unconverted, "stale"); + assertEquals(unconvertedDeadline, map.getEntryView(unconverted).getExpirationTime()); + assertEquals(2, ((AtomicInteger) map.getEntryView(unconverted).getValue()).get()); + } + private static Hazelcast3CredentialRetryStore store(HazelcastInstance instance, String mapName) { int maxIdle = first.getConfig().findMapConfig(mapName).getMaxIdleSeconds(); return new Hazelcast3CredentialRetryStore<>(instance, mapName, maxIdle, Object::toString); From b2a9e4a6a77ec8da0b67df1fa9bc0d13868aa20b Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:58:53 +0800 Subject: [PATCH 22/50] Migrate active credential retry windows in JCache regions --- README.md | 2 + README.zh-CN.md | 2 + .../jcache/JCacheCredentialRetryStore.java | 46 +++++++++++++------ ...heCredentialRetryStoreIntegrationTest.java | 34 ++++++++++++++ .../SpringJCacheCredentialRetryStores.java | 8 +--- ...ngCredentialRetryStoreIntegrationTest.java | 10 ++-- 6 files changed, 78 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 58f2ac49..3c13cf17 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,8 @@ For an existing Ehcache 2 retry cache, stop all legacy clients of that region be For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. +For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index 118d5d6a..98e76459 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -202,6 +202,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 +对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java index aa638f4e..40d45012 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import javax.cache.Cache; import javax.cache.configuration.CompleteConfiguration; import javax.cache.expiry.Duration; @@ -9,6 +10,7 @@ import javax.cache.processor.EntryProcessor; import javax.cache.processor.MutableEntry; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.apache.shiro.cache.CacheException; /** * Shared retry state in a dedicated JCache with a fixed creation expiry. @@ -16,16 +18,24 @@ */ public final class JCacheCredentialRetryStore implements CredentialRetryStore { - private final Cache cache; + private final Cache cache; /** * @param cache shared retry cache using store-by-value and a nonzero creation expiry * or eternal expiry. Its expiry policy must leave the deadline unchanged * on both access and update. All cluster members must have this module. + * To migrate legacy counters, reuse a region that accepts both value + * types after stopping all legacy clients. */ - public JCacheCredentialRetryStore(Cache cache) { - this.cache = Objects.requireNonNull(cache, "cache"); - CompleteConfiguration configuration = cache.getConfiguration(CompleteConfiguration.class); + @SuppressWarnings("unchecked") + public JCacheCredentialRetryStore(Cache cache) { + CompleteConfiguration configuration = + Objects.requireNonNull(cache, "cache").getConfiguration(CompleteConfiguration.class); + if (!configuration.getValueType().isAssignableFrom(Attempt.class)) { + throw new IllegalArgumentException("JCache retry region must accept credential retry attempts"); + } + // Provider configuration validates the values that the entry processor writes. + this.cache = (Cache) cache; ExpiryPolicy policy = configuration.getExpiryPolicyFactory().create(); Duration creation = policy.getExpiryForCreation(); if (!configuration.isStoreByValue() || Objects.isNull(creation) || creation.isZero() @@ -44,18 +54,26 @@ public void clearIfCurrent(Object principal, String windowId) { cache.invoke(principal, Clear.INSTANCE, Objects.requireNonNull(windowId, "windowId")); } - private enum Reserve implements EntryProcessor { + private enum Reserve implements EntryProcessor { INSTANCE; @Override - public Attempt process(MutableEntry entry, Object... arguments) { - Attempt current = entry.getValue(); + public Attempt process(MutableEntry entry, Object... arguments) { + Object value = entry.getValue(); Attempt next; - if (Objects.isNull(current)) { + if (Objects.isNull(value)) { next = new Attempt((String) arguments[0], 1); - } else if (current.getCount() == Integer.MAX_VALUE) { - return current; + } else if (value instanceof AtomicInteger) { + int count = ((AtomicInteger) value).get(); + if (count < 0) { + throw new CacheException("Legacy credential retry count is negative"); + } + next = new Attempt((String) arguments[0], count == Integer.MAX_VALUE ? count : count + 1); } else { + Attempt current = (Attempt) value; + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } next = new Attempt(current.getWindowId(), current.getCount() + 1); } entry.setValue(next); @@ -63,13 +81,13 @@ public Attempt process(MutableEntry entry, Object... arguments) } } - private enum Clear implements EntryProcessor { + private enum Clear implements EntryProcessor { INSTANCE; @Override - public Void process(MutableEntry entry, Object... arguments) { - Attempt current = entry.getValue(); - if (Objects.nonNull(current) && current.getWindowId().equals(arguments[0])) { + public Void process(MutableEntry entry, Object... arguments) { + Object value = entry.getValue(); + if (value instanceof Attempt && ((Attempt) value).getWindowId().equals(arguments[0])) { entry.remove(); } return null; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index 5af4a109..c50feac4 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.configuration.Factory; @@ -127,6 +128,39 @@ public void preservesExpiryAcrossUpdatesAndRejectsStaleReset() throws Exception assertNull(cache.get("alice")); } + @Test + public void migratesStoredLegacyCounterAcrossMembersWithoutRestartingExpiry() throws Exception { + String region = "legacy-expiration"; + Cache cache = firstManager.createCache(region, new MutableConfiguration() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 3))) + .setStoreByValue(true)); + cache.put("alice", new AtomicInteger(3)); + long start = System.nanoTime(); + JCacheCredentialRetryStore first = new JCacheCredentialRetryStore(firstManager.getCache(region)); + JCacheCredentialRetryStore second = new JCacheCredentialRetryStore(secondManager.getCache(region)); + + first.clearIfCurrent("alice", "stale"); + assertEquals(3, ((AtomicInteger) cache.get("alice")).get()); + awaitElapsed(start, 1400); + Attempt adopted = second.reserve("alice"); + assertEquals(4, adopted.getCount()); + Attempt next = first.reserve("alice"); + assertEquals(5, next.getCount()); + assertEquals(adopted.getWindowId(), next.getWindowId()); + awaitElapsed(start, 3300); + assertNull(cache.get("alice")); + } + + @Test + public void rejectsTypedLegacyRegionBeforeItsFirstReservation() { + Cache cache = firstManager.createCache("legacy-only", + new MutableConfiguration() + .setTypes(Object.class, AtomicInteger.class) + .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf())); + assertThrows(IllegalArgumentException.class, () -> new JCacheCredentialRetryStore(cache)); + } + @Test public void rejectsCacheWhosePolicyRestartsExpiryOnUpdate() { Cache cache = createCache("sliding", diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java index e6cc0fc7..90a09855 100644 --- a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java @@ -1,8 +1,6 @@ package org.apache.shiro.biz.cache.spring; -import javax.cache.configuration.Configuration; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; -import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.apache.shiro.biz.cache.jcache.JCacheCredentialRetryStore; import org.springframework.cache.Cache; @@ -22,10 +20,6 @@ public static CredentialRetryStore fromCache(Cache cache) { throw new IllegalArgumentException("Spring retry cache must expose a JCache region"); } - Configuration configuration = nativeCache.getConfiguration(Configuration.class); - if (!configuration.getValueType().isAssignableFrom(Attempt.class)) { - throw new IllegalArgumentException("JCache retry region must accept credential retry attempts"); - } - return new JCacheCredentialRetryStore((javax.cache.Cache) nativeCache); + return new JCacheCredentialRetryStore((javax.cache.Cache) nativeCache); } } diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java index d90e5bef..fd71523b 100644 --- a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -16,6 +16,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.cache.Cache; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.EternalExpiryPolicy; import org.apache.shiro.authc.ExcessiveAttemptsException; @@ -135,17 +137,19 @@ public void unwrapsSpringJCacheThroughTheShiroCacheManager() { HazelcastInstance member = Hazelcast.newHazelcastInstance(config); try (HazelcastServerCachingProvider provider = new HazelcastServerCachingProvider(member); javax.cache.CacheManager nativeManager = provider.getCacheManager()) { - nativeManager.createCache(REGION, new MutableConfiguration() - .setTypes(Object.class, Attempt.class) + Cache region = nativeManager.createCache(REGION, new MutableConfiguration() + .setTypes(Object.class, Object.class) .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf())); + region.put("principal", new AtomicInteger(3)); JCacheCacheManager spring = new JCacheCacheManager(nativeManager); spring.afterPropertiesSet(); SpringCacheManager shiro = new SpringCacheManager(spring); CredentialRetryStore a = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache); CredentialRetryStore b = shiro.getCredentialRetryStore(REGION, SpringJCacheCredentialRetryStores::fromCache); Attempt initial = a.reserve("principal"); + assertEquals(4, initial.getCount()); assertEquals(initial.getWindowId(), b.reserve("principal").getWindowId()); - assertEquals(2, nativeManager.getCache(REGION, Object.class, Attempt.class).get("principal").getCount()); + assertEquals(5, ((Attempt) region.get("principal")).getCount()); b.clearIfCurrent("principal", initial.getWindowId()); assertEquals(1, a.reserve("principal").getCount()); } finally { From 632c024efc946b304ed654a00cede34cd3177e46 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:07:37 +0800 Subject: [PATCH 23/50] Preserve Spring Redis retry deadlines during exclusive cutover --- README.md | 2 + README.zh-CN.md | 2 + .../redis/RedisCredentialRetryStore.java | 36 ++++++++++ ...isCredentialRetryStoreIntegrationTest.java | 13 ++++ ...SpringDataRedis4CredentialRetryStores.java | 63 ++++++++++++++++++ ...4CredentialRetryStoresIntegrationTest.java | 24 +++++++ .../SpringDataRedisCredentialRetryStores.java | 65 +++++++++++++++++++ ...ngCredentialRetryStoreIntegrationTest.java | 34 ++++++++++ 8 files changed, 239 insertions(+) diff --git a/README.md b/README.md index 3c13cf17..6fee0f21 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,8 @@ For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. +For Spring Data Redis, pause all old and new retry clients during cutover. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index 98e76459..a3a81e78 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -204,6 +204,8 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。 +对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java index 2250e3b6..c094a724 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -86,6 +86,25 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { end return '0' """; + private static final String IMPORT_LEGACY = """ + local key = KEYS[1] + if redis.call('EXISTS', key) == 1 then + return '0' + end + if ARGV[3] ~= '0' then + redis.replicate_commands() + local time = redis.call('TIME') + local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) + if tonumber(ARGV[3]) <= now then + return '0' + end + end + redis.call('HSET', key, 'window', ARGV[1], 'count', ARGV[2]) + if ARGV[3] ~= '0' then + redis.call('PEXPIREAT', key, ARGV[3]) + end + return '1' + """; private final ScriptExecutor executor; private final String namespace; @@ -195,6 +214,23 @@ public void clearIfCurrent(Object principal, String windowId) { executor.eval(CLEAR, List.of(key(principal)), List.of(windowId)); } + /** + * Imports a fixed-expiry counter into an empty destination key during an exclusive cutover. + * Run the import while legacy and destination clients are stopped. + * + * @param principal principal to migrate + * @param count persisted count before the next reservation + * @param deadlineMillis absolute Redis expiry in epoch milliseconds, or zero for a persistent key + * @return true when an unexpired counter was imported + */ + public boolean importFixedWindow(Object principal, int count, long deadlineMillis) { + if (count < 0 || deadlineMillis < 0) { + throw new IllegalArgumentException("Legacy count and deadline must be nonnegative"); + } + return "1".equals(executor.eval(IMPORT_LEGACY, List.of(key(principal)), + List.of(UUID.randomUUID().toString(), Integer.toString(count), Long.toString(deadlineMillis)))); + } + private String key(Object principal) { String encoded = Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); return namespace + ":" + encoded; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java index 485394f5..0f3f5897 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java @@ -20,6 +20,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -92,6 +93,18 @@ public void staleSuccessCannotClearNewWindowAfterRedisExpiry() throws Exception assertEquals(1, store.reserve("alice").getCount()); } + @Test + public void importsPersistentZeroCounterAndRejectsAnAlreadyExpiredWindow() { + RedisCredentialRetryStore store = newStore(Duration.ofSeconds(20)); + assertFalse(store.importFixedWindow("expired", 3, 1)); + assertEquals("0", redis("EXISTS", key("expired"))); + assertTrue(store.importFixedWindow("persistent", 0, 0)); + assertEquals(1, store.reserve("persistent").getCount()); + assertEquals("-1", redis("PTTL", key("persistent"))); + assertFalse(store.importFixedWindow("persistent", 99, 0)); + assertEquals(2, store.reserve("persistent").getCount()); + } + @Test public void preservesConfiguredPersistenceAndSaturatesCount() { RedisCredentialRetryStore store = newStore(Duration.ZERO); diff --git a/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java b/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java index aad6c991..cd2052c4 100644 --- a/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java +++ b/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java @@ -1,5 +1,6 @@ package org.apache.shiro.biz.cache.spring.redis4; +import java.nio.ByteBuffer; import java.time.Duration; import java.util.List; import java.util.Objects; @@ -17,11 +18,28 @@ import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.serializer.StringRedisSerializer; +import org.springframework.data.redis.util.ByteUtils; /** Creates retry stores for Spring Data Redis 4 cache regions. */ public final class SpringDataRedis4CredentialRetryStores { private static final StringRedisSerializer STRINGS = StringRedisSerializer.UTF_8; + private static final String SNAPSHOT_LEGACY = """ + local value = redis.call('GET', KEYS[1]) + if not value then + return {} + end + local ttl = redis.call('PTTL', KEYS[1]) + if ttl == -2 then + return {} + end + if ttl == -1 then + return {value, 0} + end + local time = redis.call('TIME') + local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) + return {value, now + ttl} + """; private SpringDataRedis4CredentialRetryStores() { } @@ -37,6 +55,46 @@ private SpringDataRedis4CredentialRetryStores() { */ public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory connectionFactory, String namespace, Function principalKey) { + return createStore(unwrap(cache), connectionFactory, namespace, principalKey); + } + + /** + * Copies one legacy Spring Redis counter during an exclusive cache cutover. + * Complete the import before either old or new matchers resume using the region. + * + * @param cache existing Spring Redis retry cache + * @param connectionFactory connection factory used by the source and destination + * @param namespace distinct destination namespace used by the new retry store + * @param principalKey destination principal encoding used by the new retry store + * @param principal original string principal in the source region + * @return true when the provider copied a live counter into an empty destination key + */ + public static boolean migrateLegacyWindow(Cache cache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey, + String principal) { + RedisCache source = unwrap(cache); + RedisCredentialRetryStore destination = createStore(source, connectionFactory, namespace, principalKey); + RedisCacheConfiguration configuration = source.getCacheConfiguration(); + Objects.requireNonNull(principal, "principal"); + String sourceKey = configuration.usePrefix() + ? configuration.getKeyPrefixFor(source.getName()) + principal : principal; + byte[] serializedKey = ByteUtils.getBytes(configuration.getKeySerializationPair().write(sourceKey)); + List snapshot; + try (RedisConnection connection = connectionFactory.getConnection()) { + snapshot = connection.scriptingCommands().eval( + STRINGS.serialize(SNAPSHOT_LEGACY), ReturnType.MULTI, 1, serializedKey); + } + if (snapshot.isEmpty()) { + return false; + } + Object value = configuration.getValueSerializationPair().read(ByteBuffer.wrap((byte[]) snapshot.get(0))); + if (!(value instanceof AtomicInteger)) { + throw new IllegalStateException("Spring Redis legacy retry entry must contain an AtomicInteger"); + } + return destination.importFixedWindow(principal, ((AtomicInteger) value).get(), (Long) snapshot.get(1)); + } + + private static RedisCache unwrap(Cache cache) { Cache target = cache; while (target instanceof TransactionAwareCacheDecorator decorator) { target = decorator.getTargetCache(); @@ -44,6 +102,11 @@ public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory if (!(target instanceof RedisCache redisCache)) { throw new IllegalArgumentException("Spring retry cache must be backed by Spring Data Redis"); } + return redisCache; + } + + private static RedisCredentialRetryStore createStore(RedisCache redisCache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey) { Objects.requireNonNull(connectionFactory, "connectionFactory"); RedisCacheConfiguration config = redisCache.getCacheConfiguration(); diff --git a/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java index cfaf4677..fe816959 100644 --- a/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java +++ b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java @@ -22,6 +22,7 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -53,6 +54,29 @@ public static void disconnect() { } } + @Test + public void copiesLegacyWindowBeforeIdlePolicyRefreshesIt() { + var config = RedisCacheConfiguration.defaultCacheConfig() + .computePrefixWith(name -> namespace + ":legacy:") + .entryTtl((key, value) -> Objects.isNull(value) ? Duration.ofSeconds(30) : Duration.ofSeconds(5)) + .enableTimeToIdle(); + var manager = RedisCacheManager.builder(first).cacheDefaults(config).transactionAware().build(); + manager.afterPropertiesSet(); + var source = manager.getCache(REGION); + source.put("principal", new AtomicInteger(3)); + long originalDeadline = expiry("legacy:principal"); + + assertTrue(SpringDataRedis4CredentialRetryStores.migrateLegacyWindow( + source, first, namespace, Object::toString, "principal")); + assertEquals(originalDeadline, expiry("legacy:principal")); + assertEquals(originalDeadline, expiry("principal")); + assertFalse(SpringDataRedis4CredentialRetryStores.migrateLegacyWindow( + source, second, namespace, Object::toString, "principal")); + Attempt next = store(second, config).reserve("principal"); + assertEquals(4, next.getCount()); + assertTrue(expiry("principal") > originalDeadline); + } + @Test public void evaluatesPerKeyTtlOnceWhenAWindowIsCreated() { AtomicInteger creationCalls = new AtomicInteger(); diff --git a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java index b52711d5..adf9942e 100644 --- a/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java @@ -1,7 +1,9 @@ package org.apache.shiro.biz.cache.spring; +import java.nio.ByteBuffer; import java.util.List; import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Stream; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; @@ -9,15 +11,33 @@ import org.springframework.cache.Cache; import org.springframework.cache.transaction.TransactionAwareCacheDecorator; import org.springframework.data.redis.cache.RedisCache; +import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.serializer.StringRedisSerializer; +import org.springframework.data.redis.util.ByteUtils; /** Creates retry stores for Spring Data Redis 2.7 cache regions. */ public final class SpringDataRedisCredentialRetryStores { private static final StringRedisSerializer STRINGS = StringRedisSerializer.UTF_8; + private static final String SNAPSHOT_LEGACY = """ + local value = redis.call('GET', KEYS[1]) + if not value then + return {} + end + local ttl = redis.call('PTTL', KEYS[1]) + if ttl == -2 then + return {} + end + if ttl == -1 then + return {value, 0} + end + local time = redis.call('TIME') + local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) + return {value, now + ttl} + """; private SpringDataRedisCredentialRetryStores() { } @@ -33,6 +53,46 @@ private SpringDataRedisCredentialRetryStores() { */ public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory connectionFactory, String namespace, Function principalKey) { + return createStore(unwrap(cache), connectionFactory, namespace, principalKey); + } + + /** + * Copies one legacy Spring Redis counter during an exclusive cache cutover. + * Complete the import before either old or new matchers resume using the region. + * + * @param cache existing Spring Redis retry cache + * @param connectionFactory connection factory used by the source and destination + * @param namespace distinct destination namespace used by the new retry store + * @param principalKey destination principal encoding used by the new retry store + * @param principal original string principal in the source region + * @return true when the provider copied a live counter into an empty destination key + */ + public static boolean migrateLegacyWindow(Cache cache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey, + String principal) { + RedisCache source = unwrap(cache); + RedisCredentialRetryStore destination = createStore(source, connectionFactory, namespace, principalKey); + RedisCacheConfiguration configuration = source.getCacheConfiguration(); + Objects.requireNonNull(principal, "principal"); + String sourceKey = configuration.usePrefix() + ? configuration.getKeyPrefixFor(source.getName()) + principal : principal; + byte[] serializedKey = ByteUtils.getBytes(configuration.getKeySerializationPair().write(sourceKey)); + List snapshot; + try (RedisConnection connection = connectionFactory.getConnection()) { + snapshot = connection.scriptingCommands().eval( + STRINGS.serialize(SNAPSHOT_LEGACY), ReturnType.MULTI, 1, serializedKey); + } + if (snapshot.isEmpty()) { + return false; + } + Object value = configuration.getValueSerializationPair().read(ByteBuffer.wrap((byte[]) snapshot.get(0))); + if (!(value instanceof AtomicInteger)) { + throw new IllegalStateException("Spring Redis legacy retry entry must contain an AtomicInteger"); + } + return destination.importFixedWindow(principal, ((AtomicInteger) value).get(), (Long) snapshot.get(1)); + } + + private static RedisCache unwrap(Cache cache) { Cache target = cache; while (target instanceof TransactionAwareCacheDecorator decorator) { target = decorator.getTargetCache(); @@ -40,6 +100,11 @@ public static CredentialRetryStore fromCache(Cache cache, RedisConnectionFactory if (!(target instanceof RedisCache redisCache)) { throw new IllegalArgumentException("Spring retry cache must be backed by Spring Data Redis"); } + return redisCache; + } + + private static RedisCredentialRetryStore createStore(RedisCache redisCache, RedisConnectionFactory connectionFactory, + String namespace, Function principalKey) { Objects.requireNonNull(connectionFactory, "connectionFactory"); return new RedisCredentialRetryStore( (script, keys, args) -> eval(connectionFactory, script, keys, args), diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java index fd71523b..797fb355 100644 --- a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import javax.cache.Cache; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.EternalExpiryPolicy; @@ -99,6 +100,39 @@ public void springRedisManagersShareAnAtomicRetryWindowWithTheirConfiguredTtl() } } + @Test + public void importsSpringRedisLegacyCountersWithTheOriginalDeadline() throws Exception { + String port = System.getProperty("shiro.redis.test.port"); + assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + String namespace = "test:spring-migrate:" + UUID.randomUUID(); + LettuceConnectionFactory factory = connectionFactory(port); + try { + String legacyPrefix = namespace + ":legacy:"; + RedisCacheManager manager = RedisCacheManager.builder(factory) + .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig() + .computePrefixWith(name -> legacyPrefix).entryTtl(Duration.ofSeconds(5))) + .transactionAware().build(); + manager.afterPropertiesSet(); + org.springframework.cache.Cache source = manager.getCache(REGION); + source.put("principal", new AtomicInteger(3)); + long deadline = expiry(factory, namespace + ":legacy"); + assertTrue(deadline > System.currentTimeMillis()); + + Function encoding = Object::toString; + assertTrue(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "principal")); + assertFalse(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "principal")); + assertFalse(SpringDataRedisCredentialRetryStores.migrateLegacyWindow(source, factory, namespace, encoding, "missing")); + assertEquals(3, source.get("principal", AtomicInteger.class).get()); + assertEquals(deadline, expiry(factory, namespace)); + + Attempt next = redisStore(factory, namespace, false).reserve("principal"); + assertEquals(4, next.getCount()); + assertEquals(deadline, expiry(factory, namespace)); + } finally { + factory.destroy(); + } + } + @Test public void springRedisEnforcesTheRetryLimitAcrossMatcherInstances() { String port = System.getProperty("shiro.redis.test.port"); From 2dca2ca8d962362d606358cacfab7aa5e97281d6 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:13:03 +0800 Subject: [PATCH 24/50] Verify Spring Redis retry cutover across cluster primaries --- README.md | 2 +- README.zh-CN.md | 2 +- ...4CredentialRetryStoresIntegrationTest.java | 51 +++++++++++++++---- ...ngCredentialRetryStoreIntegrationTest.java | 42 ++++++++++++--- 4 files changed, 80 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 6fee0f21..3bf9a12b 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. -For Spring Data Redis, pause all old and new retry clients during cutover. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. +For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. ## 8. Core Usage / API diff --git a/README.zh-CN.md b/README.zh-CN.md index a3a81e78..6ea02af8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -204,7 +204,7 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。 -对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 +对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 ## 8. Core Usage / API diff --git a/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java index fe816959..cbf4384a 100644 --- a/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java +++ b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java @@ -1,6 +1,7 @@ package org.apache.shiro.biz.cache.spring.redis4; import java.time.Duration; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -16,6 +17,8 @@ import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter.TtlFunction; +import org.springframework.data.redis.connection.RedisClusterConfiguration; +import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @@ -24,24 +27,27 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; public class SpringDataRedis4CredentialRetryStoresIntegrationTest { + private static final String CLUSTER_NODES = "shiro.redis.test.cluster.nodes"; private static final String REGION = "credential-retry"; private static final StringRedisSerializer UTF_8 = StringRedisSerializer.UTF_8; private static LettuceConnectionFactory first; private static LettuceConnectionFactory second; - private final String namespace = "test:spring-redis4-retry:" + UUID.randomUUID(); + private final String namespace = "{retry-current}:test:spring-redis4-retry:" + UUID.randomUUID(); @BeforeClass public static void connect() { String port = System.getProperty("shiro.redis.test.port"); - assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); - first = connectionFactory(port); - second = connectionFactory(port); + String nodes = System.getProperty(CLUSTER_NODES); + assumeTrue("Supply an isolated Redis port or cluster nodes", Objects.nonNull(port) || Objects.nonNull(nodes)); + first = migrationConnectionFactory(port, nodes); + second = migrationConnectionFactory(port, nodes); } @AfterClass @@ -56,19 +62,22 @@ public static void disconnect() { @Test public void copiesLegacyWindowBeforeIdlePolicyRefreshesIt() { + String legacyPrefix = "{retry-legacy}:test:" + UUID.randomUUID() + ":"; + verifyDifferentOwners(first, legacyPrefix + "principal", namespace + ":principal"); var config = RedisCacheConfiguration.defaultCacheConfig() - .computePrefixWith(name -> namespace + ":legacy:") + .computePrefixWith(name -> legacyPrefix) .entryTtl((key, value) -> Objects.isNull(value) ? Duration.ofSeconds(30) : Duration.ofSeconds(5)) .enableTimeToIdle(); var manager = RedisCacheManager.builder(first).cacheDefaults(config).transactionAware().build(); manager.afterPropertiesSet(); var source = manager.getCache(REGION); - source.put("principal", new AtomicInteger(3)); - long originalDeadline = expiry("legacy:principal"); + assertNull(source.putIfAbsent("principal", new AtomicInteger(3))); + long originalDeadline = expiryKey(legacyPrefix + "principal"); + assertTrue(originalDeadline > System.currentTimeMillis()); assertTrue(SpringDataRedis4CredentialRetryStores.migrateLegacyWindow( source, first, namespace, Object::toString, "principal")); - assertEquals(originalDeadline, expiry("legacy:principal")); + assertEquals(originalDeadline, expiryKey(legacyPrefix + "principal")); assertEquals(originalDeadline, expiry("principal")); assertFalse(SpringDataRedis4CredentialRetryStores.migrateLegacyWindow( source, second, namespace, Object::toString, "principal")); @@ -181,10 +190,34 @@ private CredentialRetryStore store(LettuceConnectionFactory factory, RedisCacheC } private long expiry(String principal) { + return expiryKey(namespace + ":" + principal); + } + + private long expiryKey(String key) { try (RedisConnection connection = first.getConnection()) { return connection.scriptingCommands().eval( UTF_8.serialize("return redis.call('PEXPIRETIME', KEYS[1])"), - ReturnType.INTEGER, 1, UTF_8.serialize(namespace + ":" + principal)); + ReturnType.INTEGER, 1, UTF_8.serialize(key)); + } + } + + private static LettuceConnectionFactory migrationConnectionFactory(String port, String nodes) { + if (Objects.isNull(nodes)) { + return connectionFactory(port); + } + LettuceConnectionFactory factory = new LettuceConnectionFactory( + new RedisClusterConfiguration(Arrays.asList(nodes.split(",")))); + factory.afterPropertiesSet(); + return factory; + } + + private static void verifyDifferentOwners(LettuceConnectionFactory factory, String source, String destination) { + if (Objects.nonNull(System.getProperty(CLUSTER_NODES))) { + try (RedisClusterConnection cluster = factory.getClusterConnection()) { + String sourceOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(source)).getId(); + String destinationOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(destination)).getId(); + assertNotEquals("Migration must cross Redis primary nodes", sourceOwner, destinationOwner); + } } } diff --git a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java index 797fb355..20c8fbc0 100644 --- a/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Arrays; import java.util.Objects; import java.util.Set; import java.util.UUID; @@ -36,6 +37,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisClusterConfiguration; +import org.springframework.data.redis.connection.RedisClusterConnection; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.ReturnType; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; @@ -50,6 +53,7 @@ public class SpringCredentialRetryStoreIntegrationTest { + private static final String CLUSTER_NODES = "shiro.redis.test.cluster.nodes"; private static final String REGION = "credential-retry"; private static final StringRedisSerializer UTF_8 = StringRedisSerializer.UTF_8; @@ -103,11 +107,13 @@ public void springRedisManagersShareAnAtomicRetryWindowWithTheirConfiguredTtl() @Test public void importsSpringRedisLegacyCountersWithTheOriginalDeadline() throws Exception { String port = System.getProperty("shiro.redis.test.port"); - assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); - String namespace = "test:spring-migrate:" + UUID.randomUUID(); - LettuceConnectionFactory factory = connectionFactory(port); + String nodes = System.getProperty(CLUSTER_NODES); + assumeTrue("Supply an isolated Redis port or cluster nodes", Objects.nonNull(port) || Objects.nonNull(nodes)); + String namespace = "{retry-current}:test:spring-migrate:" + UUID.randomUUID(); + LettuceConnectionFactory factory = migrationConnectionFactory(port, nodes); try { - String legacyPrefix = namespace + ":legacy:"; + String legacyPrefix = "{retry-legacy}:test:spring-migrate:" + UUID.randomUUID() + ":"; + verifyDifferentOwners(factory, legacyPrefix + "principal", namespace + ":principal"); RedisCacheManager manager = RedisCacheManager.builder(factory) .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig() .computePrefixWith(name -> legacyPrefix).entryTtl(Duration.ofSeconds(5))) @@ -115,7 +121,7 @@ public void importsSpringRedisLegacyCountersWithTheOriginalDeadline() throws Exc manager.afterPropertiesSet(); org.springframework.cache.Cache source = manager.getCache(REGION); source.put("principal", new AtomicInteger(3)); - long deadline = expiry(factory, namespace + ":legacy"); + long deadline = expiryKey(factory, legacyPrefix + "principal"); assertTrue(deadline > System.currentTimeMillis()); Function encoding = Object::toString; @@ -219,6 +225,26 @@ private static AnnotationConfigApplicationContext matcherContext( return context; } + private static LettuceConnectionFactory migrationConnectionFactory(String port, String nodes) { + if (Objects.isNull(nodes)) { + return connectionFactory(port); + } + LettuceConnectionFactory factory = new LettuceConnectionFactory( + new RedisClusterConfiguration(Arrays.asList(nodes.split(",")))); + factory.afterPropertiesSet(); + return factory; + } + + private static void verifyDifferentOwners(LettuceConnectionFactory factory, String source, String destination) { + if (Objects.nonNull(System.getProperty(CLUSTER_NODES))) { + try (RedisClusterConnection cluster = factory.getClusterConnection()) { + String sourceOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(source)).getId(); + String destinationOwner = cluster.clusterGetNodeForKey(UTF_8.serialize(destination)).getId(); + assertNotEquals("Migration must cross Redis primary nodes", sourceOwner, destinationOwner); + } + } + } + private static LettuceConnectionFactory connectionFactory(String port) { LettuceConnectionFactory factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port)); factory.afterPropertiesSet(); @@ -240,10 +266,14 @@ private static CredentialRetryStore redisStore(LettuceConnectionFactory factory, } private static long expiry(LettuceConnectionFactory factory, String namespace) { + return expiryKey(factory, namespace + ":principal"); + } + + private static long expiryKey(LettuceConnectionFactory factory, String key) { try (RedisConnection connection = factory.getConnection()) { return connection.scriptingCommands().eval( UTF_8.serialize("return redis.call('PEXPIRETIME', KEYS[1])"), - ReturnType.INTEGER, 1, UTF_8.serialize(namespace + ":principal")); + ReturnType.INTEGER, 1, UTF_8.serialize(key)); } } } From 1f4ae9ac69733bd65996f5d97dbbd7ca97d6fe46 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:21:04 +0800 Subject: [PATCH 25/50] Migrate active J2Cache Redis retry windows from the persisted L2 --- README.md | 2 + README.zh-CN.md | 2 + .../J2CacheLettuceCredentialRetryStore.java | 18 +++- .../J2CacheRedisCredentialRetryStore.java | 21 ++++- .../j2cache/J2CacheRedisLegacyWindows.java | 84 +++++++++++++++++++ ...ceCredentialRetryStoreIntegrationTest.java | 37 ++++++++ ...isCredentialRetryStoreIntegrationTest.java | 33 ++++++++ 7 files changed, 190 insertions(+), 7 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java diff --git a/README.md b/README.md index 3bf9a12b..f8c1cfa4 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,8 @@ For a JCache retry region that already accepts both value types (for example, wi For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. +The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. Non-UTF-8 Jedis hash region keys require a separate migration path. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index 6ea02af8..bcb3bdfc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -206,6 +206,8 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 +J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。非 UTF-8 的 Jedis Hash 区域键需要单独迁移。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java index ba9ae0cc..91b382e5 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java @@ -14,6 +14,7 @@ public final class J2CacheLettuceCredentialRetryStore implements CredentialRetryStore { private final RedisCredentialRetryStore delegate; + private final J2CacheRedisLegacyWindows legacy; /** * @param channel channel using J2Cache's Lettuce L2 provider @@ -30,10 +31,11 @@ public J2CacheLettuceCredentialRetryStore(CacheChannel channel, J2CacheConfig co throw new IllegalArgumentException("J2Cache retry state requires a Lettuce L2 provider"); } Objects.requireNonNull(commands, "commands"); - this.delegate = new RedisCredentialRetryStore( - (script, keys, args) -> commands.eval(script, ScriptOutputType.VALUE, - keys.toArray(String[]::new), args.toArray(String[]::new)), + RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> commands.eval( + script, ScriptOutputType.VALUE, keys.toArray(String[]::new), args.toArray(String[]::new)); + this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "hash")); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, false, scripts); } @Override @@ -45,4 +47,14 @@ public Attempt reserve(Object principal) { public void clearIfCurrent(Object principal, String windowId) { delegate.clearIfCurrent(principal, windowId); } + + /** + * Copies a persisted L2 counter into the dedicated retry namespace during an exclusive cutover. + * + * @param principal original string principal key in the J2Cache retry region + * @return true when a live legacy window was imported into an empty destination + */ + public boolean migrateLegacyWindow(String principal) { + return legacy.migrate(principal, delegate); + } } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java index bd50d6fa..31ec84f4 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java @@ -23,6 +23,7 @@ public final class J2CacheRedisCredentialRetryStore implements CredentialRetryStore { private final RedisCredentialRetryStore delegate; + private final J2CacheRedisLegacyWindows legacy; /** * @param channel channel using the writable Jedis provider @@ -38,9 +39,10 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf throw new IllegalArgumentException("J2Cache Cluster mode requires its native JedisCluster script client"); } RedisClient client = provider.getRedisClient(); - this.delegate = new RedisCredentialRetryStore( - (script, keys, args) -> eval(client, script, keys, args), + RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> eval(client, script, keys, args); + this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, scripts); } /** @@ -56,9 +58,10 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf JedisCluster cluster) { writableProvider(channel); Objects.requireNonNull(cluster, "cluster"); - this.delegate = new RedisCredentialRetryStore( - (script, keys, args) -> (String) cluster.eval(script, keys, args), + RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> (String) cluster.eval(script, keys, args); + this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, scripts); } @Override @@ -71,6 +74,16 @@ public void clearIfCurrent(Object principal, String windowId) { delegate.clearIfCurrent(principal, windowId); } + /** + * Copies a persisted L2 counter into the dedicated retry namespace during an exclusive cutover. + * + * @param principal original string principal key in the J2Cache retry region + * @return true when a live legacy window was imported into an empty destination + */ + public boolean migrateLegacyWindow(String principal) { + return legacy.migrate(principal, delegate); + } + private static RedisCacheProvider writableProvider(CacheChannel channel) { if (channel.getL2Provider() instanceof RedisCacheProvider provider && !(provider instanceof ReadonlyRedisCacheProvider)) { diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java new file mode 100644 index 00000000..54cfffac --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java @@ -0,0 +1,84 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.Objects; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.Level2Cache; +import net.oschina.j2cache.util.SerializationUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.apache.shiro.cache.CacheException; + +/** Reads the persisted L2 counter and its Redis deadline while all retry clients are paused. */ +final class J2CacheRedisLegacyWindows { + + private static final String DEADLINE = String.join("\n", + "local ttl = redis.call('PTTL', KEYS[1])", + "if ttl < 0 then return tostring(ttl) end", + "local time = redis.call('TIME')", + "local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)", + "return string.format('%.0f', now + ttl)"); + + private final CacheChannel channel; + private final J2CacheConfig config; + private final String region; + private final boolean jedis; + private final RedisCredentialRetryStore.ScriptExecutor scripts; + + J2CacheRedisLegacyWindows(CacheChannel channel, J2CacheConfig config, String region, boolean jedis, + RedisCredentialRetryStore.ScriptExecutor scripts) { + this.channel = channel; + this.config = config; + this.region = region; + this.jedis = jedis; + this.scripts = scripts; + } + + boolean migrate(String principal, RedisCredentialRetryStore destination) { + Objects.requireNonNull(principal, "principal"); + String key = redisKey(principal); + Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(region, null); + byte[] bytes = source.getBytes(principal); + if (Objects.isNull(bytes)) { + return false; + } + long deadline = Long.parseLong(scripts.eval(DEADLINE, Collections.singletonList(key), Collections.emptyList())); + if (deadline == -2) { + return false; + } + try { + Object value = SerializationUtils.deserialize(bytes); + if (!(value instanceof AtomicInteger)) { + throw new CacheException("J2Cache legacy retry entry must contain an AtomicInteger"); + } + return destination.importFixedWindow(principal, ((AtomicInteger) value).get(), deadline == -1 ? 0 : deadline); + } catch (IOException ex) { + throw new CacheException("Unable to read the J2Cache legacy retry counter", ex); + } + } + + private String redisKey(String principal) { + Properties redis = config.getL2CacheProperties(); + boolean hash = "hash".equalsIgnoreCase(redis.getProperty("storage", jedis ? "generic" : "hash")); + // Jedis hash storage uses the platform charset and different whitespace rules. + boolean jedisHash = jedis && hash; + String normalizedRegion = jedisHash ? StringUtils.trim(region) : region; + String name = StringUtils.isEmpty(normalizedRegion) ? "_" : region; + String namespace = redis.getProperty("namespace"); + boolean hasNamespace = jedisHash ? StringUtils.isNotEmpty(namespace) + : StringUtils.isNotEmpty(StringUtils.trim(namespace)); + String regionKey = hasNamespace ? namespace + ":" + name : name; + if (jedisHash && !Arrays.equals(regionKey.getBytes(Charset.defaultCharset()), + regionKey.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("The legacy Jedis region key must use UTF-8 for scripted migration"); + } + return hash ? regionKey : regionKey + ":" + principal; + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java index d7728ad6..1e7691da 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java @@ -4,17 +4,22 @@ import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.StatefulRedisConnection; import java.util.Objects; +import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.Level2Cache; +import net.oschina.j2cache.util.SerializationUtils; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -32,6 +37,38 @@ public void requireIsolatedRedis() { port = Integer.parseInt(configured); } + @Test + public void migratesBothL2LayoutsUsingPersistedCountsAndDeadlines() throws Exception { + SerializationUtils.init("java", new Properties()); + RedisClient client = client(); + try (StatefulRedisConnection redis = client.connect()) { + for (String storage : new String[] {"generic", "hash"}) { + J2CacheConfig config = config(true, storage); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + channel.set(REGION, "principal", new AtomicInteger(1)); + Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(REGION, null); + source.put("principal", new AtomicInteger(3), 8L); + assertEquals(1, ((AtomicInteger) channel.get(REGION, "principal").getValue()).get()); + String legacyKey = namespace + ":legacy:" + REGION + ("hash".equals(storage) ? "" : ":principal"); + long deadline = redis.sync().eval("return redis.call('PEXPIRETIME', KEYS[1])", + ScriptOutputType.INTEGER, legacyKey); + J2CacheLettuceCredentialRetryStore store = store(channel, config, redis); + assertTrue(store.migrateLegacyWindow("principal")); + assertFalse(store.migrateLegacyWindow("principal")); + assertFalse(store.migrateLegacyWindow("missing")); + assertEquals(deadline, expiry(redis)); + Attempt next = store.reserve("principal"); + assertEquals(4, next.getCount()); + assertEquals(deadline, expiry(redis)); + assertEquals(3, ((AtomicInteger) source.get("principal")).get()); + store.clearIfCurrent("principal", next.getWindowId()); + } + } + } finally { + client.shutdown(); + } + } + @Test public void independentConnectionsPreserveTheSyncedRegionDeadline() throws Exception { J2CacheConfig config = config(true, "generic"); diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java index 731fc9da..ca7cb4d5 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java @@ -1,18 +1,23 @@ package org.apache.shiro.biz.cache.j2cache; import java.util.Objects; +import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.Level2Cache; +import net.oschina.j2cache.util.SerializationUtils; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -30,6 +35,34 @@ public void requireIsolatedRedis() { port = Integer.parseInt(configured); } + @Test + public void migratesBothL2LayoutsUsingPersistedCountsAndDeadlines() throws Exception { + SerializationUtils.init("java", new Properties()); + try (Jedis redis = new Jedis("127.0.0.1", port)) { + for (String storage : new String[] {"generic", "hash"}) { + J2CacheConfig config = config(true, storage); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + channel.set(REGION, "principal", new AtomicInteger(1)); + Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(REGION, null); + source.put("principal", new AtomicInteger(3), 8L); + assertEquals(1, ((AtomicInteger) channel.get(REGION, "principal").getValue()).get()); + String legacyKey = namespace + ":legacy:" + REGION + ("hash".equals(storage) ? "" : ":principal"); + long deadline = (Long) redis.eval("return redis.call('PEXPIRETIME', KEYS[1])", 1, legacyKey); + J2CacheRedisCredentialRetryStore store = store(channel, config); + assertTrue(store.migrateLegacyWindow("principal")); + assertFalse(store.migrateLegacyWindow("principal")); + assertFalse(store.migrateLegacyWindow("missing")); + assertEquals(deadline, expiry(redis)); + Attempt next = store.reserve("principal"); + assertEquals(4, next.getCount()); + assertEquals(deadline, expiry(redis)); + assertEquals(3, ((AtomicInteger) source.get("principal")).get()); + store.clearIfCurrent("principal", next.getWindowId()); + } + } + } + } + @Test public void twoChannelsShareCountsAndPreserveTheSyncedRegionDeadline() throws Exception { J2CacheConfig config = config(true, "generic"); From 5158e09fb5927df763f4bf8b994d6a83928fd4e1 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:28:50 +0800 Subject: [PATCH 26/50] Migrate legacy Memcached retry counters with their original deadline --- README.md | 2 + README.zh-CN.md | 2 + .../J2CacheMemcachedCredentialRetryStore.java | 66 +++++++-- .../cache/j2cache/MemcachedLegacyWindow.java | 140 ++++++++++++++++++ ...edCredentialRetryStoreIntegrationTest.java | 35 +++++ 5 files changed, 235 insertions(+), 10 deletions(-) create mode 100644 shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java diff --git a/README.md b/README.md index f8c1cfa4..71bf3d7e 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,8 @@ For Spring Data Redis, pause all old and new retry clients and wait for outstand The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. Non-UTF-8 Jedis hash region keys require a separate migration path. +The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Pass the source server that owns the legacy key and accepts unauthenticated Memcached Meta Text on a trusted connection. The adapter reads the value and its remaining TTL together, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. Select source servers using the original key routing. Binary-only or authenticated source servers require a separate migration path. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index bcb3bdfc..c025b2ec 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -208,6 +208,8 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。非 UTF-8 的 Jedis Hash 区域键需要单独迁移。 +J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由传入保存旧值的源节点,该节点需允许在可信连接上使用无需认证的 Memcached Meta Text 协议。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议或需要认证的源节点需要独立迁移方式。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 2c662d6c..0775d03f 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -1,5 +1,8 @@ package org.apache.shiro.biz.cache.j2cache; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -31,6 +34,8 @@ public final class J2CacheMemcachedCredentialRetryStore implements CredentialRet private final String keyPrefix; private final Function principalKey; private final long regionExpiry; + private final String legacyRegion; + private final boolean legacySanitizeKeys; /** * @param channel channel using the xmemcached L2 provider @@ -50,6 +55,8 @@ public J2CacheMemcachedCredentialRetryStore(CacheChannel channel, J2CacheConfig this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); this.keyPrefix = "shiro-retry:" + digest(Objects.requireNonNull(namespace, "namespace")) + ":"; this.regionExpiry = J2CacheRetryExpiry.regionSeconds(channel, region); + this.legacyRegion = region; + this.legacySanitizeKeys = Boolean.parseBoolean(config.getL2CacheProperties().getProperty("sanitizeKeys")); if (regionExpiry < 0 || regionExpiry > Integer.MAX_VALUE || (regionExpiry > MAX_RELATIVE_SECONDS && regionExpiry <= Instant.now().getEpochSecond())) { throw new IllegalArgumentException("The retry region has an invalid Memcached expiry"); @@ -73,12 +80,10 @@ public Attempt reserve(Object principal) { if (window.expiresAt() > 0 && Instant.now().getEpochSecond() >= window.expiresAt()) { next = newWindow(); } else { - Attempt attempt = window.attempt(); - if (attempt.getCount() == Integer.MAX_VALUE) { - return attempt; + if (window.count() == Integer.MAX_VALUE) { + return window.attempt(); } - next = new Window(new Attempt(attempt.getWindowId(), attempt.getCount() + 1), - window.expiresAt()); + next = new Window(window.windowId(), window.count() + 1, window.expiresAt()); } if (client.cas(key, next.expiresAt(), next.encode(), STRINGS, current.getCas())) { return next.attempt(); @@ -101,7 +106,7 @@ public void clearIfCurrent(Object principal, String windowId) { try { for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { GetsResponse current = client.gets(key, STRINGS); - if (Objects.isNull(current) || !windowId.equals(Window.decode(current.getValue()).attempt().getWindowId())) { + if (Objects.isNull(current) || !windowId.equals(Window.decode(current.getValue()).windowId())) { return; } // A past absolute expiry makes the CAS remove only the version that was read. @@ -118,8 +123,39 @@ public void clearIfCurrent(Object principal, String windowId) { throw new CacheException("Unable to clear a Memcached retry window within the conflict limit"); } + /** + * Copies a legacy counter and its deadline during an exclusive cutover. + * Pause old and new clients and drain outstanding writes before importing. + * + * @param principal original string principal in the J2Cache region + * @param source server owning the legacy key, with the Memcached Meta Text protocol enabled + * @return true when the counter was copied to an empty destination + */ + public boolean migrateLegacyWindow(String principal, InetSocketAddress source) { + Objects.requireNonNull(principal, "principal"); + Objects.requireNonNull(source, "source"); + try { + String legacyKey = legacyRegion + ":" + principal; + if (legacySanitizeKeys) { + legacyKey = URLEncoder.encode(legacyKey, StandardCharsets.UTF_8.name()); + } + int timeout = (int) Math.max(1, Math.min(client.getOpTimeout(), Integer.MAX_VALUE)); + MemcachedLegacyWindow legacy = MemcachedLegacyWindow.read(source, legacyKey, timeout); + if (Objects.isNull(legacy) || (legacy.getDeadline() > 0 && legacy.getDeadline() <= Instant.now().getEpochSecond())) { + return false; + } + Window window = new Window(UUID.randomUUID().toString(), legacy.getCount(), legacy.getDeadline()); + return client.add(key(principal), window.expiresAt(), window.encode(), STRINGS); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new CacheException("Interrupted while migrating a Memcached retry window", exception); + } catch (IOException | TimeoutException | MemcachedException exception) { + throw new CacheException("Failed to migrate a Memcached retry window", exception); + } + } + private Window newWindow() { - return new Window(new Attempt(UUID.randomUUID().toString(), 1), initialDeadline()); + return new Window(UUID.randomUUID().toString(), 1, initialDeadline()); } private int initialDeadline() { @@ -147,10 +183,20 @@ private static String digest(String value) { } } - private record Window(Attempt attempt, int expiresAt) { + private record Window(String windowId, int count, int expiresAt) { + + private Window { + if (count < 0 || expiresAt < 0) { + throw new CacheException("Invalid Memcached retry count or expiry"); + } + } + + private Attempt attempt() { + return new Attempt(windowId, count); + } private String encode() { - return expiresAt + ":" + attempt.getCount() + ":" + attempt.getWindowId(); + return expiresAt + ":" + count + ":" + windowId; } private static Window decode(String encoded) { @@ -158,7 +204,7 @@ private static Window decode(String encoded) { if (fields.length != 3) { throw new CacheException("Unexpected Memcached retry window format"); } - return new Window(new Attempt(fields[2], Integer.parseInt(fields[1])), Integer.parseInt(fields[0])); + return new Window(fields[2], Integer.parseInt(fields[1]), Integer.parseInt(fields[0])); } } } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java new file mode 100644 index 00000000..c591f739 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java @@ -0,0 +1,140 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.io.BufferedInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.Value; +import net.oschina.j2cache.util.SerializationUtils; +import net.rubyeye.xmemcached.transcoders.CachedData; +import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.cache.CacheException; + +/** A read-only Memcached meta snapshot of the original J2Cache entry. */ +@Value +class MemcachedLegacyWindow { + + private static final int MAX_COUNTER_BYTES = 65_536; + private static final int MAX_CLOCK_ATTEMPTS = 5; + private static final SerializingTranscoder TRANSCODER = new SerializingTranscoder(); + + int count; + int deadline; + + static MemcachedLegacyWindow read(InetSocketAddress source, String key, int timeoutMillis) throws IOException { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + if (keyBytes.length == 0 || keyBytes.length > 250) { + throw new IllegalArgumentException("Invalid legacy Memcached key length"); + } + String request = "mg " + Base64.getEncoder().encodeToString(keyBytes) + " b t f v u"; + try (Socket socket = new Socket()) { + socket.connect(source, timeoutMillis); + socket.setSoTimeout(timeoutMillis); + DataInputStream input = new DataInputStream(new BufferedInputStream(socket.getInputStream())); + OutputStream output = socket.getOutputStream(); + for (int attempt = 0; attempt < MAX_CLOCK_ATTEMPTS; attempt++) { + long before = time(input, output); + command(output, request); + String response = line(input); + if ("EN".equals(response)) { + return null; + } + String[] fields = StringUtils.split(response); + if (Objects.isNull(fields) || fields.length < 4 || !"VA".equals(fields[0])) { + throw new CacheException("Memcached source does not support meta value and expiry reads"); + } + int bytes = Integer.parseInt(fields[1]); + if (bytes <= 0 || bytes > MAX_COUNTER_BYTES) { + throw new CacheException("Invalid legacy Memcached counter size"); + } + int ttl = Integer.parseInt(flag(fields, 't')); + int flags = Integer.parseUnsignedInt(flag(fields, 'f')); + byte[] payload = new byte[bytes]; + input.readFully(payload); + if (StringUtils.isNotEmpty(line(input))) { + throw new CacheException("Invalid legacy Memcached value terminator"); + } + if (ttl == 0) { + return null; + } + if (ttl == -1) { + return decode(payload, flags, 0); + } + if (ttl < -1) { + throw new CacheException("Invalid legacy Memcached expiry"); + } + // Both samples must belong to the server second in which it computed the remaining TTL. + if (before == time(input, output)) { + return decode(payload, flags, Math.toIntExact(before + ttl)); + } + } + } + throw new CacheException("Could not determine the legacy Memcached deadline at server precision"); + } + + private static MemcachedLegacyWindow decode(byte[] payload, int flags, int deadline) throws IOException { + Object raw = TRANSCODER.decode(new CachedData(flags, payload)); + if (!(raw instanceof byte[])) { + throw new CacheException("Legacy Memcached value must contain J2Cache bytes"); + } + Object counter = SerializationUtils.deserialize((byte[]) raw); + if (!(counter instanceof AtomicInteger) || ((AtomicInteger) counter).get() < 0) { + throw new CacheException("Legacy Memcached value must contain a nonnegative retry counter"); + } + return new MemcachedLegacyWindow(((AtomicInteger) counter).get(), deadline); + } + + private static long time(DataInputStream input, OutputStream output) throws IOException { + command(output, "stats"); + long time = -1; + for (int index = 0; index < 256; index++) { + String response = line(input); + if ("END".equals(response) && time >= 0) { + return time; + } + if (!response.startsWith("STAT ")) { + break; + } + if (response.startsWith("STAT time ")) { + time = Long.parseLong(response.substring("STAT time ".length())); + } + } + throw new CacheException("Memcached source did not report its server clock"); + } + + private static String flag(String[] fields, char name) { + for (int index = 2; index < fields.length; index++) { + if (fields[index].charAt(0) == name && fields[index].length() > 1) { + return fields[index].substring(1); + } + } + throw new CacheException("Memcached source omitted a required meta flag"); + } + + private static void command(OutputStream output, String request) throws IOException { + output.write((request + "\r\n").getBytes(StandardCharsets.US_ASCII)); + output.flush(); + } + + private static String line(DataInputStream input) throws IOException { + StringBuilder result = new StringBuilder(); + while (result.length() < 512) { + int next = input.readUnsignedByte(); + if (next == '\r' && input.readUnsignedByte() == '\n') { + return result.toString(); + } + if (next < 32 || next >= 127) { + break; + } + result.append((char) next); + } + throw new CacheException("Invalid Memcached protocol response"); + } +} diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 5fc7857d..2e07dc4c 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -1,5 +1,6 @@ package org.apache.shiro.biz.cache.j2cache; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; @@ -8,6 +9,7 @@ import java.util.HashSet; import java.util.List; import java.util.Objects; +import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; @@ -15,8 +17,11 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.Level2Cache; +import net.oschina.j2cache.util.SerializationUtils; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; @@ -28,6 +33,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -101,6 +107,35 @@ public void reservesUniqueCountsAcrossChannelsAndClearsOnlyTheMatchingWindow() t } } + @Test + public void copiesTheLegacyCounterWithItsExactDeadlineAndPersistentZero() throws Exception { + SerializationUtils.init("java", new Properties()); + J2CacheConfig config = config(true, "30s"); + config.getL2CacheProperties().setProperty("sanitizeKeys", "true"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(REGION, null); + String principal = "persisted principal"; + int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 15); + source.put(principal, new AtomicInteger(3), deadline); + source.put("persistent", new AtomicInteger(0), 0L); + InetSocketAddress address = AddrUtil.getOneAddress(endpoint); + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + assertTrue(store.migrateLegacyWindow(principal, address)); + assertFalse(store.migrateLegacyWindow(principal, address)); + assertFalse(store.migrateLegacyWindow("missing", address)); + Attempt next = store.reserve(principal); + assertEquals(4, next.getCount()); + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); + assertEquals(3, ((AtomicInteger) source.get(principal)).get()); + assertTrue(store.migrateLegacyWindow("persistent", address)); + Attempt persistent = store.reserve("persistent"); + assertEquals(1, persistent.getCount()); + String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest("persistent"); + assertEquals("0:1:" + persistent.getWindowId(), firstClient.get(persistentKey, new StringTranscoder())); + } + } + @Test public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { J2CacheConfig config = config(true, "4s"); From 28213ab6bbfa96607173f528bee6673a87a1f0f7 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:30:42 +0800 Subject: [PATCH 27/50] test: verify J2Cache retry migration across Redis primaries --- .../J2CacheRedisClusterMigrationTest.java | 141 ++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java new file mode 100644 index 00000000..de366896 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java @@ -0,0 +1,141 @@ +package org.apache.shiro.biz.cache.j2cache; + +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.cluster.RedisClusterClient; +import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import net.oschina.j2cache.CacheChannel; +import net.oschina.j2cache.J2CacheConfig; +import net.oschina.j2cache.Level2Cache; +import net.oschina.j2cache.util.SerializationUtils; +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisCluster; +import redis.clients.util.JedisClusterCRC16; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +public class J2CacheRedisClusterMigrationTest { + + private static final String REGION = "credential-retry"; + private static final String PRINCIPAL = "principal"; + private static final String DESTINATION = "{retry-current}:"; + private static final String LEGACY = "{retry-legacy}:"; + + @Test + public void jedisMigratesGenericAndHashCountersAcrossPrimaries() throws Exception { + String nodes = nodes(); + Set addresses = Arrays.stream(nodes.split(",")).map(HostAndPort::parseString) + .collect(Collectors.toSet()); + try (JedisCluster jedis = new JedisCluster(addresses)) { + verifyLayouts(nodes, "redis", (channel, config, namespace, commands) -> { + var store = new J2CacheRedisCredentialRetryStore( + channel, config, REGION, namespace, Object::toString, jedis); + return new Migration(store, store::migrateLegacyWindow); + }); + } + } + + @Test + public void lettuceMigratesGenericAndHashCountersAcrossPrimaries() throws Exception { + verifyLayouts(nodes(), "lettuce", (channel, config, namespace, commands) -> { + var store = new J2CacheLettuceCredentialRetryStore( + channel, config, REGION, namespace, Object::toString, commands); + return new Migration(store, store::migrateLegacyWindow); + }); + } + + private void verifyLayouts(String nodes, String provider, StoreFactory factory) throws Exception { + SerializationUtils.init("java", new Properties()); + List uris = Arrays.stream(nodes.split(",")).map(node -> RedisURI.create("redis://" + node)) + .collect(Collectors.toList()); + RedisClusterClient client = RedisClusterClient.create(uris); + try (var connection = client.connect()) { + var commands = connection.sync(); + for (String storage : new String[] {"generic", "hash"}) { + String id = UUID.randomUUID().toString(); + String namespace = DESTINATION + id; + String sourceNamespace = LEGACY + id; + String sourceKey = sourceNamespace + ":" + REGION + + ("hash".equals(storage) ? "" : ":" + PRINCIPAL); + String destinationKey = namespace + ":" + PRINCIPAL; + String sourceOwner = client.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(sourceKey)) + .getNodeId(); + String destinationOwner = + client.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(destinationKey)).getNodeId(); + assertNotEquals("Legacy and retry keys must lie on different primaries", sourceOwner, destinationOwner); + J2CacheConfig config = config(nodes, provider, storage, sourceNamespace); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + channel.set(REGION, PRINCIPAL, new AtomicInteger(1)); + Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(REGION, null); + source.put(PRINCIPAL, new AtomicInteger(3), 45L); + assertEquals(1, ((AtomicInteger) channel.get(REGION, PRINCIPAL).getValue()).get()); + // Give both layouts a finite source deadline, including persistent hash regions. + assertTrue("Failed to set expiry on persisted " + storage + " key", + commands.pexpire(sourceKey, 45_000L)); + long deadline = deadline(commands, sourceKey); + assertTrue(deadline > System.currentTimeMillis()); + Migration migration = factory.open(channel, config, namespace, commands); + assertTrue(migration.importWindow.test(PRINCIPAL)); + assertFalse(migration.importWindow.test(PRINCIPAL)); + assertEquals(deadline, deadline(commands, destinationKey)); + assertEquals(4, migration.store.reserve(PRINCIPAL).getCount()); + assertEquals(deadline, deadline(commands, destinationKey)); + assertEquals(3, ((AtomicInteger) source.get(PRINCIPAL)).get()); + assertEquals(deadline, deadline(commands, sourceKey)); + } + } + } finally { + client.shutdown(); + } + } + + private static long deadline(RedisAdvancedClusterCommands commands, String key) { + return commands.eval("return redis.call('PEXPIRETIME', KEYS[1])", ScriptOutputType.INTEGER, key); + } + + private static String nodes() { + String nodes = System.getProperty("shiro.redis.test.cluster.nodes"); + assumeTrue("Supply an isolated Redis cluster", Objects.nonNull(nodes)); + return nodes; + } + + private static J2CacheConfig config(String nodes, String provider, String storage, String sourceNamespace) { + J2CacheConfig config = new J2CacheConfig(); + config.setL1CacheName("caffeine"); + config.setL2CacheName(provider); + config.setSyncTtlToRedis(true); + config.getL1CacheProperties().setProperty("region." + REGION, "100, 45s"); + config.getL2CacheProperties().setProperty("hosts", nodes); + config.getL2CacheProperties().setProperty("mode", "cluster"); + config.getL2CacheProperties().setProperty("scheme", "redis-cluster"); + config.getL2CacheProperties().setProperty("password", ""); + config.getL2CacheProperties().setProperty("namespace", sourceNamespace); + config.getL2CacheProperties().setProperty("storage", storage); + return config; + } + + @FunctionalInterface + private interface StoreFactory { + Migration open(CacheChannel channel, J2CacheConfig config, String namespace, + RedisAdvancedClusterCommands commands); + } + + private record Migration(CredentialRetryStore store, + Predicate importWindow) { + } +} From b0281503848ca5cc439aafd3e70f7c8e946a967b Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:32:41 +0800 Subject: [PATCH 28/50] ci: exercise J2Cache migration on a Redis cluster --- .github/workflows/main-ci.yml | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 31e6dc46..fdc148f7 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -44,6 +44,45 @@ jobs: RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }} run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" -Dshiro.memcached.test.port="${RETRY_MEMCACHED_PORT}" clean verify + - name: Verify J2Cache retry migration on Redis Cluster + shell: bash + run: | + set -euo pipefail + containers=() + trap 'if (( ${#containers[@]} > 0 )); then docker rm -f "${containers[@]}" >/dev/null; fi' EXIT + nodes=() + for port in 16380 16381 16382; do + container=$(docker run -d --rm --network host redis:8.4.0 redis-server \ + --bind 127.0.0.1 --port "$port" --cluster-enabled yes \ + --cluster-announce-ip 127.0.0.1 --cluster-config-file nodes.conf \ + --save '' --appendonly no) + containers+=("$container") + nodes+=("127.0.0.1:$port") + for attempt in {1..60}; do + if docker exec "$container" redis-cli -p "$port" ping | grep -qx PONG; then + break + fi + if (( attempt == 60 )); then + docker logs "$container" + exit 1 + fi + sleep 0.25 + done + done + timeout 30s docker exec "${containers[0]}" redis-cli --cluster create "${nodes[@]}" --cluster-replicas 0 --cluster-yes + cluster_nodes=$(IFS=,; printf '%s' "${nodes[*]}") + mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ + -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \ + -Dtest=J2CacheRedisClusterMigrationTest test + python3 - <<'PYTHON' + from pathlib import Path + from xml.etree import ElementTree + + report = Path("shiro-extension-core/target/surefire-reports") + suite = ElementTree.parse(next(report.glob("TEST-*J2CacheRedisClusterMigrationTest.xml"))).getroot() + if tuple(suite.get(key) for key in ("tests", "failures", "errors", "skipped")) != ("2", "0", "0", "0"): + raise SystemExit("Expected both Redis Cluster migration tests to pass without skips") + PYTHON - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec From e39145162088c14a89fad16e6a6ea1810f6067ce Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:36:10 +0800 Subject: [PATCH 29/50] test: keep Jedis cluster seeds on loopback in CI --- .../j2cache/J2CacheRedisClusterMigrationTest.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java index de366896..8f98d900 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java @@ -39,7 +39,9 @@ public class J2CacheRedisClusterMigrationTest { @Test public void jedisMigratesGenericAndHashCountersAcrossPrimaries() throws Exception { String nodes = nodes(); - Set addresses = Arrays.stream(nodes.split(",")).map(HostAndPort::parseString) + // Jedis 2.9's parseString rewrites loopback to the machine's primary address. + Set addresses = redisUris(nodes).stream() + .map(uri -> new HostAndPort(uri.getHost(), uri.getPort())) .collect(Collectors.toSet()); try (JedisCluster jedis = new JedisCluster(addresses)) { verifyLayouts(nodes, "redis", (channel, config, namespace, commands) -> { @@ -61,9 +63,7 @@ public void lettuceMigratesGenericAndHashCountersAcrossPrimaries() throws Except private void verifyLayouts(String nodes, String provider, StoreFactory factory) throws Exception { SerializationUtils.init("java", new Properties()); - List uris = Arrays.stream(nodes.split(",")).map(node -> RedisURI.create("redis://" + node)) - .collect(Collectors.toList()); - RedisClusterClient client = RedisClusterClient.create(uris); + RedisClusterClient client = RedisClusterClient.create(redisUris(nodes)); try (var connection = client.connect()) { var commands = connection.sync(); for (String storage : new String[] {"generic", "hash"}) { @@ -104,6 +104,11 @@ private void verifyLayouts(String nodes, String provider, StoreFactory factory) } } + private static List redisUris(String nodes) { + return Arrays.stream(nodes.split(",")).map(node -> RedisURI.create("redis://" + node)) + .collect(Collectors.toList()); + } + private static long deadline(RedisAdvancedClusterCommands commands, String key) { return commands.eval("return redis.call('PEXPIRETIME', KEYS[1])", ScriptOutputType.INTEGER, key); } From 53f1a1a9f826829ccbf920ec5f22d8d43b3c9152 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:38:43 +0800 Subject: [PATCH 30/50] Preserve Redisson retry TTL and idle state during cutover --- .github/workflows/main-ci.yml | 11 +- README.md | 2 + README.zh-CN.md | 2 + .../redis/RedisCredentialRetryStore.java | 31 +++++- .../RedissonCredentialRetryStore.java | 78 ++++++++++++- ...onCredentialRetryStoreIntegrationTest.java | 104 +++++++++++++++++- 6 files changed, 213 insertions(+), 15 deletions(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index fdc148f7..0b4f7f2a 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -44,7 +44,7 @@ jobs: RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }} run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" -Dshiro.memcached.test.port="${RETRY_MEMCACHED_PORT}" clean verify - - name: Verify J2Cache retry migration on Redis Cluster + - name: Verify J2Cache and Redisson retry migration on Redis Cluster shell: bash run: | set -euo pipefail @@ -73,15 +73,16 @@ jobs: cluster_nodes=$(IFS=,; printf '%s' "${nodes[*]}") mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \ - -Dtest=J2CacheRedisClusterMigrationTest test + '-Dtest=J2CacheRedisClusterMigrationTest,RedissonCredentialRetryStoreIntegrationTest#migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline+keepsMapExpiryAndImportsPersistentZeroCounts' test python3 - <<'PYTHON' from pathlib import Path from xml.etree import ElementTree report = Path("shiro-extension-core/target/surefire-reports") - suite = ElementTree.parse(next(report.glob("TEST-*J2CacheRedisClusterMigrationTest.xml"))).getroot() - if tuple(suite.get(key) for key in ("tests", "failures", "errors", "skipped")) != ("2", "0", "0", "0"): - raise SystemExit("Expected both Redis Cluster migration tests to pass without skips") + for name in ("J2CacheRedisClusterMigrationTest", "RedissonCredentialRetryStoreIntegrationTest"): + suite = ElementTree.parse(next(report.glob(f"TEST-*{name}.xml"))).getroot() + if tuple(suite.get(key) for key in ("tests", "failures", "errors", "skipped")) != ("2", "0", "0", "0"): + raise SystemExit(f"Expected two Redis Cluster migration tests without skips in {name}") PYTHON - name: Require coverage for modules with existing tests run: | diff --git a/README.md b/README.md index 71bf3d7e..145d0ac8 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,8 @@ The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for eac The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Pass the source server that owns the legacy key and accepts unauthenticated Memcached Meta Text on a trusted connection. The adapter reads the value and its remaining TTL together, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. Select source servers using the original key routing. Binary-only or authenticated source servers require a separate migration path. +For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. + ## 8. Core Usage / API Selected public API (all classes under `org.apache.shiro.biz`): diff --git a/README.zh-CN.md b/README.zh-CN.md index c025b2ec..222958e2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -210,6 +210,8 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由传入保存旧值的源节点,该节点需允许在可信连接上使用无需认证的 Memcached Meta Text 协议。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议或需要认证的源节点需要独立迁移方式。 +对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java index c094a724..b2f506f1 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -100,6 +100,9 @@ public final class RedisCredentialRetryStore implements CredentialRetryStore { end end redis.call('HSET', key, 'window', ARGV[1], 'count', ARGV[2]) + if ARGV[4] ~= '0' then + redis.call('HSET', key, 'idleMillis', ARGV[4], 'ttlDeadline', ARGV[5]) + end if ARGV[3] ~= '0' then redis.call('PEXPIREAT', key, ARGV[3]) end @@ -224,11 +227,33 @@ public void clearIfCurrent(Object principal, String windowId) { * @return true when an unexpired counter was imported */ public boolean importFixedWindow(Object principal, int count, long deadlineMillis) { - if (count < 0 || deadlineMillis < 0) { - throw new IllegalArgumentException("Legacy count and deadline must be nonnegative"); + return importWindow(principal, count, deadlineMillis, 0, Duration.ZERO); + } + + /** + * Imports a legacy counter and its original lifetime and idle metadata into an empty key. + * Run this only during an exclusive cutover. + * + * @param principal principal to migrate + * @param count persisted count before the next reservation + * @param ttlDeadline absolute lifetime deadline in epoch milliseconds, or zero without a lifetime limit + * @param idleDeadline absolute idle deadline in epoch milliseconds, or zero without an idle timeout + * @param maxIdle existing idle period + * @return true when an unexpired counter was imported + */ + public boolean importWindow(Object principal, int count, long ttlDeadline, long idleDeadline, Duration maxIdle) { + long idleMillis = toMillis(maxIdle, "maxIdle"); + if (count < 0 || ttlDeadline < 0 || idleDeadline < 0 + || (idleMillis == 0) != (idleDeadline == 0) || idleMillis > (1L << 52)) { + throw new IllegalArgumentException("Invalid legacy retry count or expiry"); + } + long effectiveDeadline = ttlDeadline; + if (idleDeadline > 0 && (effectiveDeadline == 0 || idleDeadline < effectiveDeadline)) { + effectiveDeadline = idleDeadline; } return "1".equals(executor.eval(IMPORT_LEGACY, List.of(key(principal)), - List.of(UUID.randomUUID().toString(), Integer.toString(count), Long.toString(deadlineMillis)))); + List.of(UUID.randomUUID().toString(), Integer.toString(count), Long.toString(effectiveDeadline), + Long.toString(idleMillis), Long.toString(ttlDeadline)))); } private String key(Object principal) { diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java index 291989ac..066d48ca 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java @@ -1,14 +1,25 @@ package org.apache.shiro.biz.cache.redisson; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; +import io.netty.buffer.Unpooled; +import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; import org.apache.shiro.biz.cache.redis.RedisCredentialRetryStore; +import org.apache.shiro.cache.CacheException; +import org.redisson.RedissonObject; +import org.redisson.api.RMapCache; import org.redisson.api.RScript; import org.redisson.api.RedissonClient; +import org.redisson.client.codec.ByteArrayCodec; +import org.redisson.client.codec.Codec; import org.redisson.client.codec.StringCodec; +import org.redisson.client.handler.State; /** * Shared retry state using Redisson's Redis connection and the configured TTL and idle period. @@ -16,6 +27,27 @@ public final class RedissonCredentialRetryStore implements CredentialRetryStore { private final RedisCredentialRetryStore delegate; + private final RedissonClient client; + + // Redisson 3.12.5 stores the idle period with the value and each deadline in its own sorted set. + private static final String SNAPSHOT_LEGACY = """ + local value = redis.call('HGET', KEYS[1], ARGV[1]) + if not value then return {} end + local idle, payload = struct.unpack('dLc0', value) + local ttlDeadline = tonumber(redis.call('ZSCORE', KEYS[2], ARGV[1]) or '0') + local idleDeadline = 0 + if idle > 0 then + idleDeadline = tonumber(redis.call('ZSCORE', KEYS[3], ARGV[1]) or '0') + if idleDeadline == 0 then return redis.error_reply('Missing Redisson idle deadline') end + end + local mapTtl = redis.call('PTTL', KEYS[1]) + if mapTtl >= 0 then + local time = redis.call('TIME') + local mapDeadline = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000) + mapTtl + if ttlDeadline == 0 or mapDeadline < ttlDeadline then ttlDeadline = mapDeadline end + end + return {payload, ttlDeadline, idleDeadline, idle} + """; /** * @param client the configured Redisson client @@ -26,7 +58,8 @@ public final class RedissonCredentialRetryStore implements CredentialRetryStore */ public RedissonCredentialRetryStore(RedissonClient client, String namespace, Function principalKey, Duration ttl, Duration maxIdle) { - RScript scripts = Objects.requireNonNull(client, "client").getScript(StringCodec.INSTANCE); + this.client = Objects.requireNonNull(client, "client"); + RScript scripts = client.getScript(StringCodec.INSTANCE); this.delegate = new RedisCredentialRetryStore( (script, keys, args) -> scripts.eval(keys.get(0), RScript.Mode.READ_WRITE, script, RScript.ReturnType.VALUE, List.copyOf(keys), args.toArray()), @@ -42,4 +75,47 @@ public Attempt reserve(Object principal) { public void clearIfCurrent(Object principal, String windowId) { delegate.clearIfCurrent(principal, windowId); } + + /** + * Copies a Redisson 3.12.5 map-cache counter during an exclusive cutover. + * Pause old and new clients and drain writes before importing. + * + * @param source original retry map cache on the same Redis deployment + * @param principal original map key and principal for the destination + * @return true if a live legacy window was copied into an empty destination + */ + public boolean migrateLegacyWindow(RMapCache source, K principal) { + String name = Objects.requireNonNull(source, "source").getName(); + Objects.requireNonNull(principal, "principal"); + Codec codec = source.getCodec(); + try { + ByteBuf key = codec.getMapKeyEncoder().encode(principal); + List snapshot; + try { + snapshot = client.getScript(ByteArrayCodec.INSTANCE).eval(name, RScript.Mode.READ_WRITE, + SNAPSHOT_LEGACY, RScript.ReturnType.MULTI, List.of(name, + RedissonObject.prefixName("redisson__timeout__set", name), + RedissonObject.prefixName("redisson__idle__set", name)), + ByteBufUtil.getBytes(key)); + } finally { + key.release(); + } + if (snapshot.isEmpty()) { + return false; + } + ByteBuf payload = Unpooled.wrappedBuffer((byte[]) snapshot.get(0)); + try { + Object counter = codec.getMapValueDecoder().decode(payload, new State()); + if (!(counter instanceof AtomicInteger)) { + throw new CacheException("Redisson legacy retry entry must contain an AtomicInteger"); + } + return delegate.importWindow(principal, ((AtomicInteger) counter).get(), + (Long) snapshot.get(1), (Long) snapshot.get(2), Duration.ofMillis((Long) snapshot.get(3))); + } finally { + payload.release(); + } + } catch (IOException exception) { + throw new CacheException("Unable to decode the Redisson legacy retry entry", exception); + } + } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java index 6d820118..fd833158 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java @@ -1,7 +1,10 @@ package org.apache.shiro.biz.cache.redisson; +import io.lettuce.core.RedisURI; +import io.lettuce.core.cluster.RedisClusterClient; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -12,32 +15,43 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.redisson.Redisson; +import org.redisson.RedissonObject; +import org.redisson.api.RMapCache; import org.redisson.api.RScript; import org.redisson.api.RedissonClient; import org.redisson.client.codec.StringCodec; +import org.redisson.codec.CompositeCodec; +import org.redisson.codec.SerializationCodec; import org.redisson.config.Config; +import redis.clients.util.JedisClusterCRC16; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; public class RedissonCredentialRetryStoreIntegrationTest { + private static final String CLUSTER_NODES = "shiro.redis.test.cluster.nodes"; private static RedissonClient firstClient; private static RedissonClient secondClient; - private final String namespace = "test:redisson-retry:" + UUID.randomUUID(); + private final String namespace = "{retry-current}:test:redisson-retry:" + UUID.randomUUID(); + private final String legacyNamespace = "{retry-legacy}:test:redisson-retry:" + UUID.randomUUID(); @BeforeClass public static void connectTwoClients() { String port = System.getProperty("shiro.redis.test.port"); - assumeTrue("Supply an isolated Redis port", Objects.nonNull(port)); + assumeTrue("Supply an isolated Redis port or cluster", Objects.nonNull(port) + || Objects.nonNull(System.getProperty(CLUSTER_NODES))); firstClient = client(port); secondClient = client(port); } @@ -82,6 +96,35 @@ public void independentClientsReserveUniqueCountsAndPreserveTtl() throws Excepti } } + @Test + public void migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline() throws Exception { + String mapName = legacyNamespace + ":legacy"; + assertDifferentPrimaries(mapName, namespace + ":principal"); + RMapCache source = firstClient.getMapCache(mapName, + new CompositeCodec(StringCodec.INSTANCE, new SerializationCodec(), new SerializationCodec())); + source.put("principal", new AtomicInteger(3), 7000, TimeUnit.MILLISECONDS, 6000, TimeUnit.MILLISECONDS); + long ttl = sourceDeadline(mapName, "redisson__timeout__set"); + long idle = sourceDeadline(mapName, "redisson__idle__set"); + assertEquals(1000L, ttl - idle); + RedissonCredentialRetryStore store = store(secondClient, Duration.ofSeconds(30), Duration.ofSeconds(30)); + assertTrue(store.migrateLegacyWindow(source, "principal")); + assertFalse(store.migrateLegacyWindow(source, "principal")); + assertFalse(store.migrateLegacyWindow(source, "missing")); + assertEquals(idle, deadline()); + assertEquals(idle, sourceDeadline(mapName, "redisson__idle__set")); + assertEquals(ttl, sourceDeadline(mapName, "redisson__timeout__set")); + + awaitDeadline(idle - 4900); + assertEquals(4, store.reserve("principal").getCount()); + assertEquals(ttl, deadline()); + } + + private long sourceDeadline(String name, String prefix) { + return firstClient.getScript(StringCodec.INSTANCE).eval(RScript.Mode.READ_WRITE, + "return tonumber(redis.call('ZSCORE', KEYS[1], ARGV[1]))", + RScript.ReturnType.INTEGER, List.of(RedissonObject.prefixName(prefix, name)), "principal"); + } + @Test public void idleRefreshIsCappedByTtlAndStaleClearDoesNotRefreshIt() throws Exception { RedissonCredentialRetryStore first = store(firstClient, Duration.ofMillis(3000), Duration.ofMillis(2300)); @@ -104,6 +147,27 @@ public void idleRefreshIsCappedByTtlAndStaleClearDoesNotRefreshIt() throws Excep assertEquals(2, second.reserve("principal").getCount()); } + @Test + public void keepsMapExpiryAndImportsPersistentZeroCounts() { + RedissonCredentialRetryStore store = store(secondClient, Duration.ofSeconds(30), Duration.ofSeconds(30)); + RMapCache persistent = firstClient.getMapCache(legacyNamespace + ":persistent", new SerializationCodec()); + persistent.put("principal", new AtomicInteger(0)); + assertTrue(store.migrateLegacyWindow(persistent, "principal")); + Attempt attempt = store.reserve("principal"); + assertEquals(1, attempt.getCount()); + assertEquals(-1L, deadline()); + store.clearIfCurrent("principal", attempt.getWindowId()); + + RMapCache bounded = firstClient.getMapCache(legacyNamespace + ":bounded", new SerializationCodec()); + bounded.put("principal", new AtomicInteger(3), 10, TimeUnit.SECONDS); + assertTrue(bounded.expire(5, TimeUnit.SECONDS)); + long mapDeadline = deadline(bounded.getName()); + assertTrue(mapDeadline > System.currentTimeMillis()); + assertTrue(store.migrateLegacyWindow(bounded, "principal")); + assertEquals(4, store.reserve("principal").getCount()); + assertEquals(mapDeadline, deadline()); + } + @Test public void idleOnlyWindowExpiresAndZeroPoliciesStayPersistent() throws Exception { RedissonCredentialRetryStore idleOnly = store(firstClient, Duration.ZERO, Duration.ofMillis(1200)); @@ -127,9 +191,13 @@ private RedissonCredentialRetryStore store(RedissonClient client, Duration ttl, } private long deadline() { + return deadline(namespace + ":principal"); + } + + private long deadline(String key) { return firstClient.getScript(StringCodec.INSTANCE).eval(RScript.Mode.READ_WRITE, "return redis.call('PEXPIRETIME', KEYS[1])", - RScript.ReturnType.INTEGER, List.of(namespace + ":principal")); + RScript.ReturnType.INTEGER, List.of(key)); } private static void awaitDeadline(long deadline) throws InterruptedException { @@ -141,9 +209,33 @@ private static void awaitDeadline(long deadline) throws InterruptedException { private static RedissonClient client(String port) { Config config = new Config().setCodec(StringCodec.INSTANCE).setThreads(2).setNettyThreads(2); - config.useSingleServer().setAddress("redis://127.0.0.1:" + port) - .setConnectionMinimumIdleSize(1).setConnectionPoolSize(4) - .setSubscriptionConnectionMinimumIdleSize(1).setSubscriptionConnectionPoolSize(2); + String cluster = System.getProperty(CLUSTER_NODES); + if (Objects.nonNull(cluster)) { + config.useClusterServers().addNodeAddress(Arrays.stream(cluster.split(",")) + .map(node -> "redis://" + node).toArray(String[]::new)) + .setMasterConnectionMinimumIdleSize(1).setMasterConnectionPoolSize(4) + .setSlaveConnectionMinimumIdleSize(1).setSlaveConnectionPoolSize(4) + .setSubscriptionConnectionMinimumIdleSize(1).setSubscriptionConnectionPoolSize(2); + } else { + config.useSingleServer().setAddress("redis://127.0.0.1:" + port) + .setConnectionMinimumIdleSize(1).setConnectionPoolSize(4) + .setSubscriptionConnectionMinimumIdleSize(1).setSubscriptionConnectionPoolSize(2); + } return Redisson.create(config); } + + private static void assertDifferentPrimaries(String source, String destination) { + String cluster = System.getProperty(CLUSTER_NODES); + if (Objects.nonNull(cluster)) { + RedisClusterClient topology = RedisClusterClient.create(Arrays.stream(cluster.split(",")) + .map(node -> RedisURI.create("redis://" + node)).collect(Collectors.toList())); + try { + String sourceOwner = topology.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(source)).getNodeId(); + String destinationOwner = topology.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(destination)).getNodeId(); + assertNotEquals("Migration must cross Redis primary nodes", sourceOwner, destinationOwner); + } finally { + topology.shutdown(); + } + } + } } From f60225e7ac4acf58c511b1efd03d00b0e8bf0b1a Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:45:55 +0800 Subject: [PATCH 31/50] Migrate native Ehcache 3 counters during exclusive cutover --- README.md | 2 + README.zh-CN.md | 2 + .../ehcache/Ehcache3CredentialRetryStore.java | 78 +++++++++++++++---- ...e3CredentialRetryStoreIntegrationTest.java | 47 +++++++++++ 4 files changed, 114 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 145d0ac8..92edcbe2 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,8 @@ For a Spring-managed retry matcher with cache name `login`, declare a provider-b For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. +For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must already accept both legacy counters and retry windows, such as with value type `Serializable`, and use creation-only or eternal expiry. Live entries are replaced in place with the existing deadline. A legacy-only value type or a policy that resets expiry on writes requires a separate cutover. + For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. diff --git a/README.zh-CN.md b/README.zh-CN.md index 222958e2..9d5e3005 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -200,6 +200,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 +原生 Ehcache 3 的切换需暂停全部重试客户端、排空在途写入,并为每个区域只安排一个迁移写入者。沿用原缓存,对每个已知主体调用 `migrateLegacyWindow`。原区域须已允许旧计数和新窗口两种值(例如值类型为 `Serializable`),并沿用创建时确定的截止时间或永久策略。存活条目原位替换,保留原截止时间。仅接受旧类型或写入会重置有效期的区域需要单独切换。 + Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java index 73923b90..c71c73d4 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -3,6 +3,7 @@ import java.time.Duration; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Supplier; import org.apache.shiro.biz.authc.credential.CredentialRetryStore; @@ -20,7 +21,7 @@ public final class Ehcache3CredentialRetryStore implements CredentialRetrySto private static final int MAX_CONFLICTS = 128; - private final Cache cache; + private final Cache cache; private final Function principalKey; /** @@ -28,10 +29,15 @@ public final class Ehcache3CredentialRetryStore implements CredentialRetrySto * or Ehcache's eternal expiry * @param principalKey consistent principal key encoding for all callers sharing the cache */ - public Ehcache3CredentialRetryStore(Cache cache, Function principalKey) { - this.cache = Objects.requireNonNull(cache, "cache"); + @SuppressWarnings("unchecked") + public Ehcache3CredentialRetryStore(Cache cache, Function principalKey) { + Objects.requireNonNull(cache, "cache"); + if (!cache.getRuntimeConfiguration().getValueType().isAssignableFrom(Attempt.class)) { + throw new IllegalArgumentException("Ehcache retry region must accept credential retry attempts"); + } + this.cache = (Cache) cache; this.principalKey = Objects.requireNonNull(principalKey, "principalKey"); - ExpiryPolicy expiry = cache.getRuntimeConfiguration().getExpiryPolicy(); + ExpiryPolicy expiry = cache.getRuntimeConfiguration().getExpiryPolicy(); if (!(expiry instanceof FixedWindowExpiry) && !ExpiryPolicy.NO_EXPIRY.equals(expiry)) { throw new IllegalArgumentException("Retry cache must preserve its creation expiry"); } @@ -41,27 +47,37 @@ public Ehcache3CredentialRetryStore(Cache cache, Function * Returns an expiry policy for a dedicated retry cache. * * @param window configured duration for a newly created retry window + * @param value type of the retry region * @return policy that retains the first deadline on reads and updates */ - public static ExpiryPolicy fixedWindowExpiry(Duration window) { + public static ExpiryPolicy fixedWindowExpiry(Duration window) { Objects.requireNonNull(window, "window"); if (window.isZero() || window.isNegative()) { throw new IllegalArgumentException("Retry window must be positive"); } - return new FixedWindowExpiry(window); + return new FixedWindowExpiry<>(window); } @Override public Attempt reserve(Object principal) { K key = key(principal); for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { - Attempt current = cache.get(key); - if (Objects.isNull(current)) { - Attempt initial = new Attempt(UUID.randomUUID().toString(), 1); + Object value = cache.get(key); + if (Objects.isNull(value)) { + Attempt initial = firstAttempt(); if (Objects.isNull(cache.putIfAbsent(key, initial))) { return initial; } + } else if (value == MigratedCounter.ZERO) { + Attempt initial = firstAttempt(); + if (cache.replace(key, value, initial)) { + return initial; + } } else { + if (value instanceof AtomicInteger) { + throw new CacheException("Legacy Ehcache retry entry requires migration before reservation"); + } + Attempt current = (Attempt) value; if (current.getCount() == Integer.MAX_VALUE) { return current; } @@ -79,19 +95,51 @@ public void clearIfCurrent(Object principal, String windowId) { K key = key(principal); Objects.requireNonNull(windowId, "windowId"); for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { - Attempt current = cache.get(key); - if (Objects.isNull(current) || !windowId.equals(current.getWindowId()) || cache.remove(key, current)) { + Object value = cache.get(key); + if (!(value instanceof Attempt) || !windowId.equals(((Attempt) value).getWindowId()) || cache.remove(key, value)) { return; } } throw new CacheException("Unable to clear credential retry state within the conflict limit"); } + /** + * Converts a persisted counter in place without restarting its expiry. + * Pause all legacy and new retry clients, drain writes, and use a single migration writer. + * The existing region must accept both the legacy and new value formats. + * + * @param principal original principal in the Ehcache region + * @return true when a live legacy counter was converted + */ + public boolean migrateLegacyWindow(Object principal) { + K key = key(principal); + Object value = cache.get(key); + if (!(value instanceof AtomicInteger)) { + return false; + } + int count = ((AtomicInteger) value).get(); + if (count < 0) { + throw new CacheException("Legacy credential retry count is negative"); + } + Object migrated = count == 0 ? MigratedCounter.ZERO : new Attempt(UUID.randomUUID().toString(), count); + // Serialized AtomicInteger copies cannot be compared reliably. Under exclusive cutover, + // replacing a live entry preserves the existing expiry through the validated policy. + return Objects.nonNull(cache.replace(key, migrated)); + } + + private static Attempt firstAttempt() { + return new Attempt(UUID.randomUUID().toString(), 1); + } + private K key(Object principal) { return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); } - private static final class FixedWindowExpiry implements ExpiryPolicy { + private enum MigratedCounter { + ZERO + } + + private static final class FixedWindowExpiry implements ExpiryPolicy { private final Duration window; @@ -100,17 +148,17 @@ private FixedWindowExpiry(Duration window) { } @Override - public Duration getExpiryForCreation(Object key, Attempt value) { + public Duration getExpiryForCreation(Object key, V value) { return window; } @Override - public Duration getExpiryForAccess(Object key, Supplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { return null; } @Override - public Duration getExpiryForUpdate(Object key, Supplier previous, Attempt next) { + public Duration getExpiryForUpdate(Object key, Supplier previous, V next) { return null; } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index cf6f9611..45d67799 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -1,5 +1,6 @@ package org.apache.shiro.biz.cache.ehcache; +import java.io.Serializable; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; @@ -10,6 +11,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.ehcache.Cache; @@ -24,6 +26,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; @@ -87,6 +90,50 @@ public void preservesOriginalDeadlineAndIgnoresResetFromExpiredWindow() { } } + @Test + public void migratesOffHeapLegacyCountersWithoutRestartingTheDeadline() { + AtomicLong time = new AtomicLong(10_000); + try (CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder() + .using(new TimeSourceConfiguration(time::get)) + .withCache("legacy", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, Serializable.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) + .build(true)) { + Cache cache = manager.getCache("legacy", String.class, Serializable.class); + cache.put("alice", new AtomicInteger(3)); + cache.put("zero", new AtomicInteger(0)); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + time.set(12_000); + + assertTrue(store.migrateLegacyWindow("alice")); + assertTrue(store.migrateLegacyWindow("zero")); + assertFalse(store.migrateLegacyWindow("missing")); + assertFalse(store.migrateLegacyWindow("alice")); + store.clearIfCurrent("zero", "stale"); + assertEquals(1, store.reserve("zero").getCount()); + Attempt preserved = store.reserve("alice"); + assertEquals(4, preserved.getCount()); + time.set(13_001); + assertNull(cache.get("alice")); + assertNull(cache.get("zero")); + Attempt renewed = store.reserve("alice"); + assertEquals(1, renewed.getCount()); + assertNotEquals(preserved.getWindowId(), renewed.getWindowId()); + } + } + + @Test + public void rejectsARegionThatOnlyAcceptsTheLegacyCounterType() { + try (CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder() + .withCache("legacy-only", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, AtomicInteger.class, ResourcePoolsBuilder.heap(10))) + .build(true)) { + Cache cache = manager.getCache("legacy-only", String.class, AtomicInteger.class); + assertThrows(IllegalArgumentException.class, () -> new Ehcache3CredentialRetryStore<>(cache, Object::toString)); + } + } + @Test public void rejectsPoliciesThatReplaceExpiryOnWrites() { try (CacheManager manager = manager(new AtomicLong(10_000), From 45b558c7c03afd311436c875b4118fc43e362362 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:55:20 +0800 Subject: [PATCH 32/50] Preserve binary J2Cache legacy keys during Redis cutover --- .github/workflows/main-ci.yml | 6 +++- README.md | 2 +- README.zh-CN.md | 2 +- pom.xml | 3 +- .../J2CacheLettuceCredentialRetryStore.java | 33 ++++++++++++++++- .../J2CacheRedisCredentialRetryStore.java | 20 +++++++---- .../j2cache/J2CacheRedisLegacyWindows.java | 28 +++++++-------- .../J2CacheRedisClusterMigrationTest.java | 36 ++++++++++++------- ...isCredentialRetryStoreIntegrationTest.java | 16 +++++++-- 9 files changed, 104 insertions(+), 42 deletions(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 0b4f7f2a..d091bc07 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -74,12 +74,16 @@ jobs: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \ '-Dtest=J2CacheRedisClusterMigrationTest,RedissonCredentialRetryStoreIntegrationTest#migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline+keepsMapExpiryAndImportsPersistentZeroCounts' test + mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ + -pl shiro-extension-core -Dshiro.redis.test.cluster.nodes="$cluster_nodes" \ + -Dshiro.test.fileEncoding=ISO-8859-1 -Dshiro.redis.test.expectedCharset=ISO-8859-1 \ + -Dsurefire.reportNameSuffix=latin1 -Dtest=J2CacheRedisClusterMigrationTest test python3 - <<'PYTHON' from pathlib import Path from xml.etree import ElementTree report = Path("shiro-extension-core/target/surefire-reports") - for name in ("J2CacheRedisClusterMigrationTest", "RedissonCredentialRetryStoreIntegrationTest"): + for name in ("J2CacheRedisClusterMigrationTest", "J2CacheRedisClusterMigrationTest-latin1", "RedissonCredentialRetryStoreIntegrationTest"): suite = ElementTree.parse(next(report.glob(f"TEST-*{name}.xml"))).getroot() if tuple(suite.get(key) for key in ("tests", "failures", "errors", "skipped")) != ("2", "0", "0", "0"): raise SystemExit(f"Expected two Redis Cluster migration tests without skips in {name}") diff --git a/README.md b/README.md index 92edcbe2..67b7aef9 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ For a JCache retry region that already accepts both value types (for example, wi For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. -The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. Non-UTF-8 Jedis hash region keys require a separate migration path. +The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. For legacy keys that use the JVM default charset, run migration with the charset that wrote the source region. Jedis routes the expiry lookup using the original binary key. For non-UTF-8 Lettuce keys, supply a binary scripting connection in addition to the UTF-8 destination connection. The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Pass the source server that owns the legacy key and accepts unauthenticated Memcached Meta Text on a trusted connection. The adapter reads the value and its remaining TTL together, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. Select source servers using the original key routing. Binary-only or authenticated source servers require a separate migration path. diff --git a/README.zh-CN.md b/README.zh-CN.md index 9d5e3005..f1164002 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -208,7 +208,7 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 -J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。非 UTF-8 的 Jedis Hash 区域键需要单独迁移。 +J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。迁移按 JVM 默认字符集写入的旧键时,沿用原字符集。Jedis 按原二进制键查询截止时间。对于非 UTF-8 的 Lettuce 旧键,除 UTF-8 目标连接外,还需传入二进制脚本连接。 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由传入保存旧值的源节点,该节点需允许在可信连接上使用无需认证的 Memcached Meta Text 协议。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议或需要认证的源节点需要独立迁移方式。 diff --git a/pom.xml b/pom.xml index d806faa5..f23a7ab0 100644 --- a/pom.xml +++ b/pom.xml @@ -192,7 +192,7 @@ false once @{jacocoArgLine} -Xmx1024m - -Dfile.encoding=UTF-8 + -Dfile.encoding=${shiro.test.fileEncoding} ${basedir}/target/test-classes @@ -487,6 +487,7 @@ 2.0.x.20260630-SNAPSHOT UTF-8 + UTF-8 2.9.3 1.22.0 3.20.0 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java index 91b382e5..dab93fa3 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java @@ -2,6 +2,8 @@ import io.lettuce.core.ScriptOutputType; import io.lettuce.core.api.sync.RedisScriptingCommands; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Objects; import java.util.function.Function; import net.oschina.j2cache.CacheChannel; @@ -27,6 +29,22 @@ public final class J2CacheLettuceCredentialRetryStore implements CredentialRetry public J2CacheLettuceCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, String namespace, Function principalKey, RedisScriptingCommands commands) { + this(channel, config, region, namespace, principalKey, commands, null); + } + + /** + * @param channel channel using J2Cache's Lettuce L2 provider + * @param config the configuration used to create the channel + * @param region existing retry region whose expiry policy is reused + * @param namespace dedicated retry namespace shared by all instances + * @param principalKey stable principal encoding shared by all instances + * @param commands caller-managed UTF-8 scripting connection for the retry store + * @param legacyCommands binary scripting connection to the same Redis deployment for legacy keys + */ + public J2CacheLettuceCredentialRetryStore(CacheChannel channel, J2CacheConfig config, String region, + String namespace, Function principalKey, + RedisScriptingCommands commands, + RedisScriptingCommands legacyCommands) { if (!(channel.getL2Provider() instanceof LettuceCacheProvider)) { throw new IllegalArgumentException("J2Cache retry state requires a Lettuce L2 provider"); } @@ -35,7 +53,20 @@ public J2CacheLettuceCredentialRetryStore(CacheChannel channel, J2CacheConfig co script, ScriptOutputType.VALUE, keys.toArray(String[]::new), args.toArray(String[]::new)); this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "hash")); - this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, false, scripts); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, false, + key -> readDeadline(commands, legacyCommands, key)); + } + + private static long readDeadline(RedisScriptingCommands commands, + RedisScriptingCommands legacyCommands, byte[] key) { + if (Objects.nonNull(legacyCommands)) { + return legacyCommands.eval(J2CacheRedisLegacyWindows.DEADLINE_SCRIPT, ScriptOutputType.INTEGER, key); + } + String text = new String(key, StandardCharsets.UTF_8); + if (!Arrays.equals(key, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("A binary Lettuce connection is required for the legacy Redis key"); + } + return commands.eval(J2CacheRedisLegacyWindows.DEADLINE_SCRIPT, ScriptOutputType.INTEGER, text); } @Override diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java index 31ec84f4..d014295c 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java @@ -1,6 +1,6 @@ package org.apache.shiro.biz.cache.j2cache; -import java.util.List; +import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.function.Function; import net.oschina.j2cache.CacheChannel; @@ -22,6 +22,9 @@ */ public final class J2CacheRedisCredentialRetryStore implements CredentialRetryStore { + private static final byte[] DEADLINE_SCRIPT = + J2CacheRedisLegacyWindows.DEADLINE_SCRIPT.getBytes(StandardCharsets.US_ASCII); + private final RedisCredentialRetryStore delegate; private final J2CacheRedisLegacyWindows legacy; @@ -39,10 +42,12 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf throw new IllegalArgumentException("J2Cache Cluster mode requires its native JedisCluster script client"); } RedisClient client = provider.getRedisClient(); - RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> eval(client, script, keys, args); + RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> + onShard(client, keys.get(0).getBytes(StandardCharsets.UTF_8), jedis -> (String) jedis.eval(script, keys, args)); this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); - this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, scripts); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, + key -> onShard(client, key, jedis -> (Long) jedis.eval(DEADLINE_SCRIPT, 1, key))); } /** @@ -61,7 +66,8 @@ public J2CacheRedisCredentialRetryStore(CacheChannel channel, J2CacheConfig conf RedisCredentialRetryStore.ScriptExecutor scripts = (script, keys, args) -> (String) cluster.eval(script, keys, args); this.delegate = new RedisCredentialRetryStore(scripts, namespace, principalKey, J2CacheRetryExpiry.resolve(channel, config, region, "generic")); - this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, scripts); + this.legacy = new J2CacheRedisLegacyWindows(channel, config, region, true, + key -> (Long) cluster.eval(DEADLINE_SCRIPT, 1, key)); } @Override @@ -92,14 +98,14 @@ private static RedisCacheProvider writableProvider(CacheChannel channel) { throw new IllegalArgumentException("J2Cache retry state requires a writable Jedis provider"); } - private static String eval(RedisClient client, String script, List keys, List args) { + private static T onShard(RedisClient client, byte[] key, Function operation) { try { BinaryJedisCommands connection = client.get(); if (connection instanceof Jedis jedis) { - return (String) jedis.eval(script, keys, args); + return operation.apply(jedis); } if (connection instanceof ShardedJedis sharded) { - return (String) sharded.getShard(keys.get(0)).eval(script, keys, args); + return operation.apply(sharded.getShard(key)); } throw new CacheException("The J2Cache Redis connection does not expose script execution"); } finally { diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java index 54cfffac..1abc892a 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java @@ -3,11 +3,10 @@ import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; import java.util.Objects; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.ToLongFunction; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.J2CacheConfig; import net.oschina.j2cache.Level2Cache; @@ -19,37 +18,37 @@ /** Reads the persisted L2 counter and its Redis deadline while all retry clients are paused. */ final class J2CacheRedisLegacyWindows { - private static final String DEADLINE = String.join("\n", + static final String DEADLINE_SCRIPT = String.join("\n", "local ttl = redis.call('PTTL', KEYS[1])", - "if ttl < 0 then return tostring(ttl) end", + "if ttl < 0 then return ttl end", "local time = redis.call('TIME')", "local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)", - "return string.format('%.0f', now + ttl)"); + "return now + ttl"); private final CacheChannel channel; private final J2CacheConfig config; private final String region; private final boolean jedis; - private final RedisCredentialRetryStore.ScriptExecutor scripts; + private final ToLongFunction deadlineReader; J2CacheRedisLegacyWindows(CacheChannel channel, J2CacheConfig config, String region, boolean jedis, - RedisCredentialRetryStore.ScriptExecutor scripts) { + ToLongFunction deadlineReader) { this.channel = channel; this.config = config; this.region = region; this.jedis = jedis; - this.scripts = scripts; + this.deadlineReader = deadlineReader; } boolean migrate(String principal, RedisCredentialRetryStore destination) { Objects.requireNonNull(principal, "principal"); - String key = redisKey(principal); + byte[] key = redisKey(principal); Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(region, null); byte[] bytes = source.getBytes(principal); if (Objects.isNull(bytes)) { return false; } - long deadline = Long.parseLong(scripts.eval(DEADLINE, Collections.singletonList(key), Collections.emptyList())); + long deadline = deadlineReader.applyAsLong(key); if (deadline == -2) { return false; } @@ -64,7 +63,7 @@ boolean migrate(String principal, RedisCredentialRetryStore destination) { } } - private String redisKey(String principal) { + private byte[] redisKey(String principal) { Properties redis = config.getL2CacheProperties(); boolean hash = "hash".equalsIgnoreCase(redis.getProperty("storage", jedis ? "generic" : "hash")); // Jedis hash storage uses the platform charset and different whitespace rules. @@ -75,10 +74,7 @@ private String redisKey(String principal) { boolean hasNamespace = jedisHash ? StringUtils.isNotEmpty(namespace) : StringUtils.isNotEmpty(StringUtils.trim(namespace)); String regionKey = hasNamespace ? namespace + ":" + name : name; - if (jedisHash && !Arrays.equals(regionKey.getBytes(Charset.defaultCharset()), - regionKey.getBytes(StandardCharsets.UTF_8))) { - throw new IllegalArgumentException("The legacy Jedis region key must use UTF-8 for scripted migration"); - } - return hash ? regionKey : regionKey + ":" + principal; + String key = hash ? regionKey : regionKey + ":" + principal; + return key.getBytes(jedis && !hash ? StandardCharsets.UTF_8 : Charset.defaultCharset()); } } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java index 8f98d900..4ad75ae0 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java @@ -3,7 +3,10 @@ import io.lettuce.core.RedisURI; import io.lettuce.core.ScriptOutputType; import io.lettuce.core.cluster.RedisClusterClient; +import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -44,7 +47,7 @@ public void jedisMigratesGenericAndHashCountersAcrossPrimaries() throws Exceptio .map(uri -> new HostAndPort(uri.getHost(), uri.getPort())) .collect(Collectors.toSet()); try (JedisCluster jedis = new JedisCluster(addresses)) { - verifyLayouts(nodes, "redis", (channel, config, namespace, commands) -> { + verifyLayouts(nodes, "redis", (channel, config, namespace, commands, sourceCommands) -> { var store = new J2CacheRedisCredentialRetryStore( channel, config, REGION, namespace, Object::toString, jedis); return new Migration(store, store::migrateLegacyWindow); @@ -54,9 +57,9 @@ public void jedisMigratesGenericAndHashCountersAcrossPrimaries() throws Exceptio @Test public void lettuceMigratesGenericAndHashCountersAcrossPrimaries() throws Exception { - verifyLayouts(nodes(), "lettuce", (channel, config, namespace, commands) -> { + verifyLayouts(nodes(), "lettuce", (channel, config, namespace, commands, sourceCommands) -> { var store = new J2CacheLettuceCredentialRetryStore( - channel, config, REGION, namespace, Object::toString, commands); + channel, config, REGION, namespace, Object::toString, commands, sourceCommands); return new Migration(store, store::migrateLegacyWindow); }); } @@ -64,16 +67,20 @@ public void lettuceMigratesGenericAndHashCountersAcrossPrimaries() throws Except private void verifyLayouts(String nodes, String provider, StoreFactory factory) throws Exception { SerializationUtils.init("java", new Properties()); RedisClusterClient client = RedisClusterClient.create(redisUris(nodes)); - try (var connection = client.connect()) { + try (var connection = client.connect(); + var sourceConnection = client.connect(ByteArrayCodec.INSTANCE)) { var commands = connection.sync(); for (String storage : new String[] {"generic", "hash"}) { String id = UUID.randomUUID().toString(); String namespace = DESTINATION + id; - String sourceNamespace = LEGACY + id; + String sourceNamespace = LEGACY + "l\u00e9gacy:" + id; String sourceKey = sourceNamespace + ":" + REGION + ("hash".equals(storage) ? "" : ":" + PRINCIPAL); + Charset encoding = "redis".equals(provider) && "generic".equals(storage) + ? StandardCharsets.UTF_8 : Charset.defaultCharset(); + byte[] sourceKeyBytes = sourceKey.getBytes(encoding); String destinationKey = namespace + ":" + PRINCIPAL; - String sourceOwner = client.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(sourceKey)) + String sourceOwner = client.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(sourceKeyBytes)) .getNodeId(); String destinationOwner = client.getPartitions().getPartitionBySlot(JedisClusterCRC16.getSlot(destinationKey)).getNodeId(); @@ -86,17 +93,17 @@ private void verifyLayouts(String nodes, String provider, StoreFactory factory) assertEquals(1, ((AtomicInteger) channel.get(REGION, PRINCIPAL).getValue()).get()); // Give both layouts a finite source deadline, including persistent hash regions. assertTrue("Failed to set expiry on persisted " + storage + " key", - commands.pexpire(sourceKey, 45_000L)); - long deadline = deadline(commands, sourceKey); + sourceConnection.sync().pexpire(sourceKeyBytes, 45_000L)); + long deadline = deadline(sourceConnection.sync(), sourceKeyBytes); assertTrue(deadline > System.currentTimeMillis()); - Migration migration = factory.open(channel, config, namespace, commands); + Migration migration = factory.open(channel, config, namespace, commands, sourceConnection.sync()); assertTrue(migration.importWindow.test(PRINCIPAL)); assertFalse(migration.importWindow.test(PRINCIPAL)); assertEquals(deadline, deadline(commands, destinationKey)); assertEquals(4, migration.store.reserve(PRINCIPAL).getCount()); assertEquals(deadline, deadline(commands, destinationKey)); assertEquals(3, ((AtomicInteger) source.get(PRINCIPAL)).get()); - assertEquals(deadline, deadline(commands, sourceKey)); + assertEquals(deadline, deadline(sourceConnection.sync(), sourceKeyBytes)); } } } finally { @@ -109,13 +116,17 @@ private static List redisUris(String nodes) { .collect(Collectors.toList()); } - private static long deadline(RedisAdvancedClusterCommands commands, String key) { + private static long deadline(RedisAdvancedClusterCommands commands, K key) { return commands.eval("return redis.call('PEXPIRETIME', KEYS[1])", ScriptOutputType.INTEGER, key); } private static String nodes() { String nodes = System.getProperty("shiro.redis.test.cluster.nodes"); assumeTrue("Supply an isolated Redis cluster", Objects.nonNull(nodes)); + String expectedCharset = System.getProperty("shiro.redis.test.expectedCharset"); + if (Objects.nonNull(expectedCharset)) { + assertEquals(Charset.forName(expectedCharset), Charset.defaultCharset()); + } return nodes; } @@ -137,7 +148,8 @@ private static J2CacheConfig config(String nodes, String provider, String storag @FunctionalInterface private interface StoreFactory { Migration open(CacheChannel channel, J2CacheConfig config, String namespace, - RedisAdvancedClusterCommands commands); + RedisAdvancedClusterCommands commands, + RedisAdvancedClusterCommands sourceCommands); } private record Migration(CredentialRetryStore store, diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java index ca7cb4d5..ba2a0507 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java @@ -1,5 +1,7 @@ package org.apache.shiro.biz.cache.j2cache; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.Properties; import java.util.UUID; @@ -38,16 +40,26 @@ public void requireIsolatedRedis() { @Test public void migratesBothL2LayoutsUsingPersistedCountsAndDeadlines() throws Exception { SerializationUtils.init("java", new Properties()); + String expectedCharset = System.getProperty("shiro.redis.test.expectedCharset"); + if (Objects.nonNull(expectedCharset)) { + assertEquals(Charset.forName(expectedCharset), Charset.defaultCharset()); + } try (Jedis redis = new Jedis("127.0.0.1", port)) { for (String storage : new String[] {"generic", "hash"}) { J2CacheConfig config = config(true, storage); + String legacyNamespace = namespace + ":l\u00e9gacy"; + config.getL2CacheProperties().setProperty("namespace", legacyNamespace); try (CacheChannel channel = J2CacheTestChannel.open(config)) { channel.set(REGION, "principal", new AtomicInteger(1)); Level2Cache source = (Level2Cache) channel.getL2Provider().buildCache(REGION, null); source.put("principal", new AtomicInteger(3), 8L); assertEquals(1, ((AtomicInteger) channel.get(REGION, "principal").getValue()).get()); - String legacyKey = namespace + ":legacy:" + REGION + ("hash".equals(storage) ? "" : ":principal"); - long deadline = (Long) redis.eval("return redis.call('PEXPIRETIME', KEYS[1])", 1, legacyKey); + boolean hash = "hash".equals(storage); + String legacyKey = legacyNamespace + ":" + REGION + (hash ? "" : ":principal"); + byte[] keyBytes = legacyKey.getBytes(hash ? Charset.defaultCharset() : StandardCharsets.UTF_8); + assertEquals(Long.valueOf(1), redis.pexpire(keyBytes, 8000L)); + long deadline = (Long) redis.eval( + "return redis.call('PEXPIRETIME', KEYS[1])".getBytes(StandardCharsets.US_ASCII), 1, keyBytes); J2CacheRedisCredentialRetryStore store = store(channel, config); assertTrue(store.migrateLegacyWindow("principal")); assertFalse(store.migrateLegacyWindow("principal")); From a9f94b5753a286c131700842db7e0124e76b5f02 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:37:30 +0800 Subject: [PATCH 33/50] test: cover credential retry store failures --- .../biz/CredentialsMatcherSafetyTest.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) 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 index e7343d7c..fb7810e2 100644 --- 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 @@ -140,6 +140,58 @@ protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo assertEquals(1, store.attempts.get("alice").getCount()); } + @Test + public void reservationFailureStopsComparisonAndPropagates() { + IllegalStateException failure = new IllegalStateException("retry reservation failed"); + AtomicInteger comparisons = new AtomicInteger(); + DefaultCredentialsMatcher matcher = new DefaultCredentialsMatcher() { + @Override + protected boolean credentialsMatch(AuthenticationToken token, AuthenticationInfo info) { + comparisons.incrementAndGet(); + return true; + } + }; + matcher.setCredentialRetryStore(new CredentialRetryStore() { + @Override + public Attempt reserve(Object principal) { + throw failure; + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + fail("reservation failed before there was a window to clear"); + } + }); + + assertSame(failure, assertThrows(IllegalStateException.class, + () -> matcher.doCredentialsMatch(token("alice", "secret"), account(false)))); + assertEquals(0, comparisons.get()); + } + + @Test + public void failedWindowClearCannotReportSuccessfulAuthentication() { + IllegalStateException failure = new IllegalStateException("retry reset failed"); + TestRetryStore backingStore = new TestRetryStore(); + for (boolean hashed : new boolean[]{false, true}) { + CredentialRetryStore store = new CredentialRetryStore() { + @Override + public Attempt reserve(Object principal) { + return backingStore.reserve(principal); + } + + @Override + public void clearIfCurrent(Object principal, String windowId) { + assertEquals(backingStore.attempts.get(principal).getWindowId(), windowId); + throw failure; + } + }; + CredentialsMatcher matcher = matcher(hashed, store); + assertSame(failure, assertThrows(IllegalStateException.class, + () -> matcher.doCredentialsMatch(token("alice", "secret"), account(hashed)))); + } + assertEquals(2, backingStore.attempts.get("alice").getCount()); + } + private static CredentialsMatcher matcher(boolean hashed, CredentialRetryStore store) { if (hashed) { CredentialsRetryLimitCredentialsMatcher matcher = new CredentialsRetryLimitCredentialsMatcher(); From 89517ea607fe18126077e80202f51b19063e2f40 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:17:15 +0800 Subject: [PATCH 34/50] test: document JCache retry rollback boundary --- README.md | 2 +- README.zh-CN.md | 2 +- ...heCredentialRetryStoreIntegrationTest.java | 20 +++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 67b7aef9..679be2ae 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ For native Ehcache 3, pause all retry clients, drain writes, and use exactly one For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. -For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. +For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. Once the first entry is converted, the region can contain both formats. A legacy reader fails when it reads a converted entry as `AtomicInteger`. Keep the region paused for a rollback until you have verified a legacy-compatible restore, including active counts and deadlines. For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. diff --git a/README.zh-CN.md b/README.zh-CN.md index f1164002..b3ff4efc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -204,7 +204,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 -对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。 +对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。首个条目转换后,区域内可能同时存在两种值。旧客户端按 `AtomicInteger` 读取已转换条目会失败。回切时保持区域停用,先完成旧格式恢复验证,并核对仍有效的计数和截止时间。 对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index c50feac4..ab3e29db 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -152,6 +152,26 @@ public void migratesStoredLegacyCounterAcrossMembersWithoutRestartingExpiry() th assertNull(cache.get("alice")); } + @Test + public void legacyReaderCannotReuseARegionAfterAnotherMemberConvertsItsFirstEntry() { + String region = "legacy-rollback"; + Cache cache = firstManager.createCache(region, new MutableConfiguration() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf()) + .setStoreByValue(true)); + cache.put("alice", new AtomicInteger(3)); + cache.put("bob", new AtomicInteger(2)); + Cache secondCache = secondManager.getCache(region); + assertEquals(3, ((AtomicInteger) secondCache.get("alice")).get()); + + JCacheCredentialRetryStore store = new JCacheCredentialRetryStore(secondCache); + assertEquals(4, store.reserve("alice").getCount()); + + assertThrows(ClassCastException.class, () -> ((AtomicInteger) cache.get("alice")).get()); + assertEquals(2, ((AtomicInteger) cache.get("bob")).get()); + assertEquals(4, ((Attempt) cache.get("alice")).getCount()); + } + @Test public void rejectsTypedLegacyRegionBeforeItsFirstReservation() { Cache cache = firstManager.createCache("legacy-only", From 5d30150850b613ab7e1b734ecf39a60bf36e8550 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:57:15 +0800 Subject: [PATCH 35/50] Preserve active JCache retry windows during rollback Refs #6 --- README.md | 2 +- README.zh-CN.md | 2 +- .../jcache/JCacheCredentialRetryStore.java | 31 ++++++++++++++++ ...heCredentialRetryStoreIntegrationTest.java | 37 +++++++++++++++++++ 4 files changed, 70 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 679be2ae..e4b4b545 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ For native Ehcache 3, pause all retry clients, drain writes, and use exactly one For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. -For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. Once the first entry is converted, the region can contain both formats. A legacy reader fails when it reads a converted entry as `AtomicInteger`. Keep the region paused for a rollback until you have verified a legacy-compatible restore, including active counts and deadlines. +For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. Once the first entry is converted, the region can contain both formats. A legacy reader fails when it reads a converted entry as `AtomicInteger`. For rollback, pause all old and new retry clients and drain outstanding writes. Call `restoreLegacyWindow` for every converted principal using the same region. It restores an active counter in place with the current count and original deadline, leaving missing, expired or previously restored entries alone. Reconcile the region for remaining retry windows before resuming the legacy clients. For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. diff --git a/README.zh-CN.md b/README.zh-CN.md index b3ff4efc..da93ec9f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -204,7 +204,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 -对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。首个条目转换后,区域内可能同时存在两种值。旧客户端按 `AtomicInteger` 读取已转换条目会失败。回切时保持区域停用,先完成旧格式恢复验证,并核对仍有效的计数和截止时间。 +对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。首个条目转换后,区域内可能同时存在两种值。旧客户端按 `AtomicInteger` 读取已转换条目会失败。回切时暂停新旧客户端并等待在途写入完成。对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复仍有效的旧格式计数并保留原截止时间,跳过缺失、已过期和已恢复的条目。确认区域内没有遗留的新格式窗口后,再恢复旧客户端。 对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java index 40d45012..897b7b3d 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -19,6 +19,7 @@ public final class JCacheCredentialRetryStore implements CredentialRetryStore { private final Cache cache; + private final boolean acceptsLegacyCounters; /** * @param cache shared retry cache using store-by-value and a nonzero creation expiry @@ -36,6 +37,7 @@ public JCacheCredentialRetryStore(Cache cache) { } // Provider configuration validates the values that the entry processor writes. this.cache = (Cache) cache; + this.acceptsLegacyCounters = configuration.getValueType().isAssignableFrom(AtomicInteger.class); ExpiryPolicy policy = configuration.getExpiryPolicyFactory().create(); Duration creation = policy.getExpiryForCreation(); if (!configuration.isStoreByValue() || Objects.isNull(creation) || creation.isZero() @@ -54,6 +56,35 @@ public void clearIfCurrent(Object principal, String windowId) { cache.invoke(principal, Clear.INSTANCE, Objects.requireNonNull(windowId, "windowId")); } + /** + * Restores a live retry window to the legacy counter format in the same entry. + * Pause old and new retry clients and drain outstanding writes before restoring. + * + * @param principal original principal key in the shared retry region + * @return true when an active retry window was restored without changing its count or deadline + * @throws IllegalStateException when the region cannot store legacy counters + */ + public boolean restoreLegacyWindow(Object principal) { + if (!acceptsLegacyCounters) { + throw new IllegalStateException("JCache retry region must accept legacy counters for restore"); + } + return cache.invoke(principal, RestoreLegacy.INSTANCE); + } + + private enum RestoreLegacy implements EntryProcessor { + INSTANCE; + + @Override + public Boolean process(MutableEntry entry, Object... arguments) { + Object value = entry.getValue(); + if (value instanceof Attempt) { + entry.setValue(new AtomicInteger(((Attempt) value).getCount())); + return true; + } + return false; + } + } + private enum Reserve implements EntryProcessor { INSTANCE; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index ab3e29db..ac1c21b2 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -34,6 +34,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; @@ -172,6 +173,42 @@ public void legacyReaderCannotReuseARegionAfterAnotherMemberConvertsItsFirstEntr assertEquals(4, ((Attempt) cache.get("alice")).getCount()); } + @Test + public void restoresLegacyCountsWithoutRenewingOrRecreatingEntries() throws Exception { + String region = "legacy-restore"; + Cache cache = firstManager.createCache(region, new MutableConfiguration() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 4))) + .setStoreByValue(true)); + cache.put("alice", new AtomicInteger(3)); + long start = System.nanoTime(); + cache.put("bob", new AtomicInteger(2)); + JCacheCredentialRetryStore store = new JCacheCredentialRetryStore(secondManager.getCache(region)); + assertEquals(4, store.reserve("alice").getCount()); + awaitElapsed(start, 2000); + + assertTrue(store.restoreLegacyWindow("alice")); + assertEquals(4, ((AtomicInteger) cache.get("alice")).get()); + assertFalse(store.restoreLegacyWindow("alice")); + assertFalse(store.restoreLegacyWindow("bob")); + assertEquals(2, ((AtomicInteger) cache.get("bob")).get()); + assertFalse(store.restoreLegacyWindow("absent")); + assertNull(cache.get("absent")); + + awaitElapsed(start, 4400); + assertNull(cache.get("alice")); + assertFalse(store.restoreLegacyWindow("alice")); + } + + @Test + public void rejectsLegacyRestoreInAnAttemptOnlyCache() { + Cache cache = createCache("attempt-only-restore", EternalExpiryPolicy.factoryOf()); + JCacheCredentialRetryStore store = new JCacheCredentialRetryStore(cache); + Attempt initial = store.reserve("alice"); + assertThrows(IllegalStateException.class, () -> store.restoreLegacyWindow("alice")); + assertEquals(initial.getWindowId(), cache.get("alice").getWindowId()); + } + @Test public void rejectsTypedLegacyRegionBeforeItsFirstReservation() { Cache cache = firstManager.createCache("legacy-only", From b5d1aeebccf7a84a0ed34e367ca5f6a68b71d78c Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:01:06 +0800 Subject: [PATCH 36/50] Skip JCache read-through for missing retry entries during rollback Refs #6 --- .../jcache/JCacheCredentialRetryStore.java | 4 +++ ...heCredentialRetryStoreIntegrationTest.java | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java index 897b7b3d..3c053c30 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -76,6 +76,10 @@ private enum RestoreLegacy implements EntryProcessor { @Override public Boolean process(MutableEntry entry, Object... arguments) { + // Checking existence first keeps a read-through loader from recreating an expired entry. + if (!entry.exists()) { + return false; + } Object value = entry.getValue(); if (value instanceof Attempt) { entry.setValue(new AtomicInteger(((Attempt) value).getCount())); diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index ac1c21b2..f0394816 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -9,8 +9,10 @@ import java.net.InetAddress; import java.net.ServerSocket; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; @@ -22,12 +24,14 @@ import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.configuration.Factory; +import javax.cache.configuration.FactoryBuilder; import javax.cache.configuration.MutableConfiguration; import javax.cache.expiry.CreatedExpiryPolicy; import javax.cache.expiry.Duration; import javax.cache.expiry.EternalExpiryPolicy; import javax.cache.expiry.ExpiryPolicy; import javax.cache.expiry.ModifiedExpiryPolicy; +import javax.cache.integration.CacheLoader; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -200,6 +204,31 @@ public void restoresLegacyCountsWithoutRenewingOrRecreatingEntries() throws Exce assertFalse(store.restoreLegacyWindow("alice")); } + @Test + public void restoreDoesNotLoadMissingWindows() { + String region = "legacy-restore-read-through"; + Cache cache = firstManager.createCache(region, new MutableConfiguration() + .setTypes(Object.class, Object.class) + .setStoreByValue(true) + .setReadThrough(true) + .setCacheLoaderFactory(FactoryBuilder.factoryOf(ReadThroughRetryLoader.class))); + JCacheCredentialRetryStore store = new JCacheCredentialRetryStore(secondManager.getCache(region)); + assertFalse(store.restoreLegacyWindow("alice")); + assertFalse(cache.containsKey("alice")); + } + + public static final class ReadThroughRetryLoader implements CacheLoader { + @Override + public Object load(Object principal) { + return new Attempt("loaded", 3); + } + + @Override + public Map loadAll(Iterable principals) { + return Collections.emptyMap(); + } + } + @Test public void rejectsLegacyRestoreInAnAttemptOnlyCache() { Cache cache = createCache("attempt-only-restore", EternalExpiryPolicy.factoryOf()); From d42f63287eeb81197a2153cea9d85fd911c5986a Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:21:15 +0800 Subject: [PATCH 37/50] Support typed JCache retry window migration and rollback Refs #6 --- README.md | 2 +- README.zh-CN.md | 2 +- .../jcache/JCacheCredentialRetryStore.java | 61 +++++++++++++------ ...heCredentialRetryStoreIntegrationTest.java | 35 ++++++++++- 4 files changed, 79 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index e4b4b545..592f9648 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ For native Ehcache 3, pause all retry clients, drain writes, and use exactly one For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. -For a JCache retry region that already accepts both value types (for example, with value type `Object`), stop the legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. Regions configured to accept only `AtomicInteger` require a separate cutover because they cannot store the new window format. Once the first entry is converted, the region can contain both formats. A legacy reader fails when it reads a converted entry as `AtomicInteger`. For rollback, pause all old and new retry clients and drain outstanding writes. Call `restoreLegacyWindow` for every converted principal using the same region. It restores an active counter in place with the current count and original deadline, leaving missing, expired or previously restored entries alone. Reconcile the region for remaining retry windows before resuming the legacy clients. +For an existing JCache retry region, stop legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. A region that accepts both value types, for example with value type `Object`, stores retry windows directly. A region typed as `AtomicInteger` stores a serializable counter subtype holding the window ID. Verify that the provider and its configured serializer retain the subtype and deploy this module to every executing member before cutover. Typed migration was verified on a two-member Hazelcast JCache cluster. For rollback, pause all retry clients, drain outstanding writes, and call `restoreLegacyWindow` for every converted principal in the original region. It restores a plain `AtomicInteger` with the current count and original deadline. It skips missing, expired, and restored entries. Check for any remaining converted entries before resuming legacy clients. For Spring Data Redis, pause all old and new retry clients and wait for outstanding cache writes to reach Redis before importing. Call the adapter’s `migrateLegacyWindow` for each known string principal with the original cache and the distinct destination namespace used by the new store. The import copies the saved count and absolute Redis expiry using the source cache’s key and value serializers. It leaves source entries intact and skips missing, expired, and occupied destinations. Reconcile the submitted principals before resuming clients and finish all imports during the same cutover. If the new policy uses time-to-idle, it applies on the next reservation. diff --git a/README.zh-CN.md b/README.zh-CN.md index da93ec9f..ee5fc76a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -204,7 +204,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 -对于原本就接受两种值类型的 JCache 重试区域(例如值类型为 `Object`),停止旧客户端后沿用原区域和主体键。JCache 条目处理器会在同一次更新中转换已保存的计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留创建时确定的截止时间。值类型仅允许 `AtomicInteger` 的区域需要单独切换,因为该区域无法存储新窗口格式。首个条目转换后,区域内可能同时存在两种值。旧客户端按 `AtomicInteger` 读取已转换条目会失败。回切时暂停新旧客户端并等待在途写入完成。对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复仍有效的旧格式计数并保留原截止时间,跳过缺失、已过期和已恢复的条目。确认区域内没有遗留的新格式窗口后,再恢复旧客户端。 +对于现有 JCache 重试区域,停止旧客户端后沿用原区域和主体键。条目处理器会在同一次更新中转换计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留原截止时间。值类型允许两种格式的区域(例如 `Object`)直接存储重试窗口。值类型为 `AtomicInteger` 的区域使用可序列化的计数器子类保存窗口标识。切换前验证提供方及其序列化配置能保留子类,并在所有执行节点部署此模块。该类型区域的迁移已在双节点 Hazelcast JCache 集群验证。回切时暂停所有重试客户端,等待在途写入完成,然后对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复普通 `AtomicInteger`,保留当前计数和原截止时间,跳过缺失、过期或已恢复条目。检查区域中是否仍有已转换条目,再恢复旧客户端。 对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java index 3c053c30..eed754e2 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -20,24 +20,28 @@ public final class JCacheCredentialRetryStore implements CredentialRetryStore { private final Cache cache; private final boolean acceptsLegacyCounters; + private final boolean usesTypedCounters; /** * @param cache shared retry cache using store-by-value and a nonzero creation expiry * or eternal expiry. Its expiry policy must leave the deadline unchanged * on both access and update. All cluster members must have this module. - * To migrate legacy counters, reuse a region that accepts both value - * types after stopping all legacy clients. + * To migrate legacy counters, stop legacy clients before reusing + * the region. An AtomicInteger-typed region must preserve the + * serializable counter subtype and its window ID. */ @SuppressWarnings("unchecked") public JCacheCredentialRetryStore(Cache cache) { CompleteConfiguration configuration = Objects.requireNonNull(cache, "cache").getConfiguration(CompleteConfiguration.class); - if (!configuration.getValueType().isAssignableFrom(Attempt.class)) { + Class valueType = configuration.getValueType(); + this.usesTypedCounters = AtomicInteger.class.equals(valueType); + if (!usesTypedCounters && !valueType.isAssignableFrom(Attempt.class)) { throw new IllegalArgumentException("JCache retry region must accept credential retry attempts"); } // Provider configuration validates the values that the entry processor writes. this.cache = (Cache) cache; - this.acceptsLegacyCounters = configuration.getValueType().isAssignableFrom(AtomicInteger.class); + this.acceptsLegacyCounters = valueType.isAssignableFrom(AtomicInteger.class); ExpiryPolicy policy = configuration.getExpiryPolicyFactory().create(); Duration creation = policy.getExpiryForCreation(); if (!configuration.isStoreByValue() || Objects.isNull(creation) || creation.isZero() @@ -48,7 +52,7 @@ public JCacheCredentialRetryStore(Cache cache) { @Override public Attempt reserve(Object principal) { - return cache.invoke(principal, Reserve.INSTANCE, UUID.randomUUID().toString()); + return cache.invoke(principal, Reserve.INSTANCE, UUID.randomUUID().toString(), usesTypedCounters); } @Override @@ -71,6 +75,27 @@ public boolean restoreLegacyWindow(Object principal) { return cache.invoke(principal, RestoreLegacy.INSTANCE); } + private static Attempt storedAttempt(Object value) { + if (value instanceof Attempt) { + return (Attempt) value; + } + if (value instanceof TypedCounter) { + TypedCounter counter = (TypedCounter) value; + return new Attempt(counter.windowId, counter.get()); + } + return null; + } + + private static final class TypedCounter extends AtomicInteger { + private static final long serialVersionUID = 1L; + private final String windowId; + + private TypedCounter(Attempt attempt) { + super(attempt.getCount()); + this.windowId = attempt.getWindowId(); + } + } + private enum RestoreLegacy implements EntryProcessor { INSTANCE; @@ -80,9 +105,9 @@ public Boolean process(MutableEntry entry, Object... arguments) if (!entry.exists()) { return false; } - Object value = entry.getValue(); - if (value instanceof Attempt) { - entry.setValue(new AtomicInteger(((Attempt) value).getCount())); + Attempt current = storedAttempt(entry.getValue()); + if (Objects.nonNull(current)) { + entry.setValue(new AtomicInteger(current.getCount())); return true; } return false; @@ -95,8 +120,14 @@ private enum Reserve implements EntryProcessor { @Override public Attempt process(MutableEntry entry, Object... arguments) { Object value = entry.getValue(); + Attempt current = storedAttempt(value); Attempt next; - if (Objects.isNull(value)) { + if (Objects.nonNull(current)) { + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } + next = new Attempt(current.getWindowId(), current.getCount() + 1); + } else if (Objects.isNull(value)) { next = new Attempt((String) arguments[0], 1); } else if (value instanceof AtomicInteger) { int count = ((AtomicInteger) value).get(); @@ -105,13 +136,9 @@ public Attempt process(MutableEntry entry, Object... arguments) } next = new Attempt((String) arguments[0], count == Integer.MAX_VALUE ? count : count + 1); } else { - Attempt current = (Attempt) value; - if (current.getCount() == Integer.MAX_VALUE) { - return current; - } - next = new Attempt(current.getWindowId(), current.getCount() + 1); + throw new CacheException("JCache retry entry contains an unsupported value"); } - entry.setValue(next); + entry.setValue(Boolean.TRUE.equals(arguments[1]) ? new TypedCounter(next) : next); return next; } } @@ -121,8 +148,8 @@ private enum Clear implements EntryProcessor { @Override public Void process(MutableEntry entry, Object... arguments) { - Object value = entry.getValue(); - if (value instanceof Attempt && ((Attempt) value).getWindowId().equals(arguments[0])) { + Attempt current = storedAttempt(entry.getValue()); + if (Objects.nonNull(current) && current.getWindowId().equals(arguments[0])) { entry.remove(); } return null; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java index f0394816..08756d15 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -239,10 +239,41 @@ public void rejectsLegacyRestoreInAnAttemptOnlyCache() { } @Test - public void rejectsTypedLegacyRegionBeforeItsFirstReservation() { - Cache cache = firstManager.createCache("legacy-only", + public void migratesAndRestoresTypedLegacyRegionWithoutRestartingExpiry() throws Exception { + String region = "typed-legacy-expiration"; + Cache cache = firstManager.createCache(region, new MutableConfiguration() .setTypes(Object.class, AtomicInteger.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 5))) + .setStoreByValue(true)); + Cache replica = secondManager.getCache(region, Object.class, AtomicInteger.class); + cache.put("alice", new AtomicInteger(3)); + long start = System.nanoTime(); + JCacheCredentialRetryStore first = new JCacheCredentialRetryStore(cache); + JCacheCredentialRetryStore second = new JCacheCredentialRetryStore(replica); + awaitElapsed(start, 2200); + + Attempt migrated = second.reserve("alice"); + assertEquals(4, migrated.getCount()); + first.clearIfCurrent("alice", "previous-window"); + Attempt next = first.reserve("alice"); + assertEquals(5, next.getCount()); + assertEquals(migrated.getWindowId(), next.getWindowId()); + assertTrue(second.restoreLegacyWindow("alice")); + assertEquals(AtomicInteger.class, cache.get("alice").getClass()); + assertEquals(5, cache.get("alice").get()); + assertFalse(first.restoreLegacyWindow("alice")); + + awaitElapsed(start, 5300); + assertNull(replica.get("alice")); + assertEquals(1, second.reserve("alice").getCount()); + } + + @Test + public void rejectsRegionThatCannotHoldRetryState() { + Cache cache = firstManager.createCache("unrelated-type", + new MutableConfiguration() + .setTypes(Object.class, String.class) .setExpiryPolicyFactory(EternalExpiryPolicy.factoryOf())); assertThrows(IllegalArgumentException.class, () -> new JCacheCredentialRetryStore(cache)); } From d0bba0f85f4bf27343cb9f9b16fcbfb4b2f4299d Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:37:19 +0800 Subject: [PATCH 38/50] Support retry migration over authenticated Memcached Meta connections Refs #6 --- README.md | 2 +- README.zh-CN.md | 2 +- .../J2CacheMemcachedCredentialRetryStore.java | 39 ++++++++- .../cache/j2cache/MemcachedLegacyWindow.java | 84 ++++++++++--------- ...edCredentialRetryStoreIntegrationTest.java | 54 +++++++++++- 5 files changed, 135 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 592f9648..d2df2ba9 100644 --- a/README.md +++ b/README.md @@ -210,7 +210,7 @@ For Spring Data Redis, pause all old and new retry clients and wait for outstand The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. For legacy keys that use the JVM default charset, run migration with the charset that wrote the source region. Jedis routes the expiry lookup using the original binary key. For non-UTF-8 Lettuce keys, supply a binary scripting connection in addition to the UTF-8 destination connection. -The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Pass the source server that owns the legacy key and accepts unauthenticated Memcached Meta Text on a trusted connection. The adapter reads the value and its remaining TTL together, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. Select source servers using the original key routing. Binary-only or authenticated source servers require a separate migration path. +The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. diff --git a/README.zh-CN.md b/README.zh-CN.md index ee5fc76a..aa6a6986 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -210,7 +210,7 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。迁移按 JVM 默认字符集写入的旧键时,沿用原字符集。Jedis 按原二进制键查询截止时间。对于非 UTF-8 的 Lettuce 旧键,除 UTF-8 目标连接外,还需传入二进制脚本连接。 -J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由传入保存旧值的源节点,该节点需允许在可信连接上使用无需认证的 Memcached Meta Text 协议。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议或需要认证的源节点需要独立迁移方式。 +J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 0775d03f..6acbe968 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.net.InetSocketAddress; +import java.net.Socket; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -132,15 +133,41 @@ public void clearIfCurrent(Object principal, String windowId) { * @return true when the counter was copied to an empty destination */ public boolean migrateLegacyWindow(String principal, InetSocketAddress source) { - Objects.requireNonNull(principal, "principal"); Objects.requireNonNull(source, "source"); + int timeout = (int) Math.max(1, Math.min(client.getOpTimeout(), Integer.MAX_VALUE)); + return migrateLegacyWindow(principal, key -> MemcachedLegacyWindow.read(source, key, timeout)); + } + + /** + * Copies a legacy counter through a dedicated, already authenticated Meta Text connection. + * The caller owns the socket and must close it after use, including after errors. + * Pause retry clients and drain outstanding writes before importing. + * + * @param principal original string principal in the J2Cache region + * @param source connected socket to the server owning the legacy key, with a read timeout + * @return true when the counter was copied to an empty destination + */ + public boolean migrateLegacyWindowFromMetaConnection(String principal, Socket source) { + Objects.requireNonNull(source, "source"); + if (!source.isConnected() || source.isClosed()) { + throw new IllegalArgumentException("The Memcached source connection must be open"); + } + return migrateLegacyWindow(principal, key -> { + if (source.getSoTimeout() <= 0) { + throw new IllegalArgumentException("The Memcached source connection requires a read timeout"); + } + return MemcachedLegacyWindow.read(source, key); + }); + } + + private boolean migrateLegacyWindow(String principal, LegacyRead source) { + Objects.requireNonNull(principal, "principal"); try { String legacyKey = legacyRegion + ":" + principal; if (legacySanitizeKeys) { legacyKey = URLEncoder.encode(legacyKey, StandardCharsets.UTF_8.name()); } - int timeout = (int) Math.max(1, Math.min(client.getOpTimeout(), Integer.MAX_VALUE)); - MemcachedLegacyWindow legacy = MemcachedLegacyWindow.read(source, legacyKey, timeout); + MemcachedLegacyWindow legacy = source.read(legacyKey); if (Objects.isNull(legacy) || (legacy.getDeadline() > 0 && legacy.getDeadline() <= Instant.now().getEpochSecond())) { return false; } @@ -154,6 +181,12 @@ public boolean migrateLegacyWindow(String principal, InetSocketAddress source) { } } + @FunctionalInterface + private interface LegacyRead { + + MemcachedLegacyWindow read(String key) throws IOException; + } + private Window newWindow() { return new Window(UUID.randomUUID().toString(), 1, initialDeadline()); } diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java index c591f739..4f634c07 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java @@ -29,51 +29,55 @@ class MemcachedLegacyWindow { int deadline; static MemcachedLegacyWindow read(InetSocketAddress source, String key, int timeoutMillis) throws IOException { + try (Socket socket = new Socket()) { + socket.connect(source, timeoutMillis); + socket.setSoTimeout(timeoutMillis); + return read(socket, key); + } + } + + static MemcachedLegacyWindow read(Socket socket, String key) throws IOException { byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); if (keyBytes.length == 0 || keyBytes.length > 250) { throw new IllegalArgumentException("Invalid legacy Memcached key length"); } String request = "mg " + Base64.getEncoder().encodeToString(keyBytes) + " b t f v u"; - try (Socket socket = new Socket()) { - socket.connect(source, timeoutMillis); - socket.setSoTimeout(timeoutMillis); - DataInputStream input = new DataInputStream(new BufferedInputStream(socket.getInputStream())); - OutputStream output = socket.getOutputStream(); - for (int attempt = 0; attempt < MAX_CLOCK_ATTEMPTS; attempt++) { - long before = time(input, output); - command(output, request); - String response = line(input); - if ("EN".equals(response)) { - return null; - } - String[] fields = StringUtils.split(response); - if (Objects.isNull(fields) || fields.length < 4 || !"VA".equals(fields[0])) { - throw new CacheException("Memcached source does not support meta value and expiry reads"); - } - int bytes = Integer.parseInt(fields[1]); - if (bytes <= 0 || bytes > MAX_COUNTER_BYTES) { - throw new CacheException("Invalid legacy Memcached counter size"); - } - int ttl = Integer.parseInt(flag(fields, 't')); - int flags = Integer.parseUnsignedInt(flag(fields, 'f')); - byte[] payload = new byte[bytes]; - input.readFully(payload); - if (StringUtils.isNotEmpty(line(input))) { - throw new CacheException("Invalid legacy Memcached value terminator"); - } - if (ttl == 0) { - return null; - } - if (ttl == -1) { - return decode(payload, flags, 0); - } - if (ttl < -1) { - throw new CacheException("Invalid legacy Memcached expiry"); - } - // Both samples must belong to the server second in which it computed the remaining TTL. - if (before == time(input, output)) { - return decode(payload, flags, Math.toIntExact(before + ttl)); - } + DataInputStream input = new DataInputStream(new BufferedInputStream(socket.getInputStream())); + OutputStream output = socket.getOutputStream(); + for (int attempt = 0; attempt < MAX_CLOCK_ATTEMPTS; attempt++) { + long before = time(input, output); + command(output, request); + String response = line(input); + if ("EN".equals(response)) { + return null; + } + String[] fields = StringUtils.split(response); + if (Objects.isNull(fields) || fields.length < 4 || !"VA".equals(fields[0])) { + throw new CacheException("Memcached source does not support meta value and expiry reads"); + } + int bytes = Integer.parseInt(fields[1]); + if (bytes <= 0 || bytes > MAX_COUNTER_BYTES) { + throw new CacheException("Invalid legacy Memcached counter size"); + } + int ttl = Integer.parseInt(flag(fields, 't')); + int flags = Integer.parseUnsignedInt(flag(fields, 'f')); + byte[] payload = new byte[bytes]; + input.readFully(payload); + if (StringUtils.isNotEmpty(line(input))) { + throw new CacheException("Invalid legacy Memcached value terminator"); + } + if (ttl == 0) { + return null; + } + if (ttl == -1) { + return decode(payload, flags, 0); + } + if (ttl < -1) { + throw new CacheException("Invalid legacy Memcached expiry"); + } + // Both samples must belong to the server second in which it computed the remaining TTL. + if (before == time(input, output)) { + return decode(payload, flags, Math.toIntExact(before + ttl)); } } throw new CacheException("Could not determine the legacy Memcached deadline at server precision"); diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 2e07dc4c..efd3e3fc 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -1,6 +1,10 @@ package org.apache.shiro.biz.cache.j2cache; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.Socket; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; @@ -25,6 +29,8 @@ import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.command.BinaryCommandFactory; +import net.rubyeye.xmemcached.transcoders.CachedData; +import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; import net.rubyeye.xmemcached.transcoders.StringTranscoder; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; @@ -128,7 +134,14 @@ public void copiesTheLegacyCounterWithItsExactDeadlineAndPersistentZero() throws String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); assertEquals(3, ((AtomicInteger) source.get(principal)).get()); - assertTrue(store.migrateLegacyWindow("persistent", address)); + try (Socket connection = new Socket()) { + connection.connect(address, 3000); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromMetaConnection("persistent", connection)); + connection.setSoTimeout(3000); + assertTrue(store.migrateLegacyWindowFromMetaConnection("persistent", connection)); + assertFalse(store.migrateLegacyWindowFromMetaConnection("persistent", connection)); + } Attempt persistent = store.reserve("persistent"); assertEquals(1, persistent.getCount()); String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest("persistent"); @@ -136,6 +149,45 @@ public void copiesTheLegacyCounterWithItsExactDeadlineAndPersistentZero() throws } } + @Test + public void importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline() throws Exception { + String authPort = System.getProperty("shiro.memcached.auth.test.port"); + assumeTrue("Supply an isolated Memcached ASCII authentication port", Objects.nonNull(authPort)); + SerializationUtils.init("java", new Properties()); + J2CacheConfig config = config(true, "30s"); + String principal = "authenticated-cutover"; + int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 15); + byte[] credentials = "fixture-user fixture-password".getBytes(StandardCharsets.US_ASCII); + CachedData seed = new SerializingTranscoder().encode(SerializationUtils.serialize(new AtomicInteger(3))); + byte[] payload = seed.getData(); + try (Socket source = new Socket("127.0.0.1", Integer.parseInt(authPort)); + CacheChannel channel = J2CacheTestChannel.open(config)) { + source.setSoTimeout(3000); + BufferedReader reply = new BufferedReader(new InputStreamReader(source.getInputStream(), StandardCharsets.US_ASCII)); + OutputStream requests = source.getOutputStream(); + requests.write(("set auth 0 0 " + credentials.length + "\r\n").getBytes(StandardCharsets.US_ASCII)); + requests.write(credentials); + requests.write("\r\n".getBytes(StandardCharsets.US_ASCII)); + requests.flush(); + assertEquals("STORED", reply.readLine()); + String set = "set " + REGION + ":" + principal + " " + seed.getFlag() + " " + deadline + + " " + payload.length + "\r\n"; + requests.write(set.getBytes(StandardCharsets.US_ASCII)); + requests.write(payload); + requests.write("\r\n".getBytes(StandardCharsets.US_ASCII)); + requests.flush(); + assertEquals("STORED", reply.readLine()); + + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + assertTrue(store.migrateLegacyWindowFromMetaConnection(principal, source)); + assertFalse(store.migrateLegacyWindowFromMetaConnection(principal, source)); + Attempt next = store.reserve(principal); + assertEquals(4, next.getCount()); + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); + } + } + @Test public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { J2CacheConfig config = config(true, "4s"); From dbd0cf908852238be53b802fcb1397a46884aaba Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:41:51 +0800 Subject: [PATCH 39/50] ci: exercise authenticated Memcached migration in Shiro verification Refs #6 --- .github/workflows/main-ci.yml | 49 ++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index d091bc07..32bb2ca7 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -41,9 +41,52 @@ jobs: - name: Verify Shiro extension env: RETRY_REDIS_CONTAINER: ${{ job.services.redis.id }} - RETRY_REDIS_PORT: ${{ job.services.redis.ports[6379] }} - RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports[11211] }} - run: mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" -Dshiro.redis.test.container="${RETRY_REDIS_CONTAINER}" -Dshiro.redis.test.port="${RETRY_REDIS_PORT}" -Dshiro.memcached.test.port="${RETRY_MEMCACHED_PORT}" clean verify + RETRY_REDIS_PORT: ${{ job.services.redis.ports['6379'] }} + RETRY_MEMCACHED_PORT: ${{ job.services.memcached.ports['11211'] }} + shell: bash + run: | + set -euo pipefail + auth_file=$(mktemp "${RUNNER_TEMP}/memcached-auth.XXXXXX") + auth_container= + cleanup() { + if [[ -n "$auth_container" ]]; then + docker rm -f "$auth_container" >/dev/null + fi + rm -f "$auth_file" + } + trap cleanup EXIT + # Local CI fixture only. The container reads this as its non-root user. + printf '%s\n' 'fixture-user:fixture-password' > "$auth_file" + chmod 0644 "$auth_file" + auth_container=$(docker run -d --publish 127.0.0.1::11211/tcp \ + --mount "type=bind,src=$auth_file,dst=/memcached-auth,readonly" \ + memcached:1.6.45-alpine memcached -U 0 -Y /memcached-auth) + binding=$(docker port "$auth_container" 11211/tcp) + auth_port=${binding##*:} + [[ "$auth_port" =~ ^[0-9]+$ ]] + for attempt in {1..40}; do + if (: < "/dev/tcp/127.0.0.1/$auth_port") 2>/dev/null; then + break + fi + if (( attempt == 40 )); then + docker logs "$auth_container" + exit 1 + fi + sleep 0.25 + done + mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ + -Dshiro.redis.test.container="$RETRY_REDIS_CONTAINER" -Dshiro.redis.test.port="$RETRY_REDIS_PORT" \ + -Dshiro.memcached.test.port="$RETRY_MEMCACHED_PORT" -Dshiro.memcached.auth.test.port="$auth_port" clean verify + python3 - <<'PYTHON' + from pathlib import Path + from xml.etree import ElementTree + + reports = Path("shiro-extension-core/target/surefire-reports") + suite = ElementTree.parse(next(reports.glob("TEST-*J2CacheMemcachedCredentialRetryStoreIntegrationTest.xml"))) + case = suite.find('./testcase[@name="importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline"]') + if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")): + raise SystemExit("Expected an executed, successful authenticated Memcached migration test") + PYTHON - name: Verify J2Cache and Redisson retry migration on Redis Cluster shell: bash run: | From d928a556665bd7cf621310bd2c8c20e8dbb0f05c Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:51:28 +0800 Subject: [PATCH 40/50] Test binary-only Memcached retry cutover boundary --- .github/workflows/main-ci.yml | 49 ++++++++++++------- README.md | 2 +- README.zh-CN.md | 2 +- ...edCredentialRetryStoreIntegrationTest.java | 39 +++++++++++++-- 4 files changed, 69 insertions(+), 23 deletions(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 32bb2ca7..135d83e6 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -48,10 +48,14 @@ jobs: set -euo pipefail auth_file=$(mktemp "${RUNNER_TEMP}/memcached-auth.XXXXXX") auth_container= + binary_container= cleanup() { if [[ -n "$auth_container" ]]; then docker rm -f "$auth_container" >/dev/null fi + if [[ -n "$binary_container" ]]; then + docker rm -f "$binary_container" >/dev/null + fi rm -f "$auth_file" } trap cleanup EXIT @@ -61,31 +65,42 @@ jobs: auth_container=$(docker run -d --publish 127.0.0.1::11211/tcp \ --mount "type=bind,src=$auth_file,dst=/memcached-auth,readonly" \ memcached:1.6.45-alpine memcached -U 0 -Y /memcached-auth) - binding=$(docker port "$auth_container" 11211/tcp) - auth_port=${binding##*:} - [[ "$auth_port" =~ ^[0-9]+$ ]] - for attempt in {1..40}; do - if (: < "/dev/tcp/127.0.0.1/$auth_port") 2>/dev/null; then - break - fi - if (( attempt == 40 )); then - docker logs "$auth_container" - exit 1 - fi - sleep 0.25 - done + binary_container=$(docker run -d --publish 127.0.0.1::11211/tcp \ + memcached:1.6.45-alpine memcached -U 0 -B binary) + ready_port() { + local container=$1 binding port + binding=$(docker port "$container" 11211/tcp) + port=${binding##*:} + [[ "$port" =~ ^[0-9]+$ ]] || return 1 + for attempt in {1..40}; do + if (: < "/dev/tcp/127.0.0.1/$port") 2>/dev/null; then + printf '%s\n' "$port" + return + fi + sleep 0.25 + done + docker logs "$container" >&2 + return 1 + } + auth_port=$(ready_port "$auth_container") + binary_port=$(ready_port "$binary_container") mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ -Dshiro.redis.test.container="$RETRY_REDIS_CONTAINER" -Dshiro.redis.test.port="$RETRY_REDIS_PORT" \ - -Dshiro.memcached.test.port="$RETRY_MEMCACHED_PORT" -Dshiro.memcached.auth.test.port="$auth_port" clean verify + -Dshiro.memcached.test.port="$RETRY_MEMCACHED_PORT" -Dshiro.memcached.auth.test.port="$auth_port" \ + -Dshiro.memcached.binary.test.port="$binary_port" clean verify python3 - <<'PYTHON' from pathlib import Path from xml.etree import ElementTree reports = Path("shiro-extension-core/target/surefire-reports") suite = ElementTree.parse(next(reports.glob("TEST-*J2CacheMemcachedCredentialRetryStoreIntegrationTest.xml"))) - case = suite.find('./testcase[@name="importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline"]') - if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")): - raise SystemExit("Expected an executed, successful authenticated Memcached migration test") + for name in ( + "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", + "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", + ): + case = suite.find(f'./testcase[@name="{name}"]') + if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")): + raise SystemExit(f"Expected an executed, successful Memcached test: {name}") PYTHON - name: Verify J2Cache and Redisson retry migration on Redis Cluster shell: bash diff --git a/README.md b/README.md index d2df2ba9..62b1d2b5 100644 --- a/README.md +++ b/README.md @@ -210,7 +210,7 @@ For Spring Data Redis, pause all old and new retry clients and wait for outstand The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for each known string principal during an exclusive cutover. Import reads the saved L2 counter using the channel’s serializer, preserves the Redis deadline for generic keys or the hash region, and creates only absent destination windows. Keep the original provider configuration and use a distinct destination namespace. For legacy keys that use the JVM default charset, run migration with the charset that wrote the source region. Jedis routes the expiry lookup using the original binary key. For non-UTF-8 Lettuce keys, supply a binary scripting connection in addition to the UTF-8 destination connection. -The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. +The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one. For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. diff --git a/README.zh-CN.md b/README.zh-CN.md index aa6a6986..0b46f5ca 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -210,7 +210,7 @@ Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所 J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。迁移按 JVM 默认字符集写入的旧键时,沿用原字符集。Jedis 按原二进制键查询截止时间。对于非 UTF-8 的 Lettuce 旧键,除 UTF-8 目标连接外,还需传入二进制脚本连接。 -J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 +J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index efd3e3fc..5f77fd5c 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -34,6 +34,7 @@ import net.rubyeye.xmemcached.transcoders.StringTranscoder; import net.rubyeye.xmemcached.utils.AddrUtil; import org.apache.shiro.biz.authc.credential.CredentialRetryStore.Attempt; +import org.apache.shiro.cache.CacheException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -41,6 +42,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -58,8 +60,8 @@ public void connect() throws Exception { String port = System.getProperty("shiro.memcached.test.port"); assumeTrue("Supply an isolated Memcached port", Objects.nonNull(port)); endpoint = "127.0.0.1:" + port; - firstClient = client(); - secondClient = client(); + firstClient = client(endpoint); + secondClient = client(endpoint); } @After @@ -188,6 +190,35 @@ public void importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline() } } + @Test + public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws Exception { + String binaryPort = System.getProperty("shiro.memcached.binary.test.port"); + assumeTrue("Supply an isolated binary-only Memcached port", Objects.nonNull(binaryPort)); + String binaryEndpoint = "127.0.0.1:" + binaryPort; + SerializationUtils.init("java", new Properties()); + J2CacheConfig config = config(true, "30s"); + String principal = "binary-cutover-" + UUID.randomUUID(); + String legacyKey = REGION + ":" + principal; + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + SerializingTranscoder transcoder = new SerializingTranscoder(); + byte[] counter = SerializationUtils.serialize(new AtomicInteger(3)); + MemcachedClient legacy = client(binaryEndpoint); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + assertTrue(legacy.set(legacyKey, 120, counter, transcoder)); + byte[] storedCounter = (byte[]) legacy.get(legacyKey, transcoder); + assertEquals(3, ((AtomicInteger) SerializationUtils.deserialize(storedCounter)).get()); + long originalCas = legacy.gets(legacyKey, transcoder).getCas(); + + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + assertThrows(CacheException.class, + () -> store.migrateLegacyWindow(principal, AddrUtil.getOneAddress(binaryEndpoint))); + assertNull(firstClient.get(target, new StringTranscoder())); + assertEquals(originalCas, legacy.gets(legacyKey, transcoder).getCas()); + } finally { + legacy.shutdown(); + } + } + @Test public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { J2CacheConfig config = config(true, "4s"); @@ -253,8 +284,8 @@ private J2CacheConfig config(boolean syncTtl, String ttl) { return config; } - private MemcachedClient client() throws Exception { - var builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(endpoint)); + private MemcachedClient client(String server) throws Exception { + var builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(server)); builder.setCommandFactory(new BinaryCommandFactory()); return builder.build(); } From 5c10c05d929f1ead90dc08c261f7853220bf9355 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:54:51 +0800 Subject: [PATCH 41/50] Use the observed Redisson write interval for expiry assertions --- .../RedissonCredentialRetryStoreIntegrationTest.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java index fd833158..356eb3c2 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java @@ -102,10 +102,15 @@ public void migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline() throws E assertDifferentPrimaries(mapName, namespace + ":principal"); RMapCache source = firstClient.getMapCache(mapName, new CompositeCodec(StringCodec.INSTANCE, new SerializationCodec(), new SerializationCodec())); + long beforeWrite = System.currentTimeMillis(); source.put("principal", new AtomicInteger(3), 7000, TimeUnit.MILLISECONDS, 6000, TimeUnit.MILLISECONDS); + long afterWrite = System.currentTimeMillis(); long ttl = sourceDeadline(mapName, "redisson__timeout__set"); long idle = sourceDeadline(mapName, "redisson__idle__set"); - assertEquals(1000L, ttl - idle); + // Redisson samples the clock separately for the two expiration policies. + assertTrue(ttl >= beforeWrite + 7000 && ttl <= afterWrite + 7000); + assertTrue(idle >= beforeWrite + 6000 && idle <= afterWrite + 6000); + assertTrue(idle < ttl); RedissonCredentialRetryStore store = store(secondClient, Duration.ofSeconds(30), Duration.ofSeconds(30)); assertTrue(store.migrateLegacyWindow(source, "principal")); assertFalse(store.migrateLegacyWindow(source, "principal")); From 38146cd7a34002ec8900ddd8d0b0c48b3ead2d8b Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:59:50 +0800 Subject: [PATCH 42/50] docs: verify warm restart for binary Memcached retry cutover --- README.md | 3 +++ README.zh-CN.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/README.md b/README.md index 62b1d2b5..45731ac1 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,9 @@ The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for eac The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one. +If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture restored a finite window with its exact original deadline and restored a persistent window with no deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. + + For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. ## 8. Core Usage / API diff --git a/README.zh-CN.md b/README.zh-CN.md index 0b46f5ca..a180ecb3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -212,6 +212,9 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 +如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试保留了限时窗口的原始截止时间和永久窗口的无截止状态,停机期间已过期的窗口也未恢复。此方式要求在写入旧窗口前已启用热重启。 + + 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 ## 8. Core Usage / API From e75b4797088ba2de5b07428629b55c696d9ddb26 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:03:06 +0800 Subject: [PATCH 43/50] test: verify retry migration after Memcached warm restart --- .github/workflows/main-ci.yml | 20 +++- ...edCredentialRetryStoreIntegrationTest.java | 92 +++++++++++++++++++ 2 files changed, 111 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 135d83e6..21f767af 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -49,6 +49,7 @@ jobs: auth_file=$(mktemp "${RUNNER_TEMP}/memcached-auth.XXXXXX") auth_container= binary_container= + warm_container= cleanup() { if [[ -n "$auth_container" ]]; then docker rm -f "$auth_container" >/dev/null @@ -56,6 +57,9 @@ jobs: if [[ -n "$binary_container" ]]; then docker rm -f "$binary_container" >/dev/null fi + if [[ -n "$warm_container" ]]; then + docker rm -f "$warm_container" >/dev/null + fi rm -f "$auth_file" } trap cleanup EXIT @@ -67,6 +71,17 @@ jobs: memcached:1.6.45-alpine memcached -U 0 -Y /memcached-auth) binary_container=$(docker run -d --publish 127.0.0.1::11211/tcp \ memcached:1.6.45-alpine memcached -U 0 -B binary) + warm_container=$(docker run -d --user 0 --publish 127.0.0.1::11211/tcp \ + --tmpfs /state:rw,size=96m memcached:1.6.45-alpine sh -ec ' + chown memcache /state + memcached -u memcache -U 0 -m 64 -B binary -e /state/memory & + child=$! + echo "$child" >/state/source.pid + wait "$child" + # The server requires the clock to advance beyond the saved stop second. + sleep 2 + exec memcached -u memcache -U 0 -m 64 -B ascii -e /state/memory + ') ready_port() { local container=$1 binding port binding=$(docker port "$container" 11211/tcp) @@ -84,10 +99,12 @@ jobs: } auth_port=$(ready_port "$auth_container") binary_port=$(ready_port "$binary_container") + warm_port=$(ready_port "$warm_container") mvn -B -ntp -s .github/maven-central-settings.xml -Dmaven.repo.local="${RUNNER_TEMP}/verified-m2" \ -Dshiro.redis.test.container="$RETRY_REDIS_CONTAINER" -Dshiro.redis.test.port="$RETRY_REDIS_PORT" \ -Dshiro.memcached.test.port="$RETRY_MEMCACHED_PORT" -Dshiro.memcached.auth.test.port="$auth_port" \ - -Dshiro.memcached.binary.test.port="$binary_port" clean verify + -Dshiro.memcached.binary.test.port="$binary_port" -Dshiro.memcached.warm.test.port="$warm_port" \ + -Dshiro.memcached.warm.test.container="$warm_container" clean verify python3 - <<'PYTHON' from pathlib import Path from xml.etree import ElementTree @@ -97,6 +114,7 @@ jobs: for name in ( "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", + "importsLegacyWindowsAfterBinarySourceWarmRestart", ): case = suite.find(f'./testcase[@name="{name}"]') if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")): diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 5f77fd5c..7b3e8769 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -1,10 +1,12 @@ package org.apache.shiro.biz.cache.j2cache; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.time.Instant; @@ -219,6 +221,96 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E } } + @Test + public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception { + String sourcePort = System.getProperty("shiro.memcached.warm.test.port"); + String container = System.getProperty("shiro.memcached.warm.test.container"); + assumeTrue("Supply a dedicated warm-restart Memcached fixture", + Objects.nonNull(sourcePort) && Objects.nonNull(container)); + InetSocketAddress source = AddrUtil.getOneAddress("127.0.0.1:" + sourcePort); + SerializationUtils.init("java", new Properties()); + SerializingTranscoder transcoder = new SerializingTranscoder(); + String principal = "warm-" + UUID.randomUUID(); + String persistent = principal + "-persistent"; + String expiring = principal + "-expiring"; + int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 60); + byte[] counter = SerializationUtils.serialize(new AtomicInteger(3)); + byte[] zero = SerializationUtils.serialize(new AtomicInteger(0)); + MemcachedClient legacy = client("127.0.0.1:" + sourcePort); + try { + assertTrue(legacy.set(REGION + ":" + principal, deadline, counter, transcoder)); + assertTrue(legacy.set(REGION + ":" + persistent, 0, zero, transcoder)); + assertTrue(legacy.set(REGION + ":" + expiring, 1, counter, transcoder)); + } finally { + legacy.shutdown(); + } + Process stop = new ProcessBuilder("docker", "exec", container, "sh", "-ec", + "kill -USR1 \"$(cat /state/source.pid)\"").inheritIO().start(); + assertTrue("Graceful stop command timed out", stop.waitFor(10, TimeUnit.SECONDS)); + assertEquals("Graceful stop command failed", 0, stop.exitValue()); + awaitMetaListener(source); + + J2CacheConfig config = config(true, "30s"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + assertEquals(deadline, MemcachedLegacyWindow.read(source, REGION + ":" + principal, 3000).getDeadline()); + assertTrue(store.migrateLegacyWindow(principal, source)); + assertFalse(store.migrateLegacyWindow(principal, source)); + assertTrue(store.migrateLegacyWindow(persistent, source)); + assertFalse(store.migrateLegacyWindow(expiring, source)); + Attempt next = store.reserve(principal); + assertEquals(4, next.getCount()); + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); + Attempt persistentAttempt = store.reserve(persistent); + assertEquals(1, persistentAttempt.getCount()); + String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest(persistent); + assertEquals("0:1:" + persistentAttempt.getWindowId(), firstClient.get(persistentKey, new StringTranscoder())); + assertEquals(3, MemcachedLegacyWindow.read(source, REGION + ":" + principal, 3000).getCount()); + assertStoredDeadlines(target, deadline, persistentKey); + } + } + + private void assertStoredDeadlines(String target, int deadline, String persistentKey) throws IOException { + try (Socket socket = new Socket()) { + socket.connect(AddrUtil.getOneAddress(endpoint), 3000); + socket.setSoTimeout(3000); + socket.getOutputStream().write("lru_crawler metadump hash\r\n".getBytes(StandardCharsets.US_ASCII)); + BufferedReader reply = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); + Set keysAtExpectedExpiry = new HashSet<>(); + String line; + while (Objects.nonNull(line = reply.readLine()) && !"END".equals(line)) { + String entry = URLDecoder.decode(line, StandardCharsets.UTF_8); + if (entry.startsWith("key=" + target + " exp=" + deadline + " ")) { + keysAtExpectedExpiry.add(target); + } + if (entry.startsWith("key=" + persistentKey + " exp=-1 ")) { + keysAtExpectedExpiry.add(persistentKey); + } + } + assertEquals(Set.of(target, persistentKey), keysAtExpectedExpiry); + } + } + + private static void awaitMetaListener(InetSocketAddress address) throws InterruptedException { + for (int attempt = 0; attempt < 60; attempt++) { + try (Socket socket = new Socket()) { + socket.connect(address, 250); + socket.setSoTimeout(250); + socket.getOutputStream().write("version\r\n".getBytes(StandardCharsets.US_ASCII)); + BufferedReader reply = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); + String version = reply.readLine(); + if (Objects.nonNull(version) && version.startsWith("VERSION ")) { + return; + } + } catch (IOException ignored) { + // Connections can fail while the Memcached process restarts. + } + Thread.sleep(100); + } + throw new AssertionError("Warm-restarted Memcached did not open its Meta Text listener"); + } + @Test public void keepsTheOriginalRegionDeadlineAfterAnUpdate() throws Exception { J2CacheConfig config = config(true, "4s"); From d8ac321703603be93a4b8210c4f8795321543c10 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:16:32 +0800 Subject: [PATCH 44/50] fix: preserve retry state in typed native Ehcache 3 regions --- README.md | 2 +- README.zh-CN.md | 2 +- .../ehcache/Ehcache3CredentialRetryStore.java | 80 ++++++++++++++++--- ...e3CredentialRetryStoreIntegrationTest.java | 48 ++++++++++- 4 files changed, 115 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 45731ac1..91dd2cfe 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ For a Spring-managed retry matcher with cache name `login`, declare a provider-b For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. -For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must already accept both legacy counters and retry windows, such as with value type `Serializable`, and use creation-only or eternal expiry. Live entries are replaced in place with the existing deadline. A legacy-only value type or a policy that resets expiry on writes requires a separate cutover. +For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. A policy that resets expiry on writes requires a separate cutover. For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. diff --git a/README.zh-CN.md b/README.zh-CN.md index a180ecb3..30228dec 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -200,7 +200,7 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 -原生 Ehcache 3 的切换需暂停全部重试客户端、排空在途写入,并为每个区域只安排一个迁移写入者。沿用原缓存,对每个已知主体调用 `migrateLegacyWindow`。原区域须已允许旧计数和新窗口两种值(例如值类型为 `Serializable`),并沿用创建时确定的截止时间或永久策略。存活条目原位替换,保留原截止时间。仅接受旧类型或写入会重置有效期的区域需要单独切换。 +对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。 Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java index c71c73d4..9300184b 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -23,16 +23,20 @@ public final class Ehcache3CredentialRetryStore implements CredentialRetrySto private final Cache cache; private final Function principalKey; + private final boolean usesTypedCounters; /** * @param cache dedicated retry cache configured with {@link #fixedWindowExpiry(Duration)} - * or Ehcache's eternal expiry + * or Ehcache's eternal expiry. An AtomicInteger-typed region must + * preserve the serializable counter subtype during storage. * @param principalKey consistent principal key encoding for all callers sharing the cache */ @SuppressWarnings("unchecked") public Ehcache3CredentialRetryStore(Cache cache, Function principalKey) { Objects.requireNonNull(cache, "cache"); - if (!cache.getRuntimeConfiguration().getValueType().isAssignableFrom(Attempt.class)) { + Class valueType = cache.getRuntimeConfiguration().getValueType(); + this.usesTypedCounters = AtomicInteger.class.equals(valueType); + if (!usesTypedCounters && !valueType.isAssignableFrom(Attempt.class)) { throw new IllegalArgumentException("Ehcache retry region must accept credential retry attempts"); } this.cache = (Cache) cache; @@ -65,24 +69,24 @@ public Attempt reserve(Object principal) { Object value = cache.get(key); if (Objects.isNull(value)) { Attempt initial = firstAttempt(); - if (Objects.isNull(cache.putIfAbsent(key, initial))) { + if (Objects.isNull(cache.putIfAbsent(key, storeValue(initial)))) { return initial; } - } else if (value == MigratedCounter.ZERO) { + } else if (isMigratedZero(value)) { Attempt initial = firstAttempt(); - if (cache.replace(key, value, initial)) { + if (cache.replace(key, value, storeValue(initial))) { return initial; } } else { - if (value instanceof AtomicInteger) { + Attempt current = storedAttempt(value); + if (Objects.isNull(current)) { throw new CacheException("Legacy Ehcache retry entry requires migration before reservation"); } - Attempt current = (Attempt) value; if (current.getCount() == Integer.MAX_VALUE) { return current; } Attempt next = new Attempt(current.getWindowId(), current.getCount() + 1); - if (cache.replace(key, current, next)) { + if (cache.replace(key, value, storeValue(next))) { return next; } } @@ -96,7 +100,8 @@ public void clearIfCurrent(Object principal, String windowId) { Objects.requireNonNull(windowId, "windowId"); for (int conflict = 0; conflict < MAX_CONFLICTS; conflict++) { Object value = cache.get(key); - if (!(value instanceof Attempt) || !windowId.equals(((Attempt) value).getWindowId()) || cache.remove(key, value)) { + Attempt current = storedAttempt(value); + if (Objects.isNull(current) || !windowId.equals(current.getWindowId()) || cache.remove(key, value)) { return; } } @@ -106,7 +111,8 @@ public void clearIfCurrent(Object principal, String windowId) { /** * Converts a persisted counter in place without restarting its expiry. * Pause all legacy and new retry clients, drain writes, and use a single migration writer. - * The existing region must accept both the legacy and new value formats. + * The existing region must retain the actual type of stored values when serializing them. + * A region typed as AtomicInteger stores the converted state in a serializable subtype. * * @param principal original principal in the Ehcache region * @return true when a live legacy counter was converted @@ -114,19 +120,42 @@ public void clearIfCurrent(Object principal, String windowId) { public boolean migrateLegacyWindow(Object principal) { K key = key(principal); Object value = cache.get(key); - if (!(value instanceof AtomicInteger)) { + if (!(value instanceof AtomicInteger) || value instanceof TypedCounter) { return false; } int count = ((AtomicInteger) value).get(); if (count < 0) { throw new CacheException("Legacy credential retry count is negative"); } - Object migrated = count == 0 ? MigratedCounter.ZERO : new Attempt(UUID.randomUUID().toString(), count); + Object migrated = count == 0 + ? (usesTypedCounters ? new TypedCounter(null, 0) : MigratedCounter.ZERO) + : storeValue(new Attempt(UUID.randomUUID().toString(), count)); // Serialized AtomicInteger copies cannot be compared reliably. Under exclusive cutover, // replacing a live entry preserves the existing expiry through the validated policy. return Objects.nonNull(cache.replace(key, migrated)); } + private Object storeValue(Attempt attempt) { + return usesTypedCounters ? new TypedCounter(attempt.getWindowId(), attempt.getCount()) : attempt; + } + + private static Attempt storedAttempt(Object value) { + if (value instanceof Attempt) { + return (Attempt) value; + } + if (value instanceof TypedCounter) { + TypedCounter counter = (TypedCounter) value; + if (counter.get() > 0) { + return new Attempt(counter.windowId, counter.get()); + } + } + return null; + } + + private static boolean isMigratedZero(Object value) { + return value == MigratedCounter.ZERO || (value instanceof TypedCounter && ((TypedCounter) value).get() == 0); + } + private static Attempt firstAttempt() { return new Attempt(UUID.randomUUID().toString(), 1); } @@ -139,6 +168,33 @@ private enum MigratedCounter { ZERO } + private static final class TypedCounter extends AtomicInteger { + + private static final long serialVersionUID = 1L; + + private final String windowId; + + private TypedCounter(String windowId, int count) { + super(count); + this.windowId = windowId; + } + + // Conditional operations compare the value with a deserialized copy in off-heap regions. + @Override + public boolean equals(Object other) { + if (!(other instanceof TypedCounter)) { + return false; + } + TypedCounter counter = (TypedCounter) other; + return get() == counter.get() && Objects.equals(windowId, counter.windowId); + } + + @Override + public int hashCode() { + return Objects.hash(windowId, get()); + } + } + private static final class FixedWindowExpiry implements ExpiryPolicy { private final Duration window; diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index 45d67799..3e27bc5f 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -124,13 +124,55 @@ public void migratesOffHeapLegacyCountersWithoutRestartingTheDeadline() { } @Test - public void rejectsARegionThatOnlyAcceptsTheLegacyCounterType() { + public void migratesAndReservesSerializedCountersInAnAtomicIntegerRegion() throws Exception { + AtomicLong time = new AtomicLong(10_000); try (CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder() + .using(new TimeSourceConfiguration(time::get)) .withCache("legacy-only", CacheConfigurationBuilder.newCacheConfigurationBuilder( - String.class, AtomicInteger.class, ResourcePoolsBuilder.heap(10))) + String.class, AtomicInteger.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) .build(true)) { Cache cache = manager.getCache("legacy-only", String.class, AtomicInteger.class); - assertThrows(IllegalArgumentException.class, () -> new Ehcache3CredentialRetryStore<>(cache, Object::toString)); + cache.put("alice", new AtomicInteger(3)); + cache.put("zero", new AtomicInteger(0)); + Ehcache3CredentialRetryStore first = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + Ehcache3CredentialRetryStore second = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + time.set(12_000); + + assertTrue(first.migrateLegacyWindow("alice")); + assertFalse(second.migrateLegacyWindow("alice")); + assertTrue(first.migrateLegacyWindow("zero")); + first.clearIfCurrent("zero", "stale"); + assertEquals(1, second.reserve("zero").getCount()); + + Attempt initial = first.reserve("alice"); + assertEquals(4, initial.getCount()); + ExecutorService threads = Executors.newFixedThreadPool(2); + try { + List> attempts = threads.invokeAll(List.of( + () -> first.reserve("alice"), () -> second.reserve("alice"))); + Set counts = new HashSet<>(); + for (Future attempt : attempts) { + Attempt result = attempt.get(5, TimeUnit.SECONDS); + assertEquals(initial.getWindowId(), result.getWindowId()); + counts.add(result.getCount()); + } + assertEquals(Set.of(5, 6), counts); + } finally { + threads.shutdownNow(); + } + assertEquals(6, cache.get("alice").get()); + time.set(13_001); + assertNull(cache.get("alice")); + assertNull(cache.get("zero")); + + Attempt renewed = second.reserve("alice"); + assertNotEquals(initial.getWindowId(), renewed.getWindowId()); + first.clearIfCurrent("alice", initial.getWindowId()); + assertEquals(1, cache.get("alice").get()); + second.clearIfCurrent("alice", renewed.getWindowId()); + assertNull(cache.get("alice")); } } From 9dd0ecf08660067d2da4f56e3f94dafd5411b7da Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:27:56 +0800 Subject: [PATCH 45/50] test: verify Memcached warm restart across authenticated protocols --- .github/workflows/main-ci.yml | 14 +++-- README.md | 2 +- README.zh-CN.md | 2 +- ...edCredentialRetryStoreIntegrationTest.java | 62 ++++++++++++------- 4 files changed, 52 insertions(+), 28 deletions(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 21f767af..92f00777 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -72,22 +72,28 @@ jobs: binary_container=$(docker run -d --publish 127.0.0.1::11211/tcp \ memcached:1.6.45-alpine memcached -U 0 -B binary) warm_container=$(docker run -d --user 0 --publish 127.0.0.1::11211/tcp \ + --mount "type=bind,src=$auth_file,dst=/memcached-auth,readonly" \ --tmpfs /state:rw,size=96m memcached:1.6.45-alpine sh -ec ' chown memcache /state - memcached -u memcache -U 0 -m 64 -B binary -e /state/memory & + mkdir -p /etc/sasl2 + printf "%s\n" "mech_list: plain" >/etc/sasl2/memcached.conf + sed "s/:/@$(hostname):/" /memcached-auth >/state/sasl-auth + chown memcache /state/sasl-auth + chmod 0600 /state/sasl-auth + MEMCACHED_SASL_PWDB=/state/sasl-auth memcached -u memcache -U 0 -m 64 -S -e /state/memory & child=$! echo "$child" >/state/source.pid wait "$child" # The server requires the clock to advance beyond the saved stop second. sleep 2 - exec memcached -u memcache -U 0 -m 64 -B ascii -e /state/memory + exec memcached -u memcache -U 0 -m 64 -Y /memcached-auth -e /state/memory ') ready_port() { local container=$1 binding port binding=$(docker port "$container" 11211/tcp) port=${binding##*:} [[ "$port" =~ ^[0-9]+$ ]] || return 1 - for attempt in {1..40}; do + for _ in {1..40}; do if (: < "/dev/tcp/127.0.0.1/$port") 2>/dev/null; then printf '%s\n' "$port" return @@ -114,7 +120,7 @@ jobs: for name in ( "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", - "importsLegacyWindowsAfterBinarySourceWarmRestart", + "importsLegacyWindowsAfterSaslSourceWarmRestart", ): case = suite.find(f'./testcase[@name="{name}"]') if case is None or any(case.find(status) is not None for status in ("failure", "error", "skipped")): diff --git a/README.md b/README.md index 91dd2cfe..b9a41b96 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for eac The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one. -If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture restored a finite window with its exact original deadline and restored a persistent window with no deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. +If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture wrote the legacy counters using binary SASL, then imported the recovered windows over authenticated Meta Text. The finite window retained its exact original deadline, and the persistent window remained without a deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. For a retry cache stored in a Redisson 3.12.5 `RMapCache`, pass the original cache and principal to `migrateLegacyWindow` during the same exclusive cutover. The adapter copies the count, entry lifetime, idle policy and current idle deadline without refreshing the source. It also honors a shorter map-wide expiry. Use a distinct destination namespace on the same Redis deployment. diff --git a/README.zh-CN.md b/README.zh-CN.md index 30228dec..31b6d96e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -212,7 +212,7 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 -如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试保留了限时窗口的原始截止时间和永久窗口的无截止状态,停机期间已过期的窗口也未恢复。此方式要求在写入旧窗口前已启用热重启。 +如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试使用二进制 SASL 写入旧计数,热重启后通过已认证的 Meta Text 连接导入。限时窗口保留原始截止时间,永久窗口仍无截止时间,停机期间过期的窗口仍然缺失。此方式要求在写入旧窗口前已启用热重启。 对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 7b3e8769..19ac569a 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; +import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.URLDecoder; @@ -30,6 +31,7 @@ import net.oschina.j2cache.util.SerializationUtils; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.XMemcachedClientBuilder; +import net.rubyeye.xmemcached.auth.AuthInfo; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.transcoders.CachedData; import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; @@ -52,6 +54,8 @@ public class J2CacheMemcachedCredentialRetryStoreIntegrationTest { private static final String REGION = "credential-retry"; + private static final String FIXTURE_USER = "fixture-user"; + private static final String FIXTURE_PASSWORD = "fixture-password"; private final String namespace = "test:memcached-retry:" + UUID.randomUUID(); private String endpoint; private MemcachedClient firstClient; @@ -161,7 +165,6 @@ public void importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline() J2CacheConfig config = config(true, "30s"); String principal = "authenticated-cutover"; int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 15); - byte[] credentials = "fixture-user fixture-password".getBytes(StandardCharsets.US_ASCII); CachedData seed = new SerializingTranscoder().encode(SerializationUtils.serialize(new AtomicInteger(3))); byte[] payload = seed.getData(); try (Socket source = new Socket("127.0.0.1", Integer.parseInt(authPort)); @@ -169,11 +172,7 @@ public void importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline() source.setSoTimeout(3000); BufferedReader reply = new BufferedReader(new InputStreamReader(source.getInputStream(), StandardCharsets.US_ASCII)); OutputStream requests = source.getOutputStream(); - requests.write(("set auth 0 0 " + credentials.length + "\r\n").getBytes(StandardCharsets.US_ASCII)); - requests.write(credentials); - requests.write("\r\n".getBytes(StandardCharsets.US_ASCII)); - requests.flush(); - assertEquals("STORED", reply.readLine()); + assertEquals("STORED", authenticateMeta(source, reply)); String set = "set " + REGION + ":" + principal + " " + seed.getFlag() + " " + deadline + " " + payload.length + "\r\n"; requests.write(set.getBytes(StandardCharsets.US_ASCII)); @@ -222,12 +221,14 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E } @Test - public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception { + public void importsLegacyWindowsAfterSaslSourceWarmRestart() throws Exception { String sourcePort = System.getProperty("shiro.memcached.warm.test.port"); String container = System.getProperty("shiro.memcached.warm.test.container"); assumeTrue("Supply a dedicated warm-restart Memcached fixture", Objects.nonNull(sourcePort) && Objects.nonNull(container)); - InetSocketAddress source = AddrUtil.getOneAddress("127.0.0.1:" + sourcePort); + InetAddress loopback = InetAddress.getByName("127.0.0.1"); + // XMemcached indexes credentials by the connected socket's resolved host string. + InetSocketAddress source = new InetSocketAddress(loopback.getHostName(), Integer.parseInt(sourcePort)); SerializationUtils.init("java", new Properties()); SerializingTranscoder transcoder = new SerializingTranscoder(); String principal = "warm-" + UUID.randomUUID(); @@ -236,7 +237,10 @@ public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 60); byte[] counter = SerializationUtils.serialize(new AtomicInteger(3)); byte[] zero = SerializationUtils.serialize(new AtomicInteger(0)); - MemcachedClient legacy = client("127.0.0.1:" + sourcePort); + var builder = new XMemcachedClientBuilder(List.of(source)); + builder.setCommandFactory(new BinaryCommandFactory()); + builder.addAuthInfo(source, AuthInfo.plain(FIXTURE_USER, FIXTURE_PASSWORD)); + MemcachedClient legacy = builder.build(); try { assertTrue(legacy.set(REGION + ":" + principal, deadline, counter, transcoder)); assertTrue(legacy.set(REGION + ":" + persistent, 0, zero, transcoder)); @@ -248,16 +252,22 @@ public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception "kill -USR1 \"$(cat /state/source.pid)\"").inheritIO().start(); assertTrue("Graceful stop command timed out", stop.waitFor(10, TimeUnit.SECONDS)); assertEquals("Graceful stop command failed", 0, stop.exitValue()); - awaitMetaListener(source); + awaitAuthenticatedMetaListener(source); J2CacheConfig config = config(true, "30s"); - try (CacheChannel channel = J2CacheTestChannel.open(config)) { + try (Socket restoredSource = new Socket(); CacheChannel channel = J2CacheTestChannel.open(config)) { + restoredSource.connect(source, 3000); + restoredSource.setSoTimeout(3000); + BufferedReader reply = new BufferedReader( + new InputStreamReader(restoredSource.getInputStream(), StandardCharsets.US_ASCII)); + assertEquals("STORED", authenticateMeta(restoredSource, reply)); J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); - assertEquals(deadline, MemcachedLegacyWindow.read(source, REGION + ":" + principal, 3000).getDeadline()); - assertTrue(store.migrateLegacyWindow(principal, source)); - assertFalse(store.migrateLegacyWindow(principal, source)); - assertTrue(store.migrateLegacyWindow(persistent, source)); - assertFalse(store.migrateLegacyWindow(expiring, source)); + assertThrows(CacheException.class, () -> store.migrateLegacyWindow(principal, source)); + assertEquals(deadline, MemcachedLegacyWindow.read(restoredSource, REGION + ":" + principal).getDeadline()); + assertTrue(store.migrateLegacyWindowFromMetaConnection(principal, restoredSource)); + assertFalse(store.migrateLegacyWindowFromMetaConnection(principal, restoredSource)); + assertTrue(store.migrateLegacyWindowFromMetaConnection(persistent, restoredSource)); + assertFalse(store.migrateLegacyWindowFromMetaConnection(expiring, restoredSource)); Attempt next = store.reserve(principal); assertEquals(4, next.getCount()); String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); @@ -266,7 +276,7 @@ public void importsLegacyWindowsAfterBinarySourceWarmRestart() throws Exception assertEquals(1, persistentAttempt.getCount()); String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest(persistent); assertEquals("0:1:" + persistentAttempt.getWindowId(), firstClient.get(persistentKey, new StringTranscoder())); - assertEquals(3, MemcachedLegacyWindow.read(source, REGION + ":" + principal, 3000).getCount()); + assertEquals(3, MemcachedLegacyWindow.read(restoredSource, REGION + ":" + principal).getCount()); assertStoredDeadlines(target, deadline, persistentKey); } } @@ -292,15 +302,23 @@ private void assertStoredDeadlines(String target, int deadline, String persisten } } - private static void awaitMetaListener(InetSocketAddress address) throws InterruptedException { + private static String authenticateMeta(Socket socket, BufferedReader response) throws IOException { + byte[] credentials = (FIXTURE_USER + " " + FIXTURE_PASSWORD).getBytes(StandardCharsets.US_ASCII); + OutputStream requests = socket.getOutputStream(); + requests.write(("set auth 0 0 " + credentials.length + "\r\n").getBytes(StandardCharsets.US_ASCII)); + requests.write(credentials); + requests.write("\r\n".getBytes(StandardCharsets.US_ASCII)); + requests.flush(); + return response.readLine(); + } + + private static void awaitAuthenticatedMetaListener(InetSocketAddress address) throws InterruptedException { for (int attempt = 0; attempt < 60; attempt++) { try (Socket socket = new Socket()) { socket.connect(address, 250); socket.setSoTimeout(250); - socket.getOutputStream().write("version\r\n".getBytes(StandardCharsets.US_ASCII)); BufferedReader reply = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); - String version = reply.readLine(); - if (Objects.nonNull(version) && version.startsWith("VERSION ")) { + if ("STORED".equals(authenticateMeta(socket, reply))) { return; } } catch (IOException ignored) { @@ -308,7 +326,7 @@ private static void awaitMetaListener(InetSocketAddress address) throws Interrup } Thread.sleep(100); } - throw new AssertionError("Warm-restarted Memcached did not open its Meta Text listener"); + throw new AssertionError("Warm-restarted Memcached did not open its authenticated Meta Text listener"); } @Test From 05cc531d89bd33384d80f88be18202221d16bc25 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:44:14 +0800 Subject: [PATCH 46/50] fix: restore legacy counters in native Ehcache 3 --- README.md | 2 + README.zh-CN.md | 2 + .../ehcache/Ehcache3CredentialRetryStore.java | 21 +++++++ ...e3CredentialRetryStoreIntegrationTest.java | 56 +++++++++++++++++++ 4 files changed, 81 insertions(+) diff --git a/README.md b/README.md index b9a41b96..77256bdd 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,8 @@ For an existing Ehcache 2 retry cache, stop all legacy clients of that region be For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. A policy that resets expiry on writes requires a separate cutover. +For rollback, keep retry clients paused and drain outstanding writes before calling `restoreLegacyWindow` for each known principal. The cache must accept `AtomicInteger`. A live retry window becomes a plain legacy counter with its current count and original deadline. Missing, expired, and already restored entries are skipped. + For Hazelcast 5.2+ and 3.12, use the same cutover steps for the dedicated retry IMap. Deploy the retry-store module to every member and reuse the original map and principal keys. The first reservation converts the legacy counter atomically, retaining its remaining TTL and refreshing idle time under the existing policy. For the 3.12 adapter, supply the map's configured max idle explicitly. For an existing JCache retry region, stop legacy clients and reuse the region and principal keys. The JCache entry processor converts the saved counter and reserves the current attempt in one update. The region must use store-by-value and retain its creation deadline on access and update. A region that accepts both value types, for example with value type `Object`, stores retry windows directly. A region typed as `AtomicInteger` stores a serializable counter subtype holding the window ID. Verify that the provider and its configured serializer retain the subtype and deploy this module to every executing member before cutover. Typed migration was verified on a two-member Hazelcast JCache cluster. For rollback, pause all retry clients, drain outstanding writes, and call `restoreLegacyWindow` for every converted principal in the original region. It restores a plain `AtomicInteger` with the current count and original deadline. It skips missing, expired, and restored entries. Check for any remaining converted entries before resuming legacy clients. diff --git a/README.zh-CN.md b/README.zh-CN.md index 31b6d96e..f21c1e30 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -202,6 +202,8 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。 +回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。 + Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 对于现有 JCache 重试区域,停止旧客户端后沿用原区域和主体键。条目处理器会在同一次更新中转换计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留原截止时间。值类型允许两种格式的区域(例如 `Object`)直接存储重试窗口。值类型为 `AtomicInteger` 的区域使用可序列化的计数器子类保存窗口标识。切换前验证提供方及其序列化配置能保留子类,并在所有执行节点部署此模块。该类型区域的迁移已在双节点 Hazelcast JCache 集群验证。回切时暂停所有重试客户端,等待在途写入完成,然后对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复普通 `AtomicInteger`,保留当前计数和原截止时间,跳过缺失、过期或已恢复条目。检查区域中是否仍有已转换条目,再恢复旧客户端。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java index 9300184b..e210573b 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -135,6 +135,27 @@ public boolean migrateLegacyWindow(Object principal) { return Objects.nonNull(cache.replace(key, migrated)); } + /** + * Converts a live retry window back to a legacy counter while retaining its expiry. + * Pause all retry clients and drain outstanding writes before restoring the region. + * + * @param principal original principal in the Ehcache region + * @return true when a live retry window was restored + */ + public boolean restoreLegacyWindow(Object principal) { + if (!cache.getRuntimeConfiguration().getValueType().isAssignableFrom(AtomicInteger.class)) { + throw new IllegalArgumentException("Ehcache retry region must accept legacy counters"); + } + K key = key(principal); + Object value = cache.get(key); + Attempt attempt = storedAttempt(value); + if (Objects.isNull(attempt) && !isMigratedZero(value)) { + return false; + } + int count = Objects.nonNull(attempt) ? attempt.getCount() : 0; + return cache.replace(key, value, new AtomicInteger(count)); + } + private Object storeValue(Attempt attempt) { return usesTypedCounters ? new TypedCounter(attempt.getWindowId(), attempt.getCount()) : attempt; } diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index 3e27bc5f..92be675c 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -176,6 +176,62 @@ public void migratesAndReservesSerializedCountersInAnAtomicIntegerRegion() throw } } + @Test + public void restoresLegacyCountersWithoutRestartingTheDeadline() { + assertLegacyRestore(Serializable.class); + assertLegacyRestore(AtomicInteger.class); + } + + private void assertLegacyRestore(Class valueType) { + AtomicLong time = new AtomicLong(10_000); + try (CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder() + .using(new TimeSourceConfiguration(time::get)) + .withCache("legacy", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, valueType, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) + .build(true)) { + Cache cache = manager.getCache("legacy", String.class, valueType); + cache.put("alice", valueType.cast(new AtomicInteger(3))); + cache.put("zero", valueType.cast(new AtomicInteger(0))); + cache.put("untouched", valueType.cast(new AtomicInteger(5))); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + assertTrue(store.migrateLegacyWindow("alice")); + assertTrue(store.migrateLegacyWindow("zero")); + Attempt attempt = store.reserve("alice"); + time.set(12_000); + + assertTrue(store.restoreLegacyWindow("alice")); + assertTrue(store.restoreLegacyWindow("zero")); + assertFalse(store.restoreLegacyWindow("missing")); + assertFalse(store.restoreLegacyWindow("alice")); + assertFalse(store.restoreLegacyWindow("untouched")); + store.clearIfCurrent("alice", attempt.getWindowId()); + + assertEquals(AtomicInteger.class, cache.get("alice").getClass()); + assertEquals(4, ((AtomicInteger) cache.get("alice")).get()); + assertEquals(AtomicInteger.class, cache.get("zero").getClass()); + assertEquals(0, ((AtomicInteger) cache.get("zero")).get()); + assertEquals(5, ((AtomicInteger) cache.get("untouched")).get()); + time.set(13_001); + assertNull(cache.get("alice")); + assertNull(cache.get("zero")); + assertFalse(store.restoreLegacyWindow("alice")); + } + } + + @Test + public void rejectsLegacyRestoreWhenTheRegionAcceptsOnlyAttempts() { + try (CacheManager manager = manager(new AtomicLong(10_000), + Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>(cache, Object::toString); + Attempt original = store.reserve("alice"); + assertThrows(IllegalArgumentException.class, () -> store.restoreLegacyWindow("alice")); + assertEquals(original, cache.get("alice")); + } + } + @Test public void rejectsPoliciesThatReplaceExpiryOnWrites() { try (CacheManager manager = manager(new AtomicLong(10_000), From da7327bfe2994332cbedfd4006c74e6e875facc0 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 04:52:12 +0800 Subject: [PATCH 47/50] test: let Hazelcast integration members bind ephemeral ports --- ...stCredentialRetryStoreIntegrationTest.java | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java index 3e8d9b78..ceb43f24 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java @@ -7,9 +7,6 @@ import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.map.IMap; -import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -37,18 +34,22 @@ public class HazelcastCredentialRetryStoreIntegrationTest { private static HazelcastInstance second; @BeforeClass - public static void startCluster() throws IOException { + public static void startCluster() { String cluster = "shiro-map-" + UUID.randomUUID(); - int firstPort; - int secondPort; - try (ServerSocket a = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")); - ServerSocket b = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { - firstPort = a.getLocalPort(); - secondPort = b.getLocalPort(); - } - first = Hazelcast.newHazelcastInstance(member(cluster, firstPort, secondPort)); - second = Hazelcast.newHazelcastInstance(member(cluster, secondPort, firstPort)); + first = Hazelcast.newHazelcastInstance(member(cluster)); + int firstPort = first.getCluster().getLocalMember().getAddress().getPort(); + + Config joiningMember = member(cluster); + joiningMember.getNetworkConfig().getJoin().getTcpIpConfig() + .addMember("127.0.0.1:" + firstPort); + second = Hazelcast.newHazelcastInstance(joiningMember); + int secondPort = second.getCluster().getLocalMember().getAddress().getPort(); + + assertTrue(firstPort > 0); + assertTrue(secondPort > 0); + assertNotEquals(firstPort, secondPort); assertEquals(2, first.getCluster().getMembers().size()); + assertEquals(2, second.getCluster().getMembers().size()); } @AfterClass @@ -171,7 +172,7 @@ private static void awaitDeadline(long deadline) throws InterruptedException { } } - private static Config member(String cluster, int ownPort, int otherPort) { + private static Config member(String cluster) { Config config = new Config().setClusterName(cluster); config.setProperty("hazelcast.logging.type", "none"); config.setProperty("hazelcast.operation.thread.count", "2"); @@ -183,11 +184,11 @@ private static Config member(String cluster, int ownPort, int otherPort) { config.addMapConfig(new MapConfig("ttl").setTimeToLiveSeconds(3).setMaxIdleSeconds(10)); config.addMapConfig(new MapConfig("idle").setMaxIdleSeconds(2)); NetworkConfig network = config.getNetworkConfig(); - network.setPort(ownPort).setPortAutoIncrement(false); + network.setPort(0).setPortAutoIncrement(false); network.getInterfaces().setEnabled(true).addInterface("127.0.0.1"); network.getJoin().getAutoDetectionConfig().setEnabled(false); network.getJoin().getMulticastConfig().setEnabled(false); - network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + network.getJoin().getTcpIpConfig().setEnabled(true); return config; } } From b5cd77a73eb00a7e74226915ca04e3c3886f4d2b Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 05:03:53 +0800 Subject: [PATCH 48/50] Verify bounded cutover for renewing Ehcache retry regions --- README.md | 4 +- README.zh-CN.md | 4 +- ...e3CredentialRetryStoreIntegrationTest.java | 40 +++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 77256bdd..272e5f24 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,9 @@ For a Spring-managed retry matcher with cache name `login`, declare a provider-b For an existing Ehcache 2 retry cache, stop all legacy clients of that region before enabling the shared store. Reuse the same region and principal keys. The first reservation upgrades the stored legacy counter under the key lock, counts the current attempt and keeps the original TTL deadline and the configured time-to-idle policy. Use a strongly consistent region when clustered. -For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. A policy that resets expiry on writes requires a separate cutover. +For native Ehcache 3, pause all retry clients, drain writes, and use exactly one migration writer per region. Call `migrateLegacyWindow` for each known principal using the original cache. The region must use creation-only or eternal expiry. A region that accepts both legacy counters and retry windows, such as `Serializable`, stores attempts directly. An `AtomicInteger`-typed region stores a serializable counter subtype holding the window ID and must preserve that subtype. Live entries are replaced in place while retaining the existing deadline. + +For legacy regions using a verified finite TTL or TTI that renews on updates or reads, use a bounded drain for cutover. Pause all clients and background jobs that can access the retry region, and wait until in-flight operations finish. From that point, wait at least the longest configured lifetime across the source regions, including any clock margin required by the deployment. Enable the new store on a separate region only after that interval, with its configured creation window. The old region is left intact and its counters expire on their own. This path requires a maintenance pause and explicit acceptance of the new region’s fixed-window policy. Eternal entries, custom policies with unknown upper bounds, and deployments that must retain renewal behavior require a different path. For rollback, keep retry clients paused and drain outstanding writes before calling `restoreLegacyWindow` for each known principal. The cache must accept `AtomicInteger`. A live retry window becomes a plain legacy counter with its current count and original deadline. Missing, expired, and already restored entries are skipped. diff --git a/README.zh-CN.md b/README.zh-CN.md index f21c1e30..d92c9d97 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -200,7 +200,9 @@ realm.setCredentialsMatcher(new DefaultCredentialsMatcher()); 对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 -对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。会在写入时重置截止时间的策略需要独立切换方案。 +对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。 + +旧区域的 TTL 或 TTI 若会因写入或访问续期,且能确认有限上界,可在维护窗口内排空切换。暂停所有可能访问旧重试区域的客户端和后台任务,等在途操作全部完成。从该时点起,至少等待所有来源区域配置中最长的一段有效期,并计入部署所需的时钟余量。等待结束后,在独立区域启用新存储并配置创建窗口。旧区域保持原状,已有计数按自身策略自然到期。该路径需要维护停顿,并确认新区域采用固定窗口。存在永不过期条目、无法证明上界的自定义策略,或必须继续保留续期行为时,需另选切换方式。 回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。 diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java index 92be675c..a93c5079 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -242,6 +242,46 @@ public void rejectsPoliciesThatReplaceExpiryOnWrites() { } } + @Test + public void drainsFiniteRenewingLegacyWindowsBeforeStartingTheNewRegion() { + AtomicLong time = new AtomicLong(10_000); + Duration window = Duration.ofSeconds(5); + try (CacheManager manager = manager(time, Ehcache3CredentialRetryStore.fixedWindowExpiry(window))) { + Cache ttl = manager.createCache("legacy-ttl", + CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, AtomicInteger.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(window))); + Cache idle = manager.createCache("legacy-idle", + CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, AtomicInteger.class, + ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(window))); + ttl.put("alice", new AtomicInteger(2)); + idle.put("alice", new AtomicInteger(4)); + + time.set(12_000); + ttl.put("alice", new AtomicInteger(3)); + assertEquals(4, idle.get("alice").get()); + + time.set(15_001); + assertEquals(3, ttl.get("alice").get()); + assertEquals(4, idle.get("alice").get()); + + // The last idle read and the last TTL write are now both behind the drain bound. + time.set(20_002); + assertNull(ttl.get("alice")); + assertNull(idle.get("alice")); + + Cache destination = manager.getCache("retry", String.class, Attempt.class); + Ehcache3CredentialRetryStore store = new Ehcache3CredentialRetryStore<>( + destination, Object::toString); + assertEquals(1, store.reserve("alice").getCount()); + time.set(25_001); + assertEquals(2, store.reserve("alice").getCount()); + time.set(25_003); + assertNull(destination.get("alice")); + } + } + private static CacheManager manager(AtomicLong time, ExpiryPolicy policy) { return CacheManagerBuilder.newCacheManagerBuilder() .using(new TimeSourceConfiguration(time::get)) From 228146a3c12593279cb25936a09d20a0e7819b1b Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:34:10 +0800 Subject: [PATCH 49/50] fix: import verified Memcached retry expiry snapshots Refs #6 --- .github/workflows/main-ci.yml | 1 + README.md | 2 + README.zh-CN.md | 2 + .../J2CacheMemcachedCredentialRetryStore.java | 18 +++++++++ ...edCredentialRetryStoreIntegrationTest.java | 38 ++++++++++++++++++- 5 files changed, 60 insertions(+), 1 deletion(-) diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index 92f00777..69c83ce9 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -120,6 +120,7 @@ jobs: for name in ( "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", + "importsAuthoritativeSnapshotWithTheOriginalServerDeadline", "importsLegacyWindowsAfterSaslSourceWarmRestart", ): case = suite.find(f'./testcase[@name="{name}"]') diff --git a/README.md b/README.md index 272e5f24..7cd359a7 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,8 @@ The J2Cache Jedis and Lettuce adapters also expose `migrateLegacyWindow` for eac The J2Cache Memcached adapter can import a known principal during the same exclusive cutover. Select the source server using the original key routing. On a trusted source that accepts the Meta Text protocol, pass its address to `migrateLegacyWindow`. For authenticated access, first authenticate a dedicated Meta Text connection, configure a finite socket read timeout, and pass it to `migrateLegacyWindowFromMetaConnection`. The caller manages authentication, transport security, and closure of that connection. It must have no outstanding commands and be used by one reader at a time. The adapter reads the value with its remaining TTL, determines the absolute deadline at server-second precision, retains the original entry, and creates the destination only if it is absent. A binary-only source, including one that requires binary SASL, requires a separate migration path because its get operation does not report the existing TTL. For windows with a verified finite TTL bound, pause and drain all retry clients, then wait for the maximum remaining lifetime across the source nodes before enabling the new store. For persistent windows or unknown TTL bounds, keep using the legacy store until you can obtain an authoritative expiry snapshot. Binary GET returns the counter and CAS, which cannot distinguish a finite window from a persistent one. +During the exclusive cutover, pass a verified count and its original absolute Unix deadline from the same source entry to `migrateLegacyWindowFromSnapshot`. Use zero only for a confirmed persistent entry. Import while clients are paused and writes are drained. Expired snapshots and attempts to overwrite existing destination windows return false. + If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture wrote the legacy counters using binary SASL, then imported the recovered windows over authenticated Meta Text. The finite window retained its exact original deadline, and the persistent window remained without a deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. diff --git a/README.zh-CN.md b/README.zh-CN.md index d92c9d97..8cc6c477 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -216,6 +216,8 @@ J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字 J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 +独占切换期间可调用 `migrateLegacyWindowFromSnapshot`。先暂停重试客户端并排空在途写入,再传入同一源条目的可信计数和原始 Unix 秒截止时间。只有已确认永久有效的条目才传 0。已过期或目标窗口已存在时返回 false。 + 如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试使用二进制 SASL 写入旧计数,热重启后通过已认证的 Meta Text 连接导入。限时窗口保留原始截止时间,永久窗口仍无截止时间,停机期间过期的窗口仍然缺失。此方式要求在写入旧窗口前已启用热重启。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 6acbe968..3d53468b 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -160,6 +160,24 @@ public boolean migrateLegacyWindowFromMetaConnection(String principal, Socket so }); } + /** + * Imports a verified legacy counter and its original deadline during an exclusive cutover. + * Pause retry clients and drain outstanding writes before taking the snapshot. Supply the + * count and deadline from the same source entry and use zero only for a persistent entry. + * + * @param principal original string principal in the J2Cache region + * @param count original nonnegative retry count + * @param deadlineEpochSecond original absolute expiry, or zero for a persistent entry + * @return true when an active snapshot was copied to an empty destination + */ + public boolean migrateLegacyWindowFromSnapshot(String principal, int count, long deadlineEpochSecond) { + if (count < 0 || deadlineEpochSecond < 0 || deadlineEpochSecond > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Invalid Memcached snapshot retry count or expiry"); + } + MemcachedLegacyWindow legacy = new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); + return migrateLegacyWindow(principal, ignored -> legacy); + } + private boolean migrateLegacyWindow(String principal, LegacyRead source) { Objects.requireNonNull(principal, "principal"); try { diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 19ac569a..3c78d997 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -202,10 +202,11 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E String legacyKey = REGION + ":" + principal; String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); SerializingTranscoder transcoder = new SerializingTranscoder(); + int sourceDeadline = Math.toIntExact(Instant.now().getEpochSecond() + 120); byte[] counter = SerializationUtils.serialize(new AtomicInteger(3)); MemcachedClient legacy = client(binaryEndpoint); try (CacheChannel channel = J2CacheTestChannel.open(config)) { - assertTrue(legacy.set(legacyKey, 120, counter, transcoder)); + assertTrue(legacy.set(legacyKey, sourceDeadline, counter, transcoder)); byte[] storedCounter = (byte[]) legacy.get(legacyKey, transcoder); assertEquals(3, ((AtomicInteger) SerializationUtils.deserialize(storedCounter)).get()); long originalCas = legacy.gets(legacyKey, transcoder).getCas(); @@ -214,12 +215,47 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E assertThrows(CacheException.class, () -> store.migrateLegacyWindow(principal, AddrUtil.getOneAddress(binaryEndpoint))); assertNull(firstClient.get(target, new StringTranscoder())); + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, sourceDeadline)); + assertEquals(4, store.reserve(principal).getCount()); assertEquals(originalCas, legacy.gets(legacyKey, transcoder).getCas()); } finally { legacy.shutdown(); } } + @Test + public void importsAuthoritativeSnapshotWithTheOriginalServerDeadline() throws Exception { + J2CacheConfig config = config(true, "30s"); + try (CacheChannel channel = J2CacheTestChannel.open(config)) { + J2CacheMemcachedCredentialRetryStore store = store(channel, config, firstClient); + String principal = "snapshot-" + UUID.randomUUID(); + String persistent = principal + "-persistent"; + String expired = principal + "-expired"; + int deadline = Math.toIntExact(Instant.now().getEpochSecond() + 90); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, -1, deadline)); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, 3, -1)); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, 3, Integer.MAX_VALUE + 1L)); + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, deadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, 6, deadline + 5L)); + assertTrue(store.migrateLegacyWindowFromSnapshot(persistent, 0, 0)); + assertFalse(store.migrateLegacyWindowFromSnapshot(expired, 7, deadline - 91L)); + assertNull(firstClient.get("shiro-retry:" + digest(namespace) + ":" + digest(expired), + new StringTranscoder())); + + Attempt next = store.reserve(principal); + Attempt persistentAttempt = store.reserve(persistent); + assertEquals(4, next.getCount()); + assertEquals(1, persistentAttempt.getCount()); + String target = "shiro-retry:" + digest(namespace) + ":" + digest(principal); + String persistentKey = "shiro-retry:" + digest(namespace) + ":" + digest(persistent); + assertEquals(deadline + ":4:" + next.getWindowId(), firstClient.get(target, new StringTranscoder())); + assertStoredDeadlines(target, deadline, persistentKey); + } + } + @Test public void importsLegacyWindowsAfterSaslSourceWarmRestart() throws Exception { String sourcePort = System.getProperty("shiro.memcached.warm.test.port"); From 94e0f545b5be5af9296670291fe2b1648409acc6 Mon Sep 17 00:00:00 2001 From: loong10k <20489781+loong10k@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:03:56 +0800 Subject: [PATCH 50/50] fix: bind Memcached retry snapshot to the source entry version --- README.md | 2 ++ README.zh-CN.md | 2 ++ .../J2CacheMemcachedCredentialRetryStore.java | 34 +++++++++++++++++-- .../cache/j2cache/MemcachedLegacyWindow.java | 22 ++++++++++-- ...edCredentialRetryStoreIntegrationTest.java | 20 +++++++++-- 5 files changed, 72 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 7cd359a7..972d9b41 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,8 @@ The J2Cache Memcached adapter can import a known principal during the same exclu During the exclusive cutover, pass a verified count and its original absolute Unix deadline from the same source entry to `migrateLegacyWindowFromSnapshot`. Use zero only for a confirmed persistent entry. Import while clients are paused and writes are drained. Expired snapshots and attempts to overwrite existing destination windows return false. +During the same exclusive cutover, the overload of `migrateLegacyWindowFromSnapshot` that accepts a source client and a nonzero CAS also checks the live entry version and decoded count. It returns false if the source is missing, the version or count changed, the deadline passed, or the destination already has a window. The caller must connect to the original source process with the same routing and record the CAS, count and authoritative deadline together. The binary protocol provides the entry version and value. The deadline still comes from the trusted snapshot. + If the binary-only source already runs with [Memcached warm restart](https://docs.memcached.org/features/restart/) enabled on a retained RAM-backed memory file, it can expose the restored windows to the existing Meta Text importer during the exclusive cutover. Keep clients paused and writes drained. Gracefully stop the source with `SIGUSR1`, wait until the host clock advances beyond the saved stop second, and restart it from the same memory file with compatible slab and CAS settings and an isolated Meta Text listener. Keep the listener authenticated or restricted to trusted local access. Verify that the source actually recovered its items before importing. A loopback Memcached 1.6.45 fixture wrote the legacy counters using binary SASL, then imported the recovered windows over authenticated Meta Text. The finite window retained its exact original deadline, and the persistent window remained without a deadline. A third window that expired during the restart stayed absent. This route requires warm restart to have been enabled before the legacy windows were written. diff --git a/README.zh-CN.md b/README.zh-CN.md index 8cc6c477..e764b1de 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -218,6 +218,8 @@ J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体 独占切换期间可调用 `migrateLegacyWindowFromSnapshot`。先暂停重试客户端并排空在途写入,再传入同一源条目的可信计数和原始 Unix 秒截止时间。只有已确认永久有效的条目才传 0。已过期或目标窗口已存在时返回 false。 +独占切换期间也可使用接收源客户端和非零 CAS 的 `migrateLegacyWindowFromSnapshot` 重载。它会核对源条目当前的版本和解码后的计数。源条目消失、版本或计数不匹配、已过期或目标窗口已存在时返回 false。源客户端须采用原路由并连接原进程。采集时须记录同一条目的 CAS、计数和可信截止时间。二进制协议可核对版本和值,截止时间仍来自可信快照。 + 如果仅支持二进制协议的源节点已在可保留的内存文件上启用 [Memcached 热重启](https://docs.memcached.org/features/restart/),可在独占切换期间通过现有 Meta Text 导入器读取恢复后的窗口。保持客户端暂停并排空在途写入。向源进程发送 `SIGUSR1` 以正常停机,等待主机时钟超过记录的停机秒数,再使用同一个内存文件和兼容的 slab、CAS 设置重启,并开放隔离的 Meta Text 监听。监听应启用认证或限制为可信本机访问。确认源条目确实恢复后再导入。Memcached 1.6.45 回环测试使用二进制 SASL 写入旧计数,热重启后通过已认证的 Meta Text 连接导入。限时窗口保留原始截止时间,永久窗口仍无截止时间,停机期间过期的窗口仍然缺失。此方式要求在写入旧窗口前已启用热重启。 diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java index 3d53468b..b4955865 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -171,11 +171,38 @@ public boolean migrateLegacyWindowFromMetaConnection(String principal, Socket so * @return true when an active snapshot was copied to an empty destination */ public boolean migrateLegacyWindowFromSnapshot(String principal, int count, long deadlineEpochSecond) { + MemcachedLegacyWindow legacy = verifiedSnapshot(count, deadlineEpochSecond); + return migrateLegacyWindow(principal, ignored -> legacy); + } + + /** + * Imports an authoritative expiry snapshot after checking the live source version and count. + * Pause retry clients and drain outstanding writes before collecting and importing the snapshot. + * The binary protocol can check the entry version and value. The original deadline must come + * from the same trusted snapshot. Read the original process before it restarts or the key moves. + * + * @param principal original string principal in the J2Cache region + * @param source caller-managed client on the legacy servers with the original routing and authentication + * @param sourceCas nonzero CAS of the source entry recorded with the snapshot + * @param count original nonnegative retry count + * @param deadlineEpochSecond original absolute expiry, or zero for a persistent entry + * @return true when the matching active entry was copied to an empty destination + */ + public boolean migrateLegacyWindowFromSnapshot(String principal, MemcachedClient source, long sourceCas, + int count, long deadlineEpochSecond) { + Objects.requireNonNull(source, "source"); + if (sourceCas == 0) { + throw new IllegalArgumentException("The Memcached snapshot requires a nonzero source CAS"); + } + MemcachedLegacyWindow legacy = verifiedSnapshot(count, deadlineEpochSecond); + return migrateLegacyWindow(principal, key -> MemcachedLegacyWindow.readMatchingVersion(source, key, sourceCas, legacy)); + } + + private static MemcachedLegacyWindow verifiedSnapshot(int count, long deadlineEpochSecond) { if (count < 0 || deadlineEpochSecond < 0 || deadlineEpochSecond > Integer.MAX_VALUE) { throw new IllegalArgumentException("Invalid Memcached snapshot retry count or expiry"); } - MemcachedLegacyWindow legacy = new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); - return migrateLegacyWindow(principal, ignored -> legacy); + return new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); } private boolean migrateLegacyWindow(String principal, LegacyRead source) { @@ -202,7 +229,8 @@ private boolean migrateLegacyWindow(String principal, LegacyRead source) { @FunctionalInterface private interface LegacyRead { - MemcachedLegacyWindow read(String key) throws IOException; + MemcachedLegacyWindow read(String key) + throws IOException, InterruptedException, TimeoutException, MemcachedException; } private Window newWindow() { diff --git a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java index 4f634c07..acdd14cb 100644 --- a/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java @@ -9,15 +9,19 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Objects; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import lombok.Value; import net.oschina.j2cache.util.SerializationUtils; +import net.rubyeye.xmemcached.GetsResponse; +import net.rubyeye.xmemcached.MemcachedClient; +import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.transcoders.CachedData; import net.rubyeye.xmemcached.transcoders.SerializingTranscoder; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.cache.CacheException; -/** A read-only Memcached meta snapshot of the original J2Cache entry. */ +/** The original J2Cache retry count and Memcached deadline. */ @Value class MemcachedLegacyWindow { @@ -85,6 +89,20 @@ static MemcachedLegacyWindow read(Socket socket, String key) throws IOException private static MemcachedLegacyWindow decode(byte[] payload, int flags, int deadline) throws IOException { Object raw = TRANSCODER.decode(new CachedData(flags, payload)); + return new MemcachedLegacyWindow(counterValue(raw), deadline); + } + + static MemcachedLegacyWindow readMatchingVersion(MemcachedClient source, String key, long sourceCas, + MemcachedLegacyWindow expected) + throws TimeoutException, InterruptedException, MemcachedException, IOException { + GetsResponse current = source.gets(key, TRANSCODER); + if (Objects.isNull(current) || current.getCas() != sourceCas) { + return null; + } + return counterValue(current.getValue()) == expected.getCount() ? expected : null; + } + + private static int counterValue(Object raw) throws IOException { if (!(raw instanceof byte[])) { throw new CacheException("Legacy Memcached value must contain J2Cache bytes"); } @@ -92,7 +110,7 @@ private static MemcachedLegacyWindow decode(byte[] payload, int flags, int deadl if (!(counter instanceof AtomicInteger) || ((AtomicInteger) counter).get() < 0) { throw new CacheException("Legacy Memcached value must contain a nonnegative retry counter"); } - return new MemcachedLegacyWindow(((AtomicInteger) counter).get(), deadline); + return ((AtomicInteger) counter).get(); } private static long time(DataInputStream input, OutputStream output) throws IOException { diff --git a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java index 3c78d997..04657b56 100644 --- a/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -215,9 +215,23 @@ public void refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter() throws E assertThrows(CacheException.class, () -> store.migrateLegacyWindow(principal, AddrUtil.getOneAddress(binaryEndpoint))); assertNull(firstClient.get(target, new StringTranscoder())); - assertTrue(store.migrateLegacyWindowFromSnapshot(principal, 3, sourceDeadline)); - assertEquals(4, store.reserve(principal).getCount()); - assertEquals(originalCas, legacy.gets(legacyKey, transcoder).getCas()); + assertThrows(IllegalArgumentException.class, + () -> store.migrateLegacyWindowFromSnapshot(principal, legacy, 0, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot("missing", legacy, originalCas, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, originalCas, 2, sourceDeadline)); + assertNull(firstClient.get(target, new StringTranscoder())); + assertTrue(legacy.set(legacyKey, sourceDeadline, counter, transcoder)); + long currentCas = legacy.gets(legacyKey, transcoder).getCas(); + assertNotEquals(originalCas, currentCas); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, originalCas, 3, sourceDeadline)); + assertNull(firstClient.get(target, new StringTranscoder())); + + assertTrue(store.migrateLegacyWindowFromSnapshot(principal, legacy, currentCas, 3, sourceDeadline)); + assertFalse(store.migrateLegacyWindowFromSnapshot(principal, legacy, currentCas, 3, sourceDeadline)); + Attempt migrated = store.reserve(principal); + assertEquals(4, migrated.getCount()); + assertEquals(sourceDeadline + ":4:" + migrated.getWindowId(), firstClient.get(target, new StringTranscoder())); + assertEquals(currentCas, legacy.gets(legacyKey, transcoder).getCas()); } finally { legacy.shutdown(); }