Add caching support for IdentityProviderStorageProvider.getForLogin operations
Tier 2 medium java · local · real merged PR from keycloak/keycloak #32918
Ground-truth defects
Cleanup reference uses incorrect alias - should be 'idp-alias-' + i instead of 'alias'.
The change under review
diff
@@ -18,6 +18,7 @@ package org.keycloak.models.cache.infinispan.idp; import java.util.HashSet; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; @@ -36,11 +37,14 @@ import org.keycloak.models.cache.infinispan.RealmCacheManager; import org.keycloak.models.cache.infinispan.RealmCacheSession; import org.keycloak.organization.OrganizationProvider; +import static org.keycloak.models.IdentityProviderStorageProvider.LoginFilter.getLoginPredicate; + public class InfinispanIdentityProviderStorageProvider implements IdentityProviderStorageProvider { private static final String IDP_COUNT_KEY_SUFFIX = ".idp.count"; private static final String IDP_ALIAS_KEY_SUFFIX = ".idp.alias"; private static final String IDP_ORG_ID_KEY_SUFFIX = ".idp.orgId"; + private static final String IDP_LOGIN_SUFFIX = ".idp.login"; private final KeycloakSession session; private final IdentityProviderStorageProvider idpDelegate; @@ -70,9 +74,14 @@ public class InfinispanIdentityProviderStorageProvider implements IdentityProvid return realm.getId() + "." + orgId + IDP_ORG_ID_KEY_SUFFIX; } + public static String cacheKeyForLogin(RealmModel realm, FetchMode fetchMode) { + return realm.getId() + IDP_LOGIN_SUFFIX + "." + fetchMode; + } + @Override public IdentityProviderModel create(IdentityProviderModel model) { registerCountInvalidation(); + registerIDPLoginInvalidation(model); return idpDelegate.create(model); } @@ -81,15 +90,17 @@ public class InfinispanIdentityProviderStorageProvider implements IdentityProvid // for cases the alias is being updated, it is needed to lookup the idp by id to obtain the original alias IdentityProviderModel idpById = getById(model.getInternalId()); registerIDPInvalidation(idpById); + registerIDPLoginInvalidationOnUpdate(idpById, model); idpDelegate.update(model); } @Override public boolean remove(String alias) { String cacheKey = cacheKeyIdpAlias(getRealm(), alias); + IdentityProviderModel storedIdp = idpDelegate.getByAlias(alias); if (isInvalid(cacheKey)) { //lookup idp by alias in cache to be able to invalidate its internalId - registerIDPInvalidation(idpDelegate.getByAlias(alias)); + registerIDPInvalidation(storedIdp); } else { CachedIdentityProvider cached = realmCache.getCache().get(cacheKey, CachedIdentityProvider.class); if (cached != null) { @@ -97,6 +108,7 @@ public class InfinispanIdentityProviderStorageProvider implements IdentityProvid } } registerCountInvalidation(); + registerIDPLoginInvalidation(storedIdp); return idpDelegate.remove(alias); } @@ -198,6 +210,50 @@ public class InfinispanIdentityProviderStorageProvider implements IdentityProvid return identityProviders.stream(); } + @Override + public Stream<IdentityProviderModel> getForLogin(FetchMode mode, String organizationId) { + String cacheKey = cacheKeyForLogin(getRealm(), mode); + + if (isInvalid(cacheKey)) { + return idpDelegate.getForLogin(mode, organizationId).map(this::createOrganizationAwareIdentityProviderModel); + } + + RealmCacheManager cache = realmCache.getCache(); + IdentityProviderListQuery query = cache.get(cacheKey, IdentityProviderListQuery.class); + String searchKey = organizationId != null ? organizationId : ""; + Set<String> cached; + + if (query == null) { + // not cached yet + Long loaded = cache.getCurrentRevision(cacheKey); + cached = idpDelegate.getForLogin(mode, organizationId).map(IdentityProviderModel::getInternalId).collect(Collectors.toSet()); + query = new IdentityProviderListQuery(loaded, cacheKey, getRealm(), searchKey, cached); + cache.addRevisioned(query, startupRevision); + } else { + cached = query.getIDPs(searchKey); + if (cached == null) { + // there is a cache entry, but the current search is not yet cached + cache.invalidateObject(cacheKey); + Long loaded = cache.getCurrentRevision(cacheKey); + cached = idpDelegate.getForLogin(mode, organizationId).map(IdentityProviderModel::getInternalId).collect(Collectors.toSet()); + query = new IdentityProviderListQuery(loaded, cacheKey, getRealm(), searchKey, cached, query); + cache.addRevisioned(query, cache.getCurrentCounter()); + } + } + + Set<IdentityProviderModel> identityProviders = new HashSet<>(); + for (String id : cached) { + IdentityProviderModel idp = session.identityProviders().getById(id); + if (idp == null) { + realmCache.registerInvalidation(cacheKey); + return idpDelegate.getForLogin(mode, organizationId).map(this::createOrganizationAwareIdentityProviderModel); + } + identityProviders.add(idp); + } + + return identityProviders.stream(); + } + @Override public Stream<String> getByFlow(String flowId, String search, Integer first, Integer max) { return idpDelegate.getByFlow(flowId, search, first, max); @@ -323,6 +379,44 @@ public class InfinispanIdentityProviderStorageProvider implements IdentityProvid realmCache.registerInvalidation(cacheKeyIdpMapperAliasName(getRealm(), mapper.getIdentityProviderAlias(), mapper.getName())); } + private void registerIDPLoginInvalidation(IdentityProviderModel idp) { + // only invalidate login caches if the IDP qualifies as a login IDP. + if (getLoginPredicate().test(idp)) { + for (FetchMode mode : FetchMode.values()) { + realmCache.registerInvalidation(cacheKeyForLogin(getRealm(), mode)); + } + } + } + + /** + * Registers invalidations for the caches that hold the IDPs available for login when an IDP is updated. The caches + * are <strong>NOT</strong> invalidated if: + * <ul> + * <li>IDP is currently NOT a login IDP, and the update hasn't changed that (i.e. it continues to be unavailable for login);</li> + * <li>IDP is currently a login IDP, and the update hasn't changed that. This includes the organization link not being updated as well</li> + * </ul> + * In all other scenarios, the caches must be invalidated. + * + * @param original the identity provider's current model + * @param updated the identity provider's updated model + */ + private void registerIDPLoginInvalidationOnUpdate(IdentityProviderModel original, IdentityProviderModel updated) { + // IDP isn't currently available for login and update preserves that - no need to invalidate. + if (!getLoginPredicate().test(original) && !getLoginPredicate().test(updated)) { + return; + } + // IDP is currently available for login and update preserves that, including organization link - no need to invalidate. + if (getLoginPredicate().test(original) && getLoginPredicate().test(updated) + && Objects.equals(original.getOrganizationId(), updated.getOrganizationId())) { + return; + } + + // all other scenarios should invalidate the login caches. + for (FetchMode mode : FetchMode.values()) { + realmCache.registerInvalidation(cacheKeyForLogin(getRealm(), mode)); + } + } + private RealmModel getRealm() { RealmModel realm = session.getContext().getRealm(); if (realm == null) { @@ -251,6 +251,7 @@ public interface IdentityProviderStorageProvider extends Provider { public static Predicate<IdentityProviderModel> getLoginPredicate() { return ((Predicate<IdentityProviderModel>) Objects::nonNull) + .and(idp -> idp.getOrganizationId() == null || Boolean.parseBoolean(idp.getConfig().get(OrganizationModel.BROKER_PUBLIC))) .and(Stream.of(values()).map(LoginFilter::getFilter).reduce(Predicate::and).get()); } } @@ -72,12 +72,12 @@ public class OrganizationAwareIdentityProviderBean extends IdentityProviderBean } // we don't have a specific organization - fetch public enabled IDPs linked to any org. return session.identityProviders().getForLogin(ORG_ONLY, null) - .filter(idp -> !Objects.equals(existingIDP, idp.getAlias())) + .filter(idp -> idp.isEnabled() && !Objects.equals(existingIDP, idp.getAlias())) // re-check isEnabled as idp might have been wrapped. .map(idp -> createIdentityProvider(this.realm, this.baseURI, idp)) .sorted(IDP_COMPARATOR_INSTANCE).toList(); } return session.identityProviders().getForLogin(ALL, this.organization != null ? this.organization.getId() : null) - .filter(idp -> !Objects.equals(existingIDP, idp.getAlias())) + .filter(idp -> idp.isEnabled() && !Objects.equals(existingIDP, idp.getAlias())) // re-check isEnabled as idp might have been wrapped. .map(idp -> createIdentityProvider(this.realm, this.baseURI, idp)) .sorted(IDP_COMPARATOR_INSTANCE).toList(); } @@ -20,6 +20,7 @@ package org.keycloak.testsuite.organization.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.keycloak.models.cache.infinispan.idp.InfinispanIdentityProviderStorageProvider.cacheKeyForLogin; import static org.keycloak.models.cache.infinispan.idp.InfinispanIdentityProviderStorageProvider.cacheKeyOrgId; import static org.keycloak.models.cache.infinispan.organization.InfinispanOrganizationProvider.cacheKeyOrgMemberCount; @@ -32,6 +33,7 @@ import org.junit.Before; import org.junit.Test; import org.keycloak.common.Profile.Feature; import org.keycloak.models.IdentityProviderStorageProvider; +import org.keycloak.models.IdentityProviderStorageProvider.FetchMode; import org.keycloak.models.OrganizationDomainModel; import org.keycloak.models.OrganizationModel; import org.keycloak.models.RealmModel; @@ -363,4 +365,172 @@ public class OrganizationCacheTest extends AbstractOrganizationTest { assertNull(identityProviderListQuery); }); } + + @Test + public void testCacheIDPForLogin() { + // create 20 providers, and associate 10 of them with an organization. + for (int i = 0; i < 20; i++) { + IdentityProviderRepresentation idpRep = new IdentityProviderRepresentation(); + idpRep.setAlias("idp-alias-" + i); + idpRep.setEnabled((i % 2) == 0); // half of the IDPs will be disabled and won't qualify for login. + idpRep.setDisplayName("Broker " + i); + idpRep.setProviderId("keycloak-oidc"); + if (i >= 10) + idpRep.getConfig().put(OrganizationModel.BROKER_PUBLIC, Boolean.TRUE.toString()); + testRealm().identityProviders().create(idpRep).close(); + getCleanup().addCleanup(testRealm().identityProviders().get("alias")::remove); + } + + String orgaId = testRealm().organizations().getAll().get(0).getId(); + for (int i = 10; i < 20; i++) { + testRealm().organizations().get(orgaId).identityProviders().addIdentityProvider("idp-alias-" + i); + } + + getTestingClient().server(TEST_REALM_NAME).run((RunOnServer) session -> { + RealmModel realm = session.getContext().getRealm(); + RealmCacheSession realmCache = (RealmCacheSession) session.getProvider(CacheRealmProvider.class); + + // check all caches for login don't exist yet + for (FetchMode fetchMode : IdentityProviderStorageProvider.FetchMode.values()) { + String cachedKey = cacheKeyForLogin(realm, fetchMode); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cachedKey, IdentityProviderListQuery.class); + assertNull(identityProviderListQuery); + } + + // perform some login IDP searches and ensure they are cached. + session.identityProviders().getForLogin(FetchMode.REALM_ONLY, null); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.REALM_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(5, identityProviderListQuery.getIDPs("").size()); + + session.identityProviders().getForLogin(FetchMode.ORG_ONLY, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ORG_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(5, identityProviderListQuery.getIDPs(orgaId).size()); + + session.identityProviders().getForLogin(FetchMode.ALL, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ALL), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(10, identityProviderListQuery.getIDPs(orgaId).size()); + }); + + // 1- add/remove IDPs that are not available for login - none of these operations should invalidate the login caches. + IdentityProviderRepresentation idpRep = new IdentityProviderRepresentation(); + idpRep.setAlias("idp-alias-" + 20); + idpRep.setEnabled(true); + idpRep.setHideOnLogin(true); // this will make the new IDP not available for login. + idpRep.setDisplayName("Broker " + 20); + idpRep.setProviderId("keycloak-oidc"); + testRealm().identityProviders().create(idpRep).close(); + getCleanup().addCleanup(testRealm().identityProviders().get("alias")::remove); + + // remove one IDP that was not available for login. + testRealm().identityProviders().get("idp-alias-1").remove(); + + getTestingClient().server(TEST_REALM_NAME).run((RunOnServer) session -> { + RealmModel realm = session.getContext().getRealm(); + RealmCacheSession realmCache = (RealmCacheSession) session.getProvider(CacheRealmProvider.class); + + // check all caches for login are still there. + for (FetchMode fetchMode : IdentityProviderStorageProvider.FetchMode.values()) { + String cachedKey = cacheKeyForLogin(realm, fetchMode); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cachedKey, IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + } + }); + + // 2- update a couple of idps (one not available for login, one available), but don't change their login-availability status + // none of these operations should invalidate the login caches. + idpRep = testRealm().identityProviders().get("idp-alias-20").toRepresentation(); + idpRep.getConfig().put("somekey", "somevalue"); + idpRep.setTrustEmail(true); + testRealm().identityProviders().get("idp-alias-20").update(idpRep); // should still be unavailable for login + + idpRep = testRealm().identityProviders().get("idp-alias-0").toRepresentation(); + idpRep.getConfig().put("somekey", "somevalue"); + idpRep.setTrustEmail(true); + testRealm().identityProviders().get("idp-alias-0").update(idpRep); // should still be available for login + + getTestingClient().server(TEST_REALM_NAME).run((RunOnServer) session -> { + RealmModel realm = session.getContext().getRealm(); + RealmCacheSession realmCache = (RealmCacheSession) session.getProvider(CacheRealmProvider.class); + + // check all caches for login are still there. + for (FetchMode fetchMode : IdentityProviderStorageProvider.FetchMode.values()) { + String cachedKey = cacheKeyForLogin(realm, fetchMode); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cachedKey, IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + } + }); + + // 3- update an IDP, changing the availability for login - this should invalidate the caches. + idpRep = testRealm().identityProviders().get("idp-alias-20").toRepresentation(); + idpRep.setHideOnLogin(false); + testRealm().identityProviders().get("idp-alias-20").update(idpRep); + + getTestingClient().server(TEST_REALM_NAME).run((RunOnServer) session -> { + RealmModel realm = session.getContext().getRealm(); + RealmCacheSession realmCache = (RealmCacheSession) session.getProvider(CacheRealmProvider.class); + + // check all caches have been cleared. + for (FetchMode fetchMode : IdentityProviderStorageProvider.FetchMode.values()) { + String cachedKey = cacheKeyForLogin(realm, fetchMode); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cachedKey, IdentityProviderListQuery.class); + assertNull(identityProviderListQuery); + } + + // re-do searches to populate the caches again and check the updated results. + session.identityProviders().getForLogin(FetchMode.REALM_ONLY, null); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.REALM_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(6, identityProviderListQuery.getIDPs("").size()); + + session.identityProviders().getForLogin(FetchMode.ORG_ONLY, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ORG_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(5, identityProviderListQuery.getIDPs(orgaId).size()); + + session.identityProviders().getForLogin(FetchMode.ALL, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ALL), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(11, identityProviderListQuery.getIDPs(orgaId).size()); + + }); + + // 4- finally, change one of the realm-level login IDPs, linking it to an org - although it still qualifies for login, it is now + // linked to an org, which should invalidate all login caches. + idpRep = testRealm().identityProviders().get("idp-alias-20").toRepresentation(); + idpRep.getConfig().put(OrganizationModel.BROKER_PUBLIC, Boolean.TRUE.toString()); + testRealm().identityProviders().get("idp-alias-20").update(idpRep); + testRealm().organizations().get(orgaId).identityProviders().addIdentityProvider("idp-alias-20"); + + getTestingClient().server(TEST_REALM_NAME).run((RunOnServer) session -> { + RealmModel realm = session.getContext().getRealm(); + RealmCacheSession realmCache = (RealmCacheSession) session.getProvider(CacheRealmProvider.class); + + // check all caches have been cleared. + for (FetchMode fetchMode : IdentityProviderStorageProvider.FetchMode.values()) { + String cachedKey = cacheKeyForLogin(realm, fetchMode); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cachedKey, IdentityProviderListQuery.class); + assertNull(identityProviderListQuery); + } + + // re-do searches to populate the caches again and check the updated results. + session.identityProviders().getForLogin(FetchMode.REALM_ONLY, null); + IdentityProviderListQuery identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.REALM_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(5, identityProviderListQuery.getIDPs("").size()); + + session.identityProviders().getForLogin(FetchMode.ORG_ONLY, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ORG_ONLY), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(6, identityProviderListQuery.getIDPs(orgaId).size()); + + session.identityProviders().getForLogin(FetchMode.ALL, orgaId); + identityProviderListQuery = realmCache.getCache().get(cacheKeyForLogin(realm, FetchMode.ALL), IdentityProviderListQuery.class); + assertNotNull(identityProviderListQuery); + assertEquals(11, identityProviderListQuery.getIDPs(orgaId).size()); + + }); + } }
Leaderboard for this case
medium · 5 of 9 bots fully caught it (56% solve rate) · 56% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Claude Code (Opus 5.5) | solved | 1/1 | 100.0% | 4 | 0 |
| 2 | Cubic | solved | 1/1 | 100.0% | 1 | 0 |
| 3 | Drape (Deep Review) | solved | 1/1 | 100.0% | 3 | 0 |
| 4 | Drape (Review) | solved | 1/1 | 100.0% | 2 | 0 |
| 5 | greptile | solved | 1/1 | 100.0% | 1 | 0 |
| 6 | cursor | miss | 0/1 | 0.0% | 1 | 0 |
| 7 | Mjolnir (Opus 5.5) | miss | 0/1 | 0.0% | 1 | 0 |
| 8 | Mjolnir (Sonnet 5.5) | miss | 0/1 | 0.0% | 1 | 0 |
| 9 | qodo | miss | 0/1 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✓ | exact |
`update()` takes `idpById` from `getById()`, which returns `createOrganizationAwareIdentityProviderModel(...)`. In that wrapper, `isEnabled()` is false while the org is disabled, so `getLoginPredicate()` fails for the original model. If the update also makes the IDP non-login (hidden, link-only or non-public), both checks are false and invalidation is skipped. The cache is filled from the delegate's `getForLogin`, which ignores org enabled state, and the bean only re-checks `isEnabled()`. So once the org is re-enabled, the stale entry shows the IDP on the login page. [grounded: diff] [consensus 3/3: valid=3]
The new cached `getForLogin` path re-resolves IDs through `getById` and returns them without re-applying the login predicate. Finding 0 shows a real missed-invalidation path, so stale non-login IDPs can be returned. This is largely a robustness point that overlaps finding 0. [grounded: diff] [consensus 3/3: valid=3]
`IdentityProviderBean.federatedProviderPredicate()` returns `getLoginPredicate()`, so the plain bean now drops a user's linked org IDPs that are not public. Before this change it filtered only on enabled, linkOnly and hideOnLogin. This is a real behaviour change, but it is only reachable in narrow cases, such as the organizations feature being disabled while IDPs still carry an org ID. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
`update()` takes the 'original' model from `getById()`, which returns an organization-aware wrapper. In that wrapper, `isEnabled()` is false whenever the linked org (or the organizations feature) is disabled. The login query cache is built from the delegate `getForLogin`, which ignores org enabled state, so it can hold such an IDP's id. Example: the org is disabled and an admin sets one of its public IDPs to `hideOnLogin=true`, `linkOnly=true`, or `BROKER_PUBLIC=false`. `getLoginPredicate()` is then false for both the original (because of the wrapper) and the updated model, so `registerIDPLoginInvalidationOnUpdate` skips invalidation. Once the org is re-enabled, the cached `getForLogin` keeps returning that IDP. The bean only re-checks `isEnabled()`, so a hidden, link-only or non-public broker shows up on the login page. Fix: compare against the unwrapped stored model (e.g. `idpDelegate.getById`), as `remove()` does.
On a cache hit, the cached `getForLogin` path returns each IDP from `getById()` without re-applying the login predicate (enabled / linkOnly / hideOnLogin / public). Correctness therefore depends entirely on every write path invalidating precisely. Any missed invalidation, such as the update case above or other writers that bypass this provider, leaves non-login IDPs visible until the entry is evicted. Re-checking `getLoginPredicate()` and the fetch-mode/org constraints on the resolved models would make the cache robust to this.
The shared `LoginFilter.getLoginPredicate()` now also requires `BROKER_PUBLIC=true` for any org-linked IDP. That predicate is the default `IdentityProviderBean.federatedProviderPredicate()`, so the plain (non-organization-aware) bean now silently drops a user's existing federated links to non-public org IDPs. That bean is used when organizations are disabled for the realm. Before this change it only filtered on enabled, linkOnly and hideOnLogin. This is a behavior change outside the caching work.
The cleanup is registered as `testRealm().identityProviders().get("alias")::remove`, using the literal string "alias" instead of the created alias (e.g. `"idp-alias-" + i`). As a result none of the created IDPs are cleaned up, and they can leak into other tests in the class. The same mistake appears for `idp-alias-20`.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✓ | off by one |
raw comments (2)
<!-- cubic:v=bd6c4faa-b5e6-451b-b8c6-f66e1243d5e6 -->
<!-- cubic:review-run=a5255b50-cdc1-578f-bdbc-41d0ab02e379 -->
<!-- metadata:{"confidence":9} -->
P2: The cleanup handler removes nonexistent IDP "alias" instead of each created "idp-alias-N", so none of the 21 IDPs created by this test are ever cleaned up. The exceptions are swallowed by TestCleanup.addCleanup(Runnable), and the leaked IDPs change the exact counts asserted later in this test (and in sibling tests in the realm). Register cleanup with the actual alias: `getCleanup().addCleanup(testRealm().identityProviders().get("idp-alias-" + i)::remove)` in the loop, and the same fix for "idp-alias-20".
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java, line 381:
<comment>The cleanup handler removes nonexistent IDP "alias" instead of each created "idp-alias-N", so none of the 21 IDPs created by this test are ever cleaned up. The exceptions are swallowed by TestCleanup.addCleanup(Runnable), and the leaked IDPs change the exact counts asserted later in this test (and in sibling tests in the realm). Register cleanup with the actual alias: `getCleanup().addCleanup(testRealm().identityProviders().get("idp-alias-" + i)::remove)` in the loop, and the same fix for "idp-alias-20".</comment>
<file context>
@@ -363,4 +365,172 @@ public void testCacheIDPByOrg() {
+ if (i >= 10)
+ idpRep.getConfig().put(OrganizationModel.BROKER_PUBLIC, Boolean.TRUE.toString());
+ testRealm().identityProviders().create(idpRep).close();
+ getCleanup().addCleanup(testRealm().identityProviders().get("alias")::remove);
+ }
+
</file context>
```
</details>
```suggestion
getCleanup().addCleanup(testRealm().identityProviders().get("idp-alias-" + i)::remove);
```
<!-- cubic:review-summary:start -->
**1 issue found** across 4 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java">
<violation number="1" location="testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java:381">
P2: The cleanup handler removes nonexistent IDP "alias" instead of each created "idp-alias-N", so none of the 21 IDPs created by this test are ever cleaned up. The exceptions are swallowed by TestCleanup.addCleanup(Runnable), and the leaked IDPs change the exact counts asserted later in this test (and in sibling tests in the realm). Register cleanup with the actual alias: `getCleanup().addCleanup(testRealm().identityProviders().get("idp-alias-" + i)::remove)` in the loop, and the same fix for "idp-alias-20".</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/51/ai_pr_review_github_delivery_a76ab8f472a27fd51417c66c4f2103c8730d2612203928e634bf4455925d2453?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F51)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_a76ab8f472a27fd51417c66c4f2103c8730d2612203928e634bf4455925d2453:80a7ba97336b518c5fe1a9de5ca740f7ca37fc0e:a5255b50-cdc1-578f-bdbc-41d0ab02e379 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✗ | — |
In `update()`, `original` comes from `getById()`. That returns the org-aware wrapper, whose `isEnabled()` is false while the org is disabled, so `getLoginPredicate()` fails for it. Say an org IDP is in the login cache, its org gets disabled, and an admin then sets hideOnLogin or linkOnly. Both predicates are false, so the login cache is never invalidated. Once the org is re-enabled, `getForLogin` still returns that IDP's ID, and callers only re-check `isEnabled()`. Nothing in the shown code invalidates the login cache when an org is disabled, so the stale entry survives. [grounded: diff] [consensus 5/5: valid=5]
raw comments (2)
### Login cache skip uses wrapped model
**Medium Severity**
<!-- DESCRIPTION START -->
`registerIDPLoginInvalidationOnUpdate` decides whether to invalidate the login cache using `getLoginPredicate()` on the `original` from `getById`, which wraps `isEnabled()` with organization state. If the org is disabled, a still-cached login IDP looks ineligible, so updates to `hideOnLogin`, `linkOnly`, or `BROKER_PUBLIC` skip invalidation. After the org is re-enabled, stale IDs stay in `getForLogin` and can reappear on login because callers only re-check `isEnabled()`.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 075e6b6c-c926-4e25-956c-43d1f584b96c -->
<!-- LOCATIONS START
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java#L402-L412
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java#L88-L93
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java#L88-L93`](https://github.com/drape-io/crbench-cursor-2026-09/blob/ffbbc2d1b58262a0575867a98a1c1e1bac04f770/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java#L88-L93)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjYzMzM0MmMyLTZkNzItNDU4Zi1iOGRkLWUzNGI3MmJmNDgzZiIsImVuY3J5cHRpb25LZXkiOiJYYkNHWE0yQ1p4Z3NQbjE3aDJEanNKbG5OcGEwU3lqei13QW9vblJlaDljIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzI5MTgiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjYzMzM0MmMyLTZkNzItNDU4Zi1iOGRkLWUzNGI3MmJmNDgzZiIsImVuY3J5cHRpb25LZXkiOiJYYkNHWE0yQ1p4Z3NQbjE3aDJEanNKbG5OcGEwU3lqei13QW9vblJlaDljIiwiYnJhbmNoIjoidDIta2V5Y2xvYWstMzI5MTgiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjo1MSwiY29tbWl0U2hhIjoiZmZiYmMyZDFiNTgyNjJhMDU3NTg2N2E5OGExYzFlMWJhYzA0Zjc3MCIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ffbbc2d1b58262a0575867a98a1c1e1bac04f770. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTphNmQ3ODQwNC1jODJiLTQ3YmYtYmIyYi1iZmQ0OWUxMTY0NGMiLCJlbmNyeXB0aW9uS2V5IjoibkhvQk5XWGdPdGxFTlVhSjYzbldpc2Nic01SS2N0NVpGLWhObnlCQi1wbyIsImJyYW5jaCI6InQyLWtleWNsb2FrLTMyOTE4IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ffbbc2d1b58262a0575867a98a1c1e1bac04f770. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✓ | exact |
getById returns the org-aware wrapper, and its isEnabled() is false while the org is disabled. So the original fails the login predicate, and an update that hides the IDP (or makes it link-only or non-public) fails it too, which skips invalidation. The JPA-backed login cache still holds the IDP's id, and nothing in the organization provider invalidates the login cache keys. After the org is re-enabled, the bean only re-checks isEnabled, so the hidden IDP appears on the login page. [grounded: diff] [consensus 3/3: valid=3]
The new clause in getLoginPredicate applies even when the ORGANIZATION feature is off. IdentityProviderBean.federatedProviderPredicate uses this predicate on its own, so a user's linked IDP that has an organizationId but no BROKER_PUBLIC flag is now filtered out, where before it was shown. This only happens when IDPs keep org links after the feature is turned off, which is an edge case. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
**Hidden/private org IDP stays in login cache**
`update` compares against `getById`, whose org-aware wrapper reports the IDP as disabled while its organization is disabled. Hiding it, making it link-only or non-public then skips invalidation, so it shows on the login page once the org is re-enabled. Use the raw `idpDelegate.getById(...)` model as `original` in `registerIDPLoginInvalidationOnUpdate`.
```
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:91 IdentityProviderModel idpById = getById(model.getInternalId());
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:92 registerIDPInvalidation(idpById);
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:93 registerIDPLoginInvalidationOnUpdate(idpById, model);
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:403 private void registerIDPLoginInvalidationOnUpdate(IdentityProviderModel original, IdentityProviderModel updated) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:438 if (getOrganizationId() != null) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:439 OrganizationProvider provider = session.getProvider(OrganizationProvider.class);
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:440 OrganizationModel org = provider == null ? null : provider.getById(getOrganizationId());
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:441 return org != null && provider.isEnabled() && org.isEnabled() && super.isEnabled();
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:245 for (String id : cached) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:246 IdentityProviderModel idp = session.identityProviders().getById(id);
```
**User's linked org IDP hidden with feature off**
With the ORGANIZATION feature off, an IDP still carrying an organizationId but no BROKER_PUBLIC flag is now dropped by the new clause in `getLoginPredicate`. A user federated with it no longer sees it on login, though they did before. Apply the org/public check only when organizations are enabled.
```
server-spi/src/main/java/org/keycloak/models/IdentityProviderStorageProvider.java:254 .and(idp -> idp.getOrganizationId() == null || Boolean.parseBoolean(idp.getConfig().get(OrganizationModel.BROKER_PUBLIC)))
services/src/main/java/org/keycloak/forms/login/freemarker/model/IdentityProviderBean.java:191 if (!federatedIdentities.isEmpty() || organizationsDisabled(realm))
services/src/main/java/org/keycloak/forms/login/freemarker/model/IdentityProviderBean.java:192 // if orgs are enabled, we don't want to return an empty set - we want the organization IDPs to be shown if those are available.
services/src/main/java/org/keycloak/forms/login/freemarker/model/IdentityProviderBean.java:193 result = new HashSet<>(federatedIdentities);
```
**Test cleanup never removes created IDPs**
The cleanup registers removal of an IDP with the literal alias "alias" instead of the alias just created, so the 21 IDPs created by `testCacheIDPForLogin` are left in the realm. Use `get(idpRep.getAlias())::remove` (and likewise for idp-alias-20).
```
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java:381 getCleanup().addCleanup(testRealm().identityProviders().get("alias")::remove);
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java:425 getCleanup().addCleanup(testRealm().identityProviders().get("alias")::remove);
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✓ | exact |
`idpById` comes from `getById()`, which returns the org-aware wrapper. When the IDP's organization is disabled, the wrapper's `isEnabled()` returns false, so the login predicate fails on the original. The cached ID list, though, comes from `idpDelegate.getForLogin` (JPA). That query looks only at the IDP's raw flags, not at whether its org is enabled, so the IDP's ID is in the cache. If the update also makes the IDP non-login (e.g. sets hideOnLogin or linkOnly), the first early return fires and nothing is invalidated. Once the org is re-enabled, the stale entry comes back, and the bean only re-checks `isEnabled`, not hideOnLogin. The trigger is narrow (the update must also make the IDP non-login), but the claimed skip is real and new in this change. [grounded: diff] [consensus 3/3: valid=3]
raw comments (2)
**Login cache stale for IDPs in disabled orgs**
`update()` passes `original` from `getById()`, the org-aware wrapper. For an IDP in a disabled org, `original.isEnabled()` is false, so `registerIDPLoginInvalidationOnUpdate` skips invalidation. Test the original using the raw stored model from `idpDelegate.getById`.
```
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:91 IdentityProviderModel idpById = getById(model.getInternalId());
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:92 registerIDPInvalidation(idpById);
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:93 registerIDPLoginInvalidationOnUpdate(idpById, model);
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:403 private void registerIDPLoginInvalidationOnUpdate(IdentityProviderModel original, IdentityProviderModel updated) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:434 return new IdentityProviderModel(idp) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:435 @Override
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:436 public boolean isEnabled() {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:437 // if IdP is bound to an org
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:438 if (getOrganizationId() != null) {
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java:439 OrganizationProvider provider = session.getProvider(OrganizationProvider.class);
```
**Test cleanup removes wrong IDP alias**
The cleanup registered in the creation loop calls `identityProviders().get("alias")::remove`, a literal alias that never exists, instead of the IDP just created (`idp-alias-N`). The same is true for `idp-alias-20`. Use the real alias: `get(alias)::remove`, with a final copy of the loop variable inside the lambda.
```
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java:378 if (i >= 10)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java:421 idpRep.setHideOnLogin(true); // this will make the new IDP not available for login.
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✓ | off by one |
raw comments (2)
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Cleanup Targets Wrong Alias**
The test creates providers named `idp-alias-*`, but this cleanup and the cleanup for `idp-alias-20` both target the literal alias `"alias"`. Teardown can therefore fail on a missing provider or remove an unrelated provider, while leaving the providers created by this test behind. Register each cleanup using the alias from its corresponding `idpRep`.
<h3>Greptile Summary</h3>
This PR adds revisioned caching for identity providers eligible for login, extends login eligibility to account for public organization brokers, and adds targeted cache invalidation for identity-provider changes.
- Caches login-provider ID sets by realm, fetch mode, and organization search key.
- Invalidates login caches when provider eligibility or organization association changes.
- Rechecks organization-aware enabled state when constructing login-page provider lists.
- Adds integration coverage for cache population and invalidation behavior.
- The new test registers cleanup against the wrong provider aliases and should be corrected.
<h3>Confidence Score: 4/5</h3>
The production changes appear safe to merge, but the non-blocking test-cleanup defect should be fixed to avoid teardown failures and leaked identity providers.
The login-cache behavior and invalidation paths are consistent with existing provider semantics; the only accepted issue is that the new test's cleanup callbacks address the wrong aliases.
**Files Needing Attention:** testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java | Adds revisioned login-provider caching and eligibility-aware invalidation; no actionable correctness defect was established. |
| server-spi/src/main/java/org/keycloak/models/IdentityProviderStorageProvider.java | Excludes non-public organization-linked providers from the shared login predicate, consistently with existing login-query semantics. |
| services/src/main/java/org/keycloak/organization/forms/login/freemarker/model/OrganizationAwareIdentityProviderBean.java | Rechecks dynamically wrapped provider enabled state before rendering organization-aware login options. |
| testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java | Adds broad login-cache tests, but cleanup callbacks target the literal alias `"alias"` rather than the providers created by the test. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[getForLogin mode, organizationId] --> B{Login cache invalid?}
B -- Yes --> C[Query delegate and wrap models]
B -- No --> D[Read per-mode IdentityProviderListQuery]
D --> E{Organization search cached?}
E -- No --> F[Query delegate for provider IDs]
F --> G[Merge search result and write revisioned cache]
E -- Yes --> H[Resolve cached IDs through getById]
G --> H
H --> I[Return organization-aware provider models]
J[Create, update, remove, or association change] --> K{Login membership changed?}
K -- Yes --> L[Invalidate all FetchMode login keys]
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update model/infinispan/src/main/java/or..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/70afb89ff6e3dfefda2702ff6ddf7ff5e7728e60) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284573)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✗ | — |
update() passes `idpById` from getById(), and getById() returns the org-aware wrapper. That wrapper's isEnabled() returns false while the IDP's organization is disabled, so the ENABLED filter in getLoginPredicate fails for `original`. The cached login ID set, though, comes from idpDelegate.getForLogin, which only checks the IDP's own enabled field. If the update also makes the IDP non-login (hidden, link-only or not public), the method returns early and the .idp.login caches are never invalidated. The only other place these keys are invalidated is in this provider, so re-enabling the organization does not clear them either. After that, the bean re-checks only isEnabled(), so the IDP still appears on the login page. [grounded: diff] [consensus 3/3: valid=3]
raw comments (1)
[P2] Login cache is not invalidated when an IDP is updated while its organization is disabled
This only happens when an IDP is linked to an organization that is currently disabled. `update()` gets `original` from `getById()`, which returns the org-aware wrapper, and that wrapper's `isEnabled()` returns false while the organization is disabled. So `getLoginPredicate().test(original)` is false even though the stored IDP is enabled and is in the cached login ID set. The cached set is built from `idpDelegate.getForLogin`, which does not check whether the organization is enabled. Here is a concrete case. The org is disabled, and an admin updates its public IDP to set `hideOnLogin=true`, `linkOnly=true`, or `BROKER_PUBLIC=false`. The updated model built by `RepresentationToModel` also fails the predicate, so `registerIDPLoginInvalidationOnUpdate` exits early and the `.idp.login.*` entries are never invalidated. After the organization is re-enabled, `getForLogin(ORG_ONLY/ALL, …)` still returns this IDP from the cache. `OrganizationAwareIdentityProviderBean` re-checks only `isEnabled()`, so the IDP still appears on the login page even though it is now hidden, link-only or non-public. To fix this, the "was a login IDP" check should use the unwrapped/stored model (for example, `idpDelegate.getById`) rather than the org-aware wrapper.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✗ | — |
`original` comes from getById, so it is wrapped by createOrganizationAwareIdentityProviderModel, whose isEnabled() returns false while the org is disabled. The cached ID set comes from idpDelegate.getForLogin, which ignores org state. Suppose an admin sets hideOnLogin (or linkOnly, or clears BROKER_PUBLIC) on an org-linked IDP while its org is disabled. Both predicate checks then fail, the early return skips invalidation, and the stale cached entry survives. After the org is re-enabled, the bean only re-checks isEnabled, so it can still show the hidden IDP. The comment says both models are usually wrapped; in fact `updated` likely comes straight from RepresentationToModel.toModel and is not wrapped. That detail does not change the failure. [grounded: diff] [consensus 3/3: valid=3]
raw comments (1)
[P2] Login cache invalidation on update is skipped when the org is disabled
`registerIDPLoginInvalidationOnUpdate` decides whether to invalidate by calling `getLoginPredicate()` on `original` and `updated`. Both are usually models wrapped by `createOrganizationAwareIdentityProviderModel`, whose `isEnabled()` also depends on the organization being enabled. The cached `getForLogin` ID set is built from the delegate, which ignores org state. Take an org-linked IDP while its org is disabled. If an admin changes `hideOnLogin`, `linkOnly`, `BROKER_PUBLIC` or `enabled` on that IDP, both models test as non-login, so the early return skips invalidation. Nothing invalidates the cache when the org is re-enabled. After that, the login page can show an IDP that should now be hidden or non-public. The bean's re-check only covers `isEnabled`, not `hideOnLogin`, `linkOnly` or public. The reverse case also happens: an IDP made visible while the org was disabled stays missing from the cached set. The comparison should use the raw IDP state, or the login cache should be invalidated on org enable or disable.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | low | ✗ | — |
raw comments (2)
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Cache identity providers available for organization-aware login
<code>✨ Enhancement</code> <code>🐞 Bug fix</code> <code>🧪 Tests</code> <code>🕐 20-40 Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Cache login-eligible identity provider queries by fetch mode and organization.
>• Invalidate login caches only when provider eligibility or organization linkage changes.
>• Exclude private organization brokers and revalidate wrapped provider availability.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
A["Login Request"] --> B["Cache Provider"] --> C{"Cache valid?"}
C -- "Yes" --> D["Realm Cache"] --> E["Resolve Models"] --> F["Login Providers"]
C -- "No" --> G["JPA Delegate"] --> D
H["IDP Mutation"] -- "Register invalidation" --> B
B -- "Invalidate modes" --> D
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Invalidate on every IDP mutation</b></summary>
<dl>
<dd>
- ➕ Simplifies invalidation rules and reduces eligibility-transition risk.
- ➕ Makes all provider configuration changes immediately clear login query caches.
- ➖ Causes unnecessary cache churn for providers never available at login.
- ➖ Reduces the performance benefit of caching in realms with frequent unrelated updates.
</dd>
</dl>
</details>
<details>
<summary><b>2. Use independent composite cache keys</b></summary>
<dl>
<dd>
- ➕ Stores each fetch-mode and organization query as an isolated entry.
- ➕ Avoids replacing a shared query object when adding an organization search.
- ➖ Creates more cache entries and requires broader key tracking during invalidation.
- ➖ Does not reuse the existing IdentityProviderListQuery pattern.
</dd>
</dl>
</details>
>**Recommendation:** Keep the PR's shared revisioned query cache with selective invalidation. It follows the existing organization-query cache design and avoids unnecessary invalidations; reviewers should focus on ensuring every eligibility and organization-link transition triggers invalidation.
</dd>
</dl>
</details>
<details>
<summary> Files changed (4) <code> +268 / -3 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (1) <code> +95 / -1 </code></summary>
<dl>
<dd>
<details>
<summary>InfinispanIdentityProviderStorageProvider.java<code>Cache login IDP queries with selective invalidation</code> <code>+95/-1</code></summary>
<br/>
>Cache login IDP queries with selective invalidation
>
><pre>
>• Adds revisioned login-query caches keyed by realm and fetch mode, with organization IDs stored as query search keys. Resolves cached IDs through organization-aware models, falls back to JPA for missing entries, and invalidates caches only when creation, removal, eligibility changes, or organization reassignment can affect login results.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/49/files#diff-50455e412570489d0dbe7f3f4505197bafadc877a984ddd7a68acc6cf94f46b5'>model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/idp/InfinispanIdentityProviderStorageProvider.java</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Bug fix (2) <code> +3 / -2 </code></summary>
<dl>
<dd>
<details>
<summary>IdentityProviderStorageProvider.java<code>Restrict organization login providers to public brokers</code> <code>+1/-0</code></summary>
<br/>
>Restrict organization login providers to public brokers
>
><pre>
>• Extends the shared login predicate so organization-linked providers qualify only when configured as public brokers. Realm-level providers retain the existing enabled, link-only, and hidden-state filtering.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/49/files#diff-d47a80ef4b9ffb4ab5668f30de1bfecdf68ed8a89c40cdd3eab670fa18df6acc'>server-spi/src/main/java/org/keycloak/models/IdentityProviderStorageProvider.java</a>
</details>
<details>
<summary>OrganizationAwareIdentityProviderBean.java<code>Recheck wrapped provider enablement before rendering</code> <code>+2/-2</code></summary>
<br/>
>Recheck wrapped provider enablement before rendering
>
><pre>
>• Filters organization-aware login results by their effective enabled state after cached models may have been wrapped. This prevents providers belonging to disabled organizations from appearing on login pages.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/49/files#diff-18cf2ba92fb388ee8e827b46cfca64efe481d9ad8bd22d64fef662f943140a3d'>services/src/main/java/org/keycloak/organization/forms/login/freemarker/model/OrganizationAwareIdentityProviderBean.java</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (1) <code> +170 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>OrganizationCacheTest.java<code>Verify login IDP caching and invalidation behavior</code> <code>+170/-0</code></summary>
<br/>
>Verify login IDP caching and invalidation behavior
>
><pre>
>• Adds integration coverage for cache population across all fetch modes and organization-specific searches. Verifies that irrelevant mutations preserve caches while eligibility changes and organization linking invalidate them and produce updated result counts.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/49/files#diff-d834887aac1b0c03cffef74dbdfffe9e27e8d58c537c5c966281c09a5d26187a'>testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/organization/cache/OrganizationCacheTest.java</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>