Repository navigation
Deprecate in-memory login failures and make persistent login failures the default - #52128
Conversation
6fa88bf to
7979aa8
Compare
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.broker.KcSamlBrokerTest#loginWithExistingUserWithBruteForceEnabledKeycloak CI - FIPS IT (non-strict) |
20cef3b to
4ee8ee5
Compare
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.broker.KcOidcBrokerTest#loginWithExistingUserWithBruteForceEnabledKeycloak CI - Java Distribution IT (ubuntu-latest - temurin - 21) |
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.broker.KcOidcBrokerTest#loginWithExistingUserWithBruteForceEnabledKeycloak CI - Java Distribution IT (ubuntu-latest - temurin - 17) |
e663018 to
abcf9a5
Compare
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.forms.MultiFactorAuthenticationTest#testAlternativeCredentialsKeycloak CI - Forms IT (chrome) |
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.federation.ldap.LDAPUserLoginTest#loginLDAPUserCredentialVaultAuthenticationNoneEncryptionStartTLSKeycloak CI - Java Distribution IT (windows-latest - temurin - 17) |
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.webauthn.passwordless.WebAuthnPwdLessPropertyTest#timeout |
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.webauthn.passwordless.WebAuthnPwdLessPropertyTest#timeout |
| return false; | ||
| } | ||
| // Expired if last failure is older than maxDeltaTimeSeconds (same threshold used by LoginFailureExpirationAction). | ||
| long expireMs = TimeUnit.SECONDS.toMillis((long) Time.currentTime() - realm.getMaxDeltaTimeSeconds()); |
There was a problem hiding this comment.
Use Time.currentTimeSeconds() instead
There was a problem hiding this comment.
It is probably worth to move this computation to a common method to be shared between here and the expiration task.
// returns the timestamp of expired entries, or -1 if permanent lockout is configured
public static long computeExpiration(RealmModel realm, long currentTime) {
if (realm.isPermanentLockout() && realm.getMaxTemporaryLockouts() == 0) {
// If mode is permanent lockout only, the "failure reset time" cannot be configured and login failures should never expire.
return -1L;
}
// expired if last-failure + max-delta-time < current time
return TimeUnit.SECONDS.toMillis(currentTime - realm.getMaxDeltaTimeSeconds());
}| @@ -361,6 +364,58 @@ private void checkMySQLWaitTimeout() { | |||
| } | |||
| } | |||
|
|
|||
| private void checkMySQLBinlogFormat() { | |||
| if (!Profile.isFeatureEnabled(Profile.Feature.STATELESS)) { | |||
There was a problem hiding this comment.
shouldn't this check be performed when login-failures-v2 is enabled?
There was a problem hiding this comment.
We're only switching to READ COMMITTED isolation level when stateless is enabled. It is essential for root authentication sessions, and not for login failures. I'll add a line comment in the next commit.
| if (vendor != Database.Vendor.MYSQL && vendor != Database.Vendor.MARIADB && vendor != Database.Vendor.TIDB) { | ||
| return false; | ||
| } | ||
| return Profile.isFeatureEnabled(Profile.Feature.STATELESS); |
There was a problem hiding this comment.
Doesn't login-failures:v2 requires it too?
There was a problem hiding this comment.
The tests didn't show it, and I hope not. The tests didn't require it. I assume there are not so many concurrent inserts here, and once the table fills it shouldn't lead to deadlocks. If there are complaints, they can roll back to login failures V1.
I don't feel ready to make this enable for all databases. We could have a follow-up discussion on that one, and then re-decide for 26.8. But it would need to be opt-in.
| import org.keycloak.models.RealmModel; | ||
| import org.keycloak.models.UserModel; | ||
|
|
||
| public class DefaultLockingBruteForceProtector extends DefaultBlockingBruteForceProtector { |
There was a problem hiding this comment.
Should it extend DefaultBruteForceProtector instead? The DefaultBlockingBruteForceProtector has a Map with 1000 entries instantiated every time, wasting memory. It has no use since the instance is not shared between sessions.
There was a problem hiding this comment.
Yes, this was broken, well spotted. I'm rewriting this completely in the next commit.
| @@ -48,7 +49,7 @@ public void init(Config.Scope config) { | |||
|
|
|||
| @Override | |||
| public void postInit(KeycloakSessionFactory factory) { | |||
| protector = allowConcurrentRequests ? new DefaultBruteForceProtector(factory) : new DefaultBlockingBruteForceProtector(factory); | |||
| protector = Profile.isFeatureEnabled(Profile.Feature.LOGIN_FAILURES_V2) ? null : allowConcurrentRequests ? new DefaultBruteForceProtector(factory) : new DefaultBlockingBruteForceProtector(factory); | |||
There was a problem hiding this comment.
nitpic, an if-else would it make more readable
| 10BC8 | return; | |
| } | ||
|
|
||
| try (Connection connection = getConnection(); |
There was a problem hiding this comment.
can't you do this in the connection above (line 396)?
There was a problem hiding this comment.
thanks, reworked in next commit
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.forms.MultipleTabsLoginTest#testLoginAfterLogoutFromDifferentTabKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#loginActionWithoutExecutionKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestWithAuthSessionExpiredAndRequiredActionKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#expiredAuthenticationAction_expiredCodeExpiredExecutionKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testWithAuthSessionExpiredInTheMiddle_badRedirectUriKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testEmptyBaseUrlKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testRestartFailureWithDifferentClientAfterAuthSessionExpirationKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#expiredAuthenticationAction_currentCodeExpiredExecutionKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testLogoutDifferentBrowserWithAuthenticationSessionStillPresentKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsLoginAndPassiveCheckKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestWithAuthSessionExpiredInTheMiddleKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#loginActionWithoutExecutionInRequiredActionsKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestWithAuthSessionExpiredAndRefreshInTab1Keycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testLoginPageRefreshKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#loginWithDifferentClientsKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestWithAuthSessionExpiredAndRegisterClickKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#multipleTabsParallelLoginTestKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#expiredAuthenticationAction_expiredCodeCurrentExecutionKeycloak CI - Forms IT (chrome) org.keycloak.testsuite.forms.MultipleTabsLoginTest#testInjectRedirectUriInClientDataAfterAuthSessionExpirationKeycloak CI - Forms IT (chrome) |
There was a problem hiding this comment.
Pull request overview
Makes persistent, database-backed login failures the default while retaining deprecated in-memory and remote-cache modes.
Changes:
- Adds versioned login-failure features, persistence, expiration, cleanup, and locking.
- Adds database dialect and isolation handling for reliable upserts.
- Expands tests, CI coverage, migration guidance, and release documentation.
Reviewed changes
Copilot reviewed 34 out of 35 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
testsuite/model/.../Stateless.java |
Resolves stateless feature dependency. |
testsuite/model/.../Jpa.java |
Adds expiration-task dependencies. |
testsuite/model/.../Infinispan.java |
Enables deprecated V1 for tests. |
testsuite/integration-arquillian/.../keycloak-server.json |
Defaults tests to JPA failures. |
tests/base/.../StatelessTestSuite.java |
Expands stateless coverage. |
tests/base/.../LoginFailureExpirationTest.java |
Tests real-time expiration. |
services/.../DefaultLockingBruteForceProtector.java |
Serializes same-user logins. |
services/.../DefaultBruteForceProtectorFactory.java |
Selects V1/V2 protection behavior. |
server-spi-private/.../LoginFailureUtils.java |
Centralizes expiration calculation. |
quarkus/tests/.../CustomJpaEntityProviderDistTest.java |
Updates dialect expectation. |
quarkus/runtime/.../DatasourcesConfigurationTest.java |
Tests custom dialect defaults. |
quarkus/runtime/.../ConfigurationTest.java |
Updates database configuration tests. |
quarkus/runtime/.../QuarkusJpaConnectionProviderFactory.java |
Adds database startup checks. |
quarkus/runtime/.../DatabasePropertyMappers.java |
Configures READ COMMITTED. |
quarkus/config-api/.../Database.java |
Registers Keycloak dialects. |
model/jpa/.../OutboxEntryEntity.java |
Specifies upsert conflict columns. |
model/jpa/.../UserLoginFailureAdapter.java |
Optimizes failure clearing. |
model/jpa/.../LoginFailureExpirationAction.java |
Uses shared expiration logic. |
model/jpa/.../JpaUserLoginFailureProviderFactory.java |
Enables JPA V2 and cleanup. |
model/jpa/.../JpaUserLoginFailureProvider.java |
Handles persistent expiration. |
model/jpa/.../KeycloakSQLServerDialect.java |
Adds SQL Server MERGE emulation. |
model/jpa/.../KeycloakOracleDialect.java |
Adds Oracle MERGE emulation. |
model/jpa/.../KeycloakH2Dialect.java |
Adds H2 MERGE emulation. |
model/jpa/.../DefaultJpaConnectionProviderFactory.java |
Auto-detects custom dialects. |
model/jpa/.../RootAuthenticationSessionEntity.java |
Specifies upsert conflict key. |
model/infinispan/.../InfinispanUserLoginFailureProviderFactory.java |
Restricts embedded storage to V1. |
docs/guides/server/db.adoc |
Documents database requirements. |
docs/guides/server/caching.adoc |
Documents login-failure storage. |
docs/.../prep_migration.adoc |
Updates migration preparation. |
docs/.../changes-26_8_0.adoc |
Adds notable upgrade changes. |
docs/.../ignored-links |
Updates temporary link exclusions. |
docs/.../release_notes/topics/26_8_0.adoc |
Announces persistent failures. |
common/.../Profile.java |
Registers V1/V2 features. |
.github/workflows/ci.yml |
Extends Store IT timeout. |
.github/actions/run-store-tests/action.yml |
Runs full stateless tests. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
…span/DefaultInfinispanConnectionProviderFactory.java Co-authored-by: Pedro Ruivo <pruivo@users.noreply.github.com> Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
1691cd4 to
0d1ba24
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Secondary-factor counters can be reset inadvertently, and JPA cleanup is mis-scoped when the remote provider is selected.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (1)
model/jpa/src/main/java/org/keycloak/loginfailures/jpa/JpaUserLoginFailureProviderFactory.java:88
- Provider ordering only controls which provider
getProvider()returns; every enabled factory still receivespostInit. With default v2 plus a higher-order remote provider, this therefore schedules an unused JPA cleanup task that scans every realm and the database every interval. Guard scheduling so it runs only when JPA is the selected login-failure provider.
ExpirationTask.builder()
.withEntityId("login-failure")
.withAction(LoginFailureExpirationAction.INSTANCE)
.withFactory(factory)
.withExecutor(ExpirationHelper.expirationExecutor(factory))
.withMaxRemoval(expirationTaskMaxRemoval)
.withMetrics(metricsEnabled)
.withRealmExpiration(true)
.withTimeout(expirationTaskTimeoutSeconds, TimeUnit.SECONDS)
.withInterval(expirationTaskIntervalSeconds, TimeUnit.SECONDS)
.build()
.schedule();
- Files reviewed: 35/37 changed files
- Comments generated: 3
- Review effort level: Balanced
Unreported flaky test detectedIf the flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR. org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest#salesPostTestKeycloak CI - Adapter IT Strict Cookies org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest#employeeSigPostNoIdpKeyTestKeyIdAsKeyNameInKeyInfoKeycloak CI - Adapter IT Strict Cookies org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest#testMultipleTabsParallelLoginKeycloak CI - Adapter IT Strict Cookies |
…stom dialects PR keycloak#52128 introduced custom database dialects (KeycloakH2Dialect, KeycloakSQLServerDialect, KeycloakOracleDialect) to fix Hibernate ORM HHH-20826 ('on conflict do nothing' dropping conflict clause) and made them the default dialects in Database.java. When producing user-defined persistence units, resolve dialects with the following precedence: 1. Explicit CLI/config option (--db-dialect-<datasource>) always wins. 2. Dialects declared in persistence.xml: standard Hibernate dialects replaced by Keycloak dialects (H2, MSSQL, Oracle) are upgraded to the Keycloak equivalents, while custom user dialects are honored. 3. If no dialect is declared in persistence.xml, derive dialect from the datasource DB kind. Also update CustomJpaEntityProviderDistTest assertions to expect KeycloakH2Dialect for default, client-store, and pu-without-dialect-store persistence units, while preserving KeycloakItH2Dialect for custom user unit.
Closes #52126
Summary
login-failureswithv1(in-memory, deprecated) andv2(persistent/database, default).stateless) is now active by default viaLOGIN_FAILURES_V2, making database-backed login failures the standard for single-site deployments.login-failures:v1is explicitly enabled.KeycloakH2Dialect,KeycloakOracleDialect,KeycloakSQLServerDialect) fixINSERT ... ON CONFLICT ... DO NOTHINGbeing silently dropped by Hibernate on H2, Oracle, and MS SQL Server.statelessfeature is enabled, preventing deadlocks from gap locks on upsert statements.clearFailures()optimization: skips database locking on successful logins when no failure data exists.maxDeltaTimeSeconds, matching the Infinispan TTL behavior.ProviderEventListener.Decisions and assumptions
RemoteUserLoginFailureProviderFactory, regardless of thelogin-failuresfeature version. No dependency onLOGIN_FAILURES_V2was added to these features. The remote provider'sisSupported()check (!STATELESS && isRemoteInfinispan()) is unchanged.statelessalready required JPA login failures, this dependency is a natural fit. The versioned feature conflict mechanism preventslogin-failures:v1from being enabled alongsidestateless.order()=1vs JPA's defaultorder()=0. When both are supported (e.g.,clusterless+ defaultv2), the 8000 remote provider wins automatically — no explicit exclusion needed in the JPA provider.ON CONFLICT ... DO NOTHINGconflict clauses instead of emitting MERGE statements. The custom dialects overridevisitInsertStatementOnlyto callvisitInsertStatementEmulateMergewhen conflict columns are present. MySQL/MariaDB and PostgreSQL handle this correctly out of the box. The Quarkus distribution sets the custom dialect on all persistence units;DefaultJpaConnectionProviderFactory(used in tests) auto-detects the database and applies the dialect.LoginFailureEntity,OutboxEntryEntity, andRootAuthenticationSessionEntityspecifyON CONFLICT(id) DO NOTHING(or composite keys) so the dialect can produce a correct MERGE ON clause.INSERT ... ON DUPLICATE KEY UPDATE, causing deadlocks under concurrent logins. READ COMMITTED is set only whenstatelessis enabled to limit the blast radius. This matches PostgreSQL, Oracle, and SQL Server defaults. Requiresbinlog_format = ROWorMIXED(default since MySQL 8.0 / MariaDB 10.6). Changing isolation for all modes is being considered for a future release.clearFailures()avoids unnecessary locking: On successful logins,clearFailures()checks whether any failure data exists before acquiring a database lock. This avoids contention on the login failure row during the common successful-login path.lastFailureis older thanmaxDeltaTimeSeconds(same threshold asLoginFailureExpirationAction). Expired entries are filtered out on read and re-initialized on upsert. A backgroundExpirationTaskperiodically purges old entries.Jpa.javaaddsTimerSpi/ExecutorsSpiand their factories (required by the expiration task now loaded by default).Stateless.javaremoves theLOGIN_FAILURES_V1system property set byInfinispan.javato prevent the V1/STATELESS dependency conflict.CustomJpaEntityProviderDistTestupdated because Quarkus overrides dialect for all persistence units (4xKeycloakH2Dialect).wsrep_sync_wait = 1. Also the isolation level READ COMMITTED will only be effective within a node, but not across nodes. With that, all writes need to go to a single node.🤖 Generated with Claude Code