diff --git a/.github/workflows/main-ci.yml b/.github/workflows/main-ci.yml index b23e0b36..69c83ce9 100644 --- a/.github/workflows/main-ci.yml +++ b/.github/workflows/main-ci.yml @@ -10,6 +10,20 @@ jobs: verify: runs-on: ubuntu-latest timeout-minutes: 30 + services: + redis: + image: redis:8.4.0 + ports: + - 6379/tcp + options: >- + --health-cmd "redis-cli ping" + --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 @@ -20,18 +34,155 @@ 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 - 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 }} + 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= + binary_container= + warm_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 + if [[ -n "$warm_container" ]]; then + docker rm -f "$warm_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) + 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 + 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 -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 _ 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") + 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" -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 + + reports = Path("shiro-extension-core/target/surefire-reports") + suite = ElementTree.parse(next(reports.glob("TEST-*J2CacheMemcachedCredentialRetryStoreIntegrationTest.xml"))) + for name in ( + "importsThroughAnAuthenticatedMetaConnectionWithItsOriginalDeadline", + "refusesToImportWhenOnlyTheBinaryProtocolCanReadTheCounter", + "importsAuthoritativeSnapshotWithTheOriginalServerDeadline", + "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")): + raise SystemExit(f"Expected an executed, successful Memcached test: {name}") + PYTHON + - name: Verify J2Cache and Redisson 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,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", "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}") + PYTHON - name: Require coverage for modules with existing tests run: | test -s .ci-dependencies/jwt-issuer/jwt-issuer-with-jjwt/target/jacoco.exec 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 + 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/README.md b/README.md index 294a0f47..972d9b41 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,37 @@ 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. + +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. + +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. + +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. + +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. 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. 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. + +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. + + +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 ed346754..e764b1de 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,37 @@ 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 缓存配置。共享重试窗口的应用实例应使用相同的缓存提供者、重试命名空间和主体键映射。 + +对于现有 Ehcache 2 重试缓存,先停止访问该区域的全部旧版客户端,再启用共享重试存储,并沿用原区域及主体键。首次预留在键锁内转换已保存的旧计数,计入本次尝试,并保留原 TTL 截止时间和配置的空闲过期策略。集群部署使用强一致性区域。 + +对于原生 Ehcache 3,暂停所有重试客户端并排空在途写入,每个区域只允许一个迁移写入方。使用原缓存对已知主体调用 `migrateLegacyWindow`。区域须使用仅在创建时设置的过期策略或永不过期策略。`Serializable` 等可接受旧计数和新窗口的区域直接保存新窗口。`AtomicInteger` 类型区域保存含窗口 ID 的可序列化子类型,要求序列化器保留该类型。活跃条目在原位置替换,保留原截止时间。 + +旧区域的 TTL 或 TTI 若会因写入或访问续期,且能确认有限上界,可在维护窗口内排空切换。暂停所有可能访问旧重试区域的客户端和后台任务,等在途操作全部完成。从该时点起,至少等待所有来源区域配置中最长的一段有效期,并计入部署所需的时钟余量。等待结束后,在独立区域启用新存储并配置创建窗口。旧区域保持原状,已有计数按自身策略自然到期。该路径需要维护停顿,并确认新区域采用固定窗口。存在永不过期条目、无法证明上界的自定义策略,或必须继续保留续期行为时,需另选切换方式。 + +回滚时保持客户端暂停并排空在途写入,再对已知主体调用 `restoreLegacyWindow`。缓存区域必须接受 `AtomicInteger`。活跃窗口恢复为普通旧版计数,保留当前次数和原截止时间。缺失、已过期或已经恢复的条目会跳过。 + +Hazelcast 5.2+ 与 3.12 的独立重试 IMap 沿用同样的切换顺序。所有集群成员须部署重试存储模块,并沿用原 IMap 和主体键。首次预留会原子转换旧计数,保留剩余 TTL,并按原策略刷新空闲时间。使用 3.12 适配器时需传入 IMap 配置的最大空闲时长。 + +对于现有 JCache 重试区域,停止旧客户端后沿用原区域和主体键。条目处理器会在同一次更新中转换计数并预留本次尝试。区域必须按值存储,并在访问和更新时保留原截止时间。值类型允许两种格式的区域(例如 `Object`)直接存储重试窗口。值类型为 `AtomicInteger` 的区域使用可序列化的计数器子类保存窗口标识。切换前验证提供方及其序列化配置能保留子类,并在所有执行节点部署此模块。该类型区域的迁移已在双节点 Hazelcast JCache 集群验证。回切时暂停所有重试客户端,等待在途写入完成,然后对原区域内每个已转换的主体调用 `restoreLegacyWindow`。该方法原地恢复普通 `AtomicInteger`,保留当前计数和原截止时间,跳过缺失、过期或已恢复条目。检查区域中是否仍有已转换条目,再恢复旧客户端。 + +对于 Spring Data Redis,切换期间暂停所有旧版和新版重试客户端,等在途缓存写入全部到达 Redis 后再导入。用原缓存和新存储使用的独立目标命名空间,对每个已知的字符串主体调用适配器的 `migrateLegacyWindow`。导入沿用源缓存的键和值序列化配置,复制已保存的计数与 Redis 绝对截止时间。源数据保留,跳过缺失、已过期和目标已存在的窗口。恢复客户端之前先核对本次提交的全部主体,并在同一切换窗口完成导入。启用空闲续期时,从下一次预留起应用原策略。 + +J2Cache 的 Jedis 和 Lettuce 适配器也可在独占切换期间对已知字符串主体调用 `migrateLegacyWindow`。导入按原渠道的序列化方式读取 Redis 二级缓存计数,保留普通键或 Hash 区域的 Redis 截止时间,仅在目标窗口不存在时写入。沿用原缓存提供者配置,并指定独立的目标命名空间。迁移按 JVM 默认字符集写入的旧键时,沿用原字符集。Jedis 按原二进制键查询截止时间。对于非 UTF-8 的 Lettuce 旧键,除 UTF-8 目标连接外,还需传入二进制脚本连接。 + +J2Cache Memcached 适配器也可在同一独占切换阶段导入已知主体。按原键路由选择保存旧值的源节点。对允许 Meta Text 协议的可信源节点,可向 `migrateLegacyWindow` 传入地址。需要认证时,先认证专用 Meta Text 连接,设置有限的读取超时,再传给 `migrateLegacyWindowFromMetaConnection`。调用方负责认证、传输安全和关闭连接。连接上应没有在途命令,并由单个调用方顺序读取。适配器同时读取旧值和剩余有效期,按服务端秒级精度确定绝对截止时间,保留原条目,仅在目标不存在时写入。仅支持二进制协议的节点(包括要求二进制 SASL 的节点)仍需要独立迁移方式,因为其 GET 操作不返回原有效期。 如果能确认所有旧窗口的有效期上限,先暂停旧、新客户端并排空在途写入,等待所有源节点上的旧窗口过期,再启用新存储。存在永久窗口或无法确认有效期上限时,应继续使用旧存储,直到取得可信的到期时间快照。二进制 GET 返回计数和 CAS,无法区分限时窗口和永久窗口。 + +独占切换期间可调用 `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 连接导入。限时窗口保留原始截止时间,永久窗口仍无截止时间,停机期间过期的窗口仍然缺失。此方式要求在写入旧窗口前已启用热重启。 + + +对于 Redisson 3.12.5 的 `RMapCache` 重试区域,在同一独占切换阶段使用原缓存和主体调用 `migrateLegacyWindow`。导入复制原计数、条目固定截止时间、空闲策略和当前空闲截止时间,读取时不延长源窗口。若整个 Map 更早过期,使用更早的截止时间。同一 Redis 部署内使用独立的目标命名空间。 + ## 8. Core Usage / API 精选公开 API(类均位于 `org.apache.shiro.biz` 包下): diff --git a/pom.xml b/pom.xml index a9162619..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 @@ -643,6 +644,8 @@ shiro-extension-core + shiro-extension-hazelcast3 shiro-extension-spring + shiro-extension-spring-redis4 diff --git a/shiro-extension-core/pom.xml b/shiro-extension-core/pom.xml index a41b6009..3addefc3 100644 --- a/shiro-extension-core/pom.xml +++ b/shiro-extension-core/pom.xml @@ -74,6 +74,54 @@ lombok provided + + net.sf.ehcache + ehcache-core + 2.6.11 + provided + + + org.ehcache + ehcache + 3.6.0 + provided + + + javax.cache + cache-api + 1.1.1 + provided + + + net.oschina.j2cache + j2cache-core + 2.8.5-release + provided + + + com.googlecode.xmemcached + xmemcached + 2.4.5 + provided + + + io.lettuce + lettuce-core + 5.3.7.RELEASE + provided + + + org.redisson + redisson + 3.12.5 + provided + + + com.hazelcast + hazelcast + 5.3.7 + provided + 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 new file mode 100644 index 00000000..248550a9 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/authc/credential/CredentialRetryStore.java @@ -0,0 +1,54 @@ +package org.apache.shiro.biz.authc.credential; + +import java.io.Serializable; +import java.util.Objects; +import lombok.EqualsAndHashCode; +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 + @EqualsAndHashCode + final class Attempt implements Serializable { + + private static final long serialVersionUID = 1L; + + 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 5645a1b3..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 @@ -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,32 @@ 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; + } + + /** + * @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; + if (Objects.nonNull(store)) { + return CredentialRetrySupport.match(store, token.getPrincipal(), getCredentialsRetryTimesLimit(), + () -> super.doCredentialsMatch(token, info)); + } + AtomicInteger retryCount = getCachedRetryTimes(token.getPrincipal()); if (retryCount == null) { @@ -109,11 +134,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..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 @@ -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,32 @@ 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; + } + + /** + * @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; + if (Objects.nonNull(store)) { + return CredentialRetrySupport.match(store, token.getPrincipal(), getRetryLimit(), + () -> credentialsMatch(token, info)); + } + // check retry checkCredentialsRetry(token); // credentials match @@ -56,7 +81,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..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 @@ -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之前调用 */ @@ -57,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; @@ -65,7 +70,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 +87,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/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..5c2581e4 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStore.java @@ -0,0 +1,98 @@ +package org.apache.shiro.biz.cache.ehcache; + +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 + */ +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; + } + + 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); + } + // 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)) { + Object value = entry.getObjectValue(); + if (value instanceof Attempt && windowId.equals(((Attempt) value).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/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..e210573b --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStore.java @@ -0,0 +1,242 @@ +package org.apache.shiro.biz.cache.ehcache; + +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; +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; + private final boolean usesTypedCounters; + + /** + * @param cache dedicated retry cache configured with {@link #fixedWindowExpiry(Duration)} + * 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"); + 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; + 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 + * @param value type of the retry region + * @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++) { + Object value = cache.get(key); + if (Objects.isNull(value)) { + Attempt initial = firstAttempt(); + if (Objects.isNull(cache.putIfAbsent(key, storeValue(initial)))) { + return initial; + } + } else if (isMigratedZero(value)) { + Attempt initial = firstAttempt(); + if (cache.replace(key, value, storeValue(initial))) { + return initial; + } + } else { + Attempt current = storedAttempt(value); + if (Objects.isNull(current)) { + throw new CacheException("Legacy Ehcache retry entry requires migration before reservation"); + } + if (current.getCount() == Integer.MAX_VALUE) { + return current; + } + Attempt next = new Attempt(current.getWindowId(), current.getCount() + 1); + if (cache.replace(key, value, storeValue(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++) { + Object value = cache.get(key); + Attempt current = storedAttempt(value); + if (Objects.isNull(current) || !windowId.equals(current.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 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 + */ + public boolean migrateLegacyWindow(Object principal) { + K key = key(principal); + Object value = cache.get(key); + 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 + ? (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)); + } + + /** + * 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; + } + + 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); + } + + private K key(Object principal) { + return Objects.requireNonNull(principalKey.apply(principal), "encoded principal"); + } + + 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; + + private FixedWindowExpiry(Duration window) { + this.window = window; + } + + @Override + public Duration getExpiryForCreation(Object key, V value) { + return window; + } + + @Override + public Duration getExpiryForAccess(Object key, Supplier value) { + return null; + } + + @Override + public Duration getExpiryForUpdate(Object key, Supplier previous, V next) { + return null; + } + } +} 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..c12350ef --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStore.java @@ -0,0 +1,127 @@ +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.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 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. 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 + */ + @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"); + } + + @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)) { + return; + } + Object value = entry.getValue(); + if (!(value instanceof Attempt) || !windowId.equals(((Attempt) value).getWindowId()) + || map.remove(key, value)) { + 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; + Object value = entry.getValue(); + if (Objects.isNull(value)) { + updated = new Attempt(initialWindowId, 1); + } 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); + 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/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..dab93fa3 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStore.java @@ -0,0 +1,91 @@ +package org.apache.shiro.biz.cache.j2cache; + +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; +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; + private final J2CacheRedisLegacyWindows legacy; + + /** + * @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) { + 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"); + } + Objects.requireNonNull(commands, "commands"); + 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, + 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 + public Attempt reserve(Object principal) { + return delegate.reserve(principal); + } + + @Override + 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/J2CacheMemcachedCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java new file mode 100644 index 00000000..b4955865 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStore.java @@ -0,0 +1,289 @@ +package org.apache.shiro.biz.cache.j2cache; + +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; +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; + private final String legacyRegion; + private final boolean legacySanitizeKeys; + + /** + * @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); + 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"); + } + } + + @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 = newWindow(); + if (client.add(key, initial.expiresAt(), initial.encode(), STRINGS)) { + return initial.attempt(); + } + } else { + Window window = Window.decode(current.getValue()); + Window next; + if (window.expiresAt() > 0 && Instant.now().getEpochSecond() >= window.expiresAt()) { + next = newWindow(); + } else { + if (window.count() == Integer.MAX_VALUE) { + return window.attempt(); + } + next = new Window(window.windowId(), window.count() + 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()).windowId())) { + 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"); + } + + /** + * 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(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); + }); + } + + /** + * 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) { + 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"); + } + return new MemcachedLegacyWindow(count, (int) deadlineEpochSecond); + } + + 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()); + } + MemcachedLegacyWindow legacy = source.read(legacyKey); + 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); + } + } + + @FunctionalInterface + private interface LegacyRead { + + MemcachedLegacyWindow read(String key) + throws IOException, InterruptedException, TimeoutException, MemcachedException; + } + + private Window newWindow() { + return new Window(UUID.randomUUID().toString(), 1, initialDeadline()); + } + + 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(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 + ":" + count + ":" + windowId; + } + + 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(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/J2CacheRedisCredentialRetryStore.java b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java new file mode 100644 index 00000000..d014295c --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStore.java @@ -0,0 +1,115 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +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 static final byte[] DEADLINE_SCRIPT = + J2CacheRedisLegacyWindows.DEADLINE_SCRIPT.getBytes(StandardCharsets.US_ASCII); + + private final RedisCredentialRetryStore delegate; + private final J2CacheRedisLegacyWindows legacy; + + /** + * @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(); + 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, + key -> onShard(client, key, jedis -> (Long) jedis.eval(DEADLINE_SCRIPT, 1, key))); + } + + /** + * @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"); + 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, + key -> (Long) cluster.eval(DEADLINE_SCRIPT, 1, key)); + } + + @Override + public Attempt reserve(Object principal) { + return delegate.reserve(principal); + } + + @Override + 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)) { + return provider; + } + throw new IllegalArgumentException("J2Cache retry state requires a writable Jedis provider"); + } + + private static T onShard(RedisClient client, byte[] key, Function operation) { + try { + BinaryJedisCommands connection = client.get(); + if (connection instanceof Jedis jedis) { + return operation.apply(jedis); + } + if (connection instanceof ShardedJedis sharded) { + return operation.apply(sharded.getShard(key)); + } + throw new CacheException("The J2Cache Redis connection does not expose script execution"); + } finally { + client.release(); + } + } +} 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..1abc892a --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisLegacyWindows.java @@ -0,0 +1,80 @@ +package org.apache.shiro.biz.cache.j2cache; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +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; +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 { + + static final String DEADLINE_SCRIPT = String.join("\n", + "local ttl = redis.call('PTTL', KEYS[1])", + "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 now + ttl"); + + private final CacheChannel channel; + private final J2CacheConfig config; + private final String region; + private final boolean jedis; + private final ToLongFunction deadlineReader; + + J2CacheRedisLegacyWindows(CacheChannel channel, J2CacheConfig config, String region, boolean jedis, + ToLongFunction deadlineReader) { + this.channel = channel; + this.config = config; + this.region = region; + this.jedis = jedis; + this.deadlineReader = deadlineReader; + } + + boolean migrate(String principal, RedisCredentialRetryStore destination) { + Objects.requireNonNull(principal, "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 = deadlineReader.applyAsLong(key); + 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 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. + 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; + String key = hash ? regionKey : regionKey + ":" + principal; + return key.getBytes(jedis && !hash ? StandardCharsets.UTF_8 : Charset.defaultCharset()); + } +} 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..add9c48c --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/J2CacheRetryExpiry.java @@ -0,0 +1,32 @@ +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; + } + + 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()); + return channel.regions().stream() + .filter(candidate -> region.equals(candidate.getName())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("J2Cache retry region TTL is unavailable")) + .getTtl(); + } +} 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..acdd14cb --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/j2cache/MemcachedLegacyWindow.java @@ -0,0 +1,162 @@ +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.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; + +/** The original J2Cache retry count and Memcached deadline. */ +@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 { + 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"; + 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)); + 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"); + } + 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 ((AtomicInteger) counter).get(); + } + + 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/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..eed754e2 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStore.java @@ -0,0 +1,158 @@ +package org.apache.shiro.biz.cache.jcache; + +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; +import javax.cache.expiry.ExpiryPolicy; +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. + * The cache provider executes each state change atomically against one entry. + */ +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, 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); + 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 = valueType.isAssignableFrom(AtomicInteger.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(), usesTypedCounters); + } + + @Override + 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 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; + + @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; + } + Attempt current = storedAttempt(entry.getValue()); + if (Objects.nonNull(current)) { + entry.setValue(new AtomicInteger(current.getCount())); + return true; + } + return false; + } + } + + private enum Reserve implements EntryProcessor { + INSTANCE; + + @Override + public Attempt process(MutableEntry entry, Object... arguments) { + Object value = entry.getValue(); + Attempt current = storedAttempt(value); + Attempt next; + 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(); + 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 { + throw new CacheException("JCache retry entry contains an unsupported value"); + } + entry.setValue(Boolean.TRUE.equals(arguments[1]) ? new TypedCounter(next) : next); + return next; + } + } + + private enum Clear implements EntryProcessor { + INSTANCE; + + @Override + public Void process(MutableEntry entry, Object... arguments) { + 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/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..b2f506f1 --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStore.java @@ -0,0 +1,282 @@ +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 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 + 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 + end + if idleDeadline then + redis.call('PEXPIREAT', key, string.format('%.0f', idleDeadline)) + 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]) + return '1' + 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[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 + return '1' + """; + + private final ScriptExecutor executor; + private final String namespace; + private final Function principalKey; + private final Reservation reservation; + + /** + * @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, 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, 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"); + } + 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) { + 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"); + } + return millis; + } + + @Override + public Attempt reserve(Object principal) { + 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"); + } + 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)); + } + + /** + * 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) { + 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(effectiveDeadline), + Long.toString(idleMillis), Long.toString(ttlDeadline)))); + } + + private String key(Object principal) { + String encoded = Objects.requireNonNull(principalKey.apply(principal), "encoded 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 { + + /** + * @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/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..066d48ca --- /dev/null +++ b/shiro-extension-core/src/main/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStore.java @@ -0,0 +1,121 @@ +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. + */ +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 + * @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) { + 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()), + 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); + } + + /** + * 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/AuthenticationStrategySafetyTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java new file mode 100644 index 00000000..b2a663fa --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/AuthenticationStrategySafetyTest.java @@ -0,0 +1,287 @@ +/* + * 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(); } + } + @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); + 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/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(); + } + } +} 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..fb7810e2 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/CredentialsMatcherSafetyTest.java @@ -0,0 +1,247 @@ +/* + * 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()); + } + @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()); + } + + @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(); + 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(); + 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; } + }; + } +} 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..231c19d9 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache2CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,155 @@ +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 java.util.concurrent.atomic.AtomicInteger; +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 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); + 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; + } +} 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..a93c5079 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/ehcache/Ehcache3CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,293 @@ +package org.apache.shiro.biz.cache.ehcache; + +import java.io.Serializable; +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.AtomicInteger; +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.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; + +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 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 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.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(Ehcache3CredentialRetryStore.fixedWindowExpiry(Duration.ofSeconds(3)))) + .build(true)) { + Cache cache = manager.getCache("legacy-only", String.class, AtomicInteger.class); + 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")); + } + } + + @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), + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(5)))) { + Cache cache = manager.getCache("retry", String.class, Attempt.class); + assertThrows(IllegalArgumentException.class, + () -> new Ehcache3CredentialRetryStore<>(cache, Object::toString)); + } + } + + @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)) + .withCache("retry", CacheConfigurationBuilder.newCacheConfigurationBuilder( + String.class, Attempt.class, ResourcePoolsBuilder.newResourcePoolsBuilder().offheap(2, MemoryUnit.MB)) + .withExpiry(policy)) + .build(true); + } +} 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..ceb43f24 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/hazelcast/HazelcastCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,194 @@ +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.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 java.util.concurrent.atomic.AtomicInteger; +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() { + String cluster = "shiro-map-" + UUID.randomUUID(); + 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 + 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()); + } + + @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); + } + + 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) { + 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(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); + return config; + } +} 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..1e7691da --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheLettuceCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,158 @@ +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.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; + +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 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"); + 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/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java new file mode 100644 index 00000000..04657b56 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheMemcachedCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,459 @@ +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.InetAddress; +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; +import java.util.ArrayList; +import java.util.HexFormat; +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; +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.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.auth.AuthInfo; +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; +import org.apache.shiro.cache.CacheException; +import org.junit.After; +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.assertNull; +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 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; + 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(endpoint); + secondClient = client(endpoint); + } + + @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 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()); + 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"); + assertEquals("0:1:" + persistent.getWindowId(), firstClient.get(persistentKey, new StringTranscoder())); + } + } + + @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); + 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(); + assertEquals("STORED", authenticateMeta(source, reply)); + 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 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(); + 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, sourceDeadline, 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())); + 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(); + } + } + + @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"); + String container = System.getProperty("shiro.memcached.warm.test.container"); + assumeTrue("Supply a dedicated warm-restart Memcached fixture", + Objects.nonNull(sourcePort) && Objects.nonNull(container)); + 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(); + 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)); + 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)); + 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()); + awaitAuthenticatedMetaListener(source); + + J2CacheConfig config = config(true, "30s"); + 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); + 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); + 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(restoredSource, REGION + ":" + principal).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 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); + BufferedReader reply = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII)); + if ("STORED".equals(authenticateMeta(socket, reply))) { + 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 authenticated Meta Text listener"); + } + + @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 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"); + 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(String server) throws Exception { + var builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(server)); + 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); + } + } +} 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..4ad75ae0 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisClusterMigrationTest.java @@ -0,0 +1,158 @@ +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.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; +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(); + // 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, sourceCommands) -> { + 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, sourceCommands) -> { + var store = new J2CacheLettuceCredentialRetryStore( + channel, config, REGION, namespace, Object::toString, commands, sourceCommands); + return new Migration(store, store::migrateLegacyWindow); + }); + } + + 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(); + 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 + "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(sourceKeyBytes)) + .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", + sourceConnection.sync().pexpire(sourceKeyBytes, 45_000L)); + long deadline = deadline(sourceConnection.sync(), sourceKeyBytes); + assertTrue(deadline > System.currentTimeMillis()); + 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(sourceConnection.sync(), sourceKeyBytes)); + } + } + } finally { + client.shutdown(); + } + } + + 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, 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; + } + + 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, + RedisAdvancedClusterCommands sourceCommands); + } + + private record Migration(CredentialRetryStore store, + Predicate importWindow) { + } +} 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..ba2a0507 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/j2cache/J2CacheRedisCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,152 @@ +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; +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; + +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 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()); + 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")); + 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"); + 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); + 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 = J2CacheTestChannel.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; + } +} 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(); + } +} 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..08756d15 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/jcache/JCacheCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,318 @@ +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.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; +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.AtomicInteger; +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; +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; +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 = new HazelcastServerCachingProvider(firstMember).getCacheManager(); + secondManager = new HazelcastServerCachingProvider(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 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 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 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 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()); + 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 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)); + } + + @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.setClusterName(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().getAutoDetectionConfig().setEnabled(false); + network.getJoin().getMulticastConfig().setEnabled(false); + network.getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1:" + otherPort); + return configuration; + } +} 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..0f3f5897 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redis/RedisCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,154 @@ +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.assertFalse; +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 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); + 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); + } + } +} 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..356eb3c2 --- /dev/null +++ b/shiro-extension-core/src/test/java/org/apache/shiro/biz/cache/redisson/RedissonCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,246 @@ +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; +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 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 = "{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 or cluster", Objects.nonNull(port) + || Objects.nonNull(System.getProperty(CLUSTER_NODES))); + 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 migratesTheLegacyMapEntryWithoutRefreshingItsIdleDeadline() throws Exception { + String mapName = legacyNamespace + ":legacy"; + 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"); + // 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")); + 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)); + 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 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)); + 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 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(key)); + } + + 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); + 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(); + } + } + } +} 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..6c3153f0 --- /dev/null +++ b/shiro-extension-hazelcast3/src/main/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStore.java @@ -0,0 +1,139 @@ +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.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 + * 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. 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 + */ + 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); + } + + 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); + 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)) { + Object value = entry.getValue(); + if (value instanceof Window && windowId.equals(((Window) value).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) { + Object value = entry.getValue(); + if (value instanceof Window) { + long saved = ((Window) value).ttlDeadline(); + if (saved != UNSET_DEADLINE) { + return saved; + } + } + + long ttl = entry.getTtl(); + // 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 { + + 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..8d6d1bd8 --- /dev/null +++ b/shiro-extension-hazelcast3/src/test/java/org/apache/shiro/biz/cache/hazelcast3/Hazelcast3CredentialRetryStoreIntegrationTest.java @@ -0,0 +1,222 @@ +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 java.util.concurrent.atomic.AtomicInteger; +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()); + } + + @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); + } + + 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; + } +} 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..cd2052c4 --- /dev/null +++ b/shiro-extension-spring-redis4/src/main/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStores.java @@ -0,0 +1,130 @@ +package org.apache.shiro.biz.cache.spring.redis4; + +import java.nio.ByteBuffer; +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; +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() { + } + + /** + * 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) { + 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(); + } + 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(); + 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..cbf4384a --- /dev/null +++ b/shiro-extension-spring-redis4/src/test/java/org/apache/shiro/biz/cache/spring/redis4/SpringDataRedis4CredentialRetryStoresIntegrationTest.java @@ -0,0 +1,229 @@ +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; +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.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; +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.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 = "{retry-current}:test:spring-redis4-retry:" + UUID.randomUUID(); + + @BeforeClass + public static void connect() { + String port = System.getProperty("shiro.redis.test.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 + public static void disconnect() { + if (Objects.nonNull(second)) { + second.destroy(); + } + if (Objects.nonNull(first)) { + first.destroy(); + } + } + + @Test + public void copiesLegacyWindowBeforeIdlePolicyRefreshesIt() { + String legacyPrefix = "{retry-legacy}:test:" + UUID.randomUUID() + ":"; + verifyDifferentOwners(first, legacyPrefix + "principal", namespace + ":principal"); + var config = RedisCacheConfiguration.defaultCacheConfig() + .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); + 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, expiryKey(legacyPrefix + "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(); + 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) { + 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(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); + } + } + } + + private static LettuceConnectionFactory connectionFactory(String port) { + var factory = new LettuceConnectionFactory("127.0.0.1", Integer.parseInt(port)); + factory.afterPropertiesSet(); + return factory; + } +} diff --git a/shiro-extension-spring/pom.xml b/shiro-extension-spring/pom.xml index 65464ac1..15b477da 100644 --- a/shiro-extension-spring/pom.xml +++ b/shiro-extension-spring/pom.xml @@ -65,5 +65,46 @@ lombok provided + + org.springframework.boot + spring-boot-autoconfigure + 2.7.18 + 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/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/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..adf9942e --- /dev/null +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringDataRedisCredentialRetryStores.java @@ -0,0 +1,122 @@ +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; +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.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() { + } + + /** + * 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) { + 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(); + } + 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), + 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..90a09855 --- /dev/null +++ b/shiro-extension-spring/src/main/java/org/apache/shiro/biz/cache/spring/SpringJCacheCredentialRetryStores.java @@ -0,0 +1,25 @@ +package org.apache.shiro.biz.cache.spring; + +import org.apache.shiro.biz.authc.credential.CredentialRetryStore; +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"); + } + + return new JCacheCredentialRetryStore((javax.cache.Cache) nativeCache); + } +} 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 new file mode 100644 index 00000000..20c8fbc0 --- /dev/null +++ b/shiro-extension-spring/src/test/java/org/apache/shiro/biz/cache/spring/SpringCredentialRetryStoreIntegrationTest.java @@ -0,0 +1,279 @@ +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.Arrays; +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 java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import javax.cache.Cache; +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.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.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; +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 CLUSTER_NODES = "shiro.redis.test.cluster.nodes"; + 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 importsSpringRedisLegacyCountersWithTheOriginalDeadline() throws Exception { + String port = System.getProperty("shiro.redis.test.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 = "{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))) + .transactionAware().build(); + manager.afterPropertiesSet(); + org.springframework.cache.Cache source = manager.getCache(REGION); + source.put("principal", new AtomicInteger(3)); + long deadline = expiryKey(factory, legacyPrefix + "principal"); + 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"); + 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 (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"); + 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()) { + 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(5, ((Attempt) region.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 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 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(); + 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) { + 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(key)); + } + } +}