8000 Deprecate in-memory login failures and make persistent login failures the default by ahus1 · Pull Request #52128 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
d34ed26
Deprecate in-memory login failures and make persistent login failures…
ahus1 Aug 27, 2026
cc9b305
Fixing tests
ahus1 Aug 28, 2026
3aaaf12
Fixing tests
ahus1 Aug 28, 2026
d63933f
Optimize performance for successful login path
ahus1 Aug 28, 2026
f4096aa
Fix test that breaks on H2
ahus1 Aug 28, 2026
f015d94
Ensure that data is written to the database before returning, otherwi…
ahus1 Aug 28, 2026
a0a3a6c
Fixing test as we're now expiring
ahus1 Aug 28, 2026
0c376af
Fixing test
ahus1 Aug 28, 2026
8264543
Adding this test as it triggers brute force detection
ahus1 Aug 28, 2026
242cdab
Run more stateless tests in the CI on each database
ahus1 Aug 28, 2026
93c7326
Extend the database dialects to support the "on conflict"
ahus1 Aug 28, 2026
cd97db7
Fix MERGE emulation for HQL queries without explicit conflict columns
ahus1 Aug 28, 2026
06aff0e
Fixing failing test
ahus1 Aug 28, 2026
32aab4c
Fixing concurrency deadlocks
ahus1 Aug 29, 2026
21f6680
Extending the upgrading guide
ahus1 Aug 29, 2026
995eee6
Fixing model tests and integration tests
ahus1 Aug 29, 2026
2452944
Fixing tests
ahus1 Aug 29, 2026
562ab7a
Created an upstream issue to see that it will be included in upstream…
ahus1 Aug 30, 2026
b2fca8c
Stabilizing the test
ahus1 Aug 30, 2026
1edfe0e
Guidance for Galera cluster
ahus1 Aug 30, 2026
b434eff
Refactoring docs
ahus1 Aug 30, 2026
5d9bbc5
Refactoring and code cleanup
ahus1 Aug 31, 2026
70d9dcc
Adding a comment to explain the why
ahus1 Aug 31, 2026
04c3d8c
Updating the brute force protector
ahus1 Aug 31, 2026
e2f3cb2
Reworking locking for brute force detection
ahus1 Aug 31, 2026
375b877
Do the work within a single SQL connection
ahus1 Aug 31, 2026
beac47b
Apply batched suggestions from code review
ahus1 Aug 31, 2026
8f0d885
Addressing review comments
ahus1 Sep 1, 2026
09a4ebd
Require a shutown first when changing the login failure feature.
ahus1 Sep 1, 2026
2d5da51
Updating the rationale why DefaultLockingBruteForceProtector is needed
ahus1 Sep 1, 2026
d96c7f7
Apply batched suggestions from code review
ahus1 Sep 1, 2026
013a6a5
Fixing test
ahus1 Sep 1, 2026
00c3c60
Update model/infinispan/src/main/java/org/keycloak/connections/infini…
ahus1 Sep 2, 2026
1283034
Update entity retrieval with pessimistic locking
ahus1 Sep 3, 2026
82053bc
Addressing another round of copilot changes
ahus1 Sep 3, 2026
02e145c
Addressing another round of copilot changes
ahus1 Sep 3, 2026
0d1ba24
Addressing another round of copilot changes
ahus1 Sep 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
13 changes: 2 additions & 11 deletions .github/actions/run-store-tests/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,10 @@ runs:
-pl testsuite/integration-arquillian/tests/base \
2>&1 | misc/log/trimmer.sh

# The LoginTest should be enough to exercise the authentication sessions
- name: Run stateless smoke test
- name: Run stateless tests
shell: bash
run: |
./mvnw test ${{ env.SUREFIRE_RETRY }} \
-Pauth-server-quarkus -Pdb-${{ inputs.db }} \
"-Dwebdriver.chrome.driver=$CHROMEWEBDRIVER/chromedriver" \
-Dtest=LoginTest \
-Dauth.server.feature=stateless \
-Ddocker.database.skip=true \
-Ddocker.database.port=$DATABASE_PORT \
-Ddocker.container.testdb.ip=localhost \
-pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh
KC_TEST_DATABASE=${{ inputs.db }} KC_TEST_DATABASE_REUSE=true TESTCONTAINERS_REUSE_ENABLE=true ./mvnw package -f tests/pom.xml -Dtest=StatelessTestSuite -Dkc.test.server.start.timeout=360

- uses: ./.github/actions/upload-flaky-tests
name: Upload flaky tests
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -846,7 +846,7 @@ jobs:
name: Store IT
needs: build
runs-on: ubuntu-latest
timeout-minutes: 75
timeout-minutes: 85
strategy:
matrix:
db: [postgres, mysql, oracle, mssql, mariadb]
Expand Down
5 changes: 4 additions & 1 deletion
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,12 @@ public enum Feature {

TRANSIENT_USERS("Transient users for brokering", Type.EXPERIMENTAL),

LOGIN_FAILURES_V1("In-memory login failures", Type.DEPRECATED, 1, FeatureUpdatePolicy.SHUTDOWN),
LOGIN_FAILURES_V2("Persistent login failures", Type.DEFAULT, 2, FeatureUpdatePolicy.SHUTDOWN),

MULTI_SITE("Multi-site support", Type.DISABLED_BY_DEFAULT, FeatureUpdatePolicy.SHUTDOWN),

STATELESS("Stateless (stores authentication sessions, action tokens and login failure data in the database, allowing multiple clusters to be connected with just the database)", Type.PREVIEW, FeatureUpdatePolicy.SHUTDOWN),
STATELESS("Stateless (stores authentication sessions, action tokens and login failure data in the database, allowing multiple clusters to be connected with just the database)", Type.PREVIEW, FeatureUpdatePolicy.SHUTDOWN, Feature.LOGIN_FAILURES_V2),

CLUSTERLESS("Store all session data, work cache and login failure data in an external Infinispan cluster.", Type.EXPERIMENTAL, FeatureUpdatePolicy.SHUTDOWN),

Expand Down
7 changes: 7 additions & 0 deletions docs/documentation/release_notes/topics/26_8_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ In this release, Client Secret Rotation is promoted from preview to supported. F

{project_name} now supports encrypted PKCS#8 private keys in PEM format for HTTPS configuration. Use the new `--https-certificate-key-file-password` option to provide the decryption password. The management interface also supports this via `--https-management-certificate-key-file-password`. For details, see <@links.server id="enabletls"/>.

== Login failures now stored in the database

Brute force detection data is now persisted in the database by default, so temporarily locked-out users remain locked out across cluster restarts.
Deployments using the `multi-site` or `clusterless` features continue to store login failures in the external Infinispan cluster.
The previous in-memory behavior is available as `login-failures:v1` but is deprecated.
For details, see the link:{upgradingguide_link}[{upgradingguide_name}].

== Automatic non-blocking index creation for large tables
// https://github.com/keycloak/keycloak/issues/46555

Expand Down
8 changes: 4 additions & 4 deletions docs/documentation/tests/src/test/resources/ignored-links
Original file line number Diff line number Diff line change
Expand Up 10BC8 @@ -46,7 +46,7 @@ https://www.oasis-open.org/standard/saml/
https://www.h2database.com/*
# Blocks automated HTTP requests from CI runners (returns 403), but loads fine in a browser.
https://www.iso.org/*
# Remove after 26.7 release
https://www.keycloak.org/securing-apps/ssf-support
https://www.keycloak.org/securing-apps/authzen-authorization
https://www.keycloak.org/high-availability/multi-cluster-v2/introduction

# Remove after 26.8 release
https://www.keycloak.org/server/db#mariadb-galera-cluster-considerations
https://www.keycloak.org/server/db#mysql-mariadb-transaction-isolation-level-in-stateless-mode
38 changes: 38 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-26_8_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ Revalidating certificates can be problematic in certain installations (for examp
// ------------------------ Notable changes ------------------------ //
== Notable changes

=== Login failures now stored in the database by default

Login failure data for brute force detection is now stored in the database by default, instead of only in the embedded Infinispan `loginFailures` cache. This ensures that temporarily locked-out users remain locked out across cluster restarts, and reduces memory consumption from accumulated login failure entries.

This change is controlled by the new `login-failures` versioned feature. The previous in-memory behavior (`login-failures:v1`) is deprecated. To restore it, set `--features=login-failures:v1`. Note that `login-failures:v1` is incompatible with the `stateless` feature.

Deployments using the `multi-site` or `clusterless` features continue to store login failure data in the external Infinispan cluster, regardless of the `login-failures` feature version.

As a trade-off, users may observe increased database connection usage and higher CPU usage on the database.

The option `spi-brute-force-protector-default-brute-force-detector-allow-concurrent-requests` is deprecated and has no effect with `login-failures:v2`.
Instead, concurrent logins for the same user are executed serially for each node.

=== Clusterless feature will be removed

The experimental `clusterless` feature will be removed in a future release. The `stateless` feature is the successor for running {project_name} without depending on an external Infinispan cluster. While `clusterless` offloads all session data to an external Infinispan cluster, `stateless` stores session data in the database and uses the embedded Infinispan only as a cache.
Expand Down Expand Up @@ -165,6 +178,27 @@ When {project_name} generates self-signed certificates (for example, during SAML

If you have tooling that inspects the CN of {project_name}-generated certificates and expects it to match a value longer than 64 characters, be aware that the CN may now be shorter.

=== Transaction isolation level changed to READ COMMITTED for MySQL and MariaDB in stateless mode

When the `stateless` feature is enabled, {project_name} now sets the transaction isolation level to `READ COMMITTED` for MySQL and MariaDB.
This prevents deadlocks that occur under concurrent logins.
If binary logging is enabled with `binlog_format = STATEMENT`, this change will cause write operations to fail.
{project_name} logs an error at startup when it detects this incompatible setting.

See the link:https://www.keycloak.org/server/db#mysql-mariadb-transaction-isolation-level-in-stateless-mode[Transaction isolation level in stateless mode] section in the database configuration guide for details on `binlog_format` requirements.

Changing the default transaction isolation level for all modes is being considered for a future release.

[#mariadb-galera-cluster-considerations]
=== MariaDB Galera Cluster considerations

WARNING: MariaDB Galera Cluster is not a supported database configuration for {project_name}. The guidance in this section is provided on a best-effort basis. Before reporting bugs, reproduce them with a supported database configuration first.

On a multi-writer Galera setup, concurrent writes to the same row on different nodes can trigger certification failures, and asynchronous replication can cause stale reads.
{project_name} logs an error at startup when it detects Galera with `wsrep_sync_wait = 0`.

See the link:https://www.keycloak.org/server/db#mariadb-galera-cluster-considerations[MariaDB Galera Cluster] section in the database configuration guide for recommended settings and limitations.

=== Asynchronous commit on MS SQL Server and Oracle databases

The asynchronous commit optimization, previously available only on PostgreSQL, now also supports MS SQL Server and Oracle databases.
Expand Down Expand Up @@ -281,6 +315,10 @@ To avoid the deprecation warning at startup, set those SPI options to `false`.

Disabling the `persistent-user-sessions` feature (volatile sessions) is deprecated and will be removed in a future release. Persistent user sessions will become the only supported mode. If you have explicitly disabled persistent user sessions with `--features-disabled=persistent-user-sessions`, remove this option before upgrading to a future release.

=== In-memory login failures (`login-failures:v1`) is deprecated

The previous d 10BC8 efault of storing login failure data only in the in-memory Infinispan cache (`login-failures:v1`) is deprecated and will be removed in a future release. Login failures are now stored in the database by default (`login-failures:v2`). If you have explicitly enabled `login-failures:v1`, plan to remove this option before upgrading to a future release.

=== Organization invitation link no longer exposed in API responses

The `inviteLink` field in `OrganizationInvitationRepresentation` is deprecated and is no longer returned in Admin REST API responses from the organization invitation endpoints.
Expand Down
3 changes: 2 additions & 1 deletion docs/documentation/upgrading/topics/prep_migration.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Disabling `persistent-user-sessions` is deprecated since {project_name} 26.8 and

[WARNING]
====
Information about failed logins for brute force detection and currently ongoing authentication flows is only stored in the internal caches that are cleared when {project_name} is shut down.
Information about failed logins for brute force detection is now stored in the database by default since {project_name} 26.8 and survives cluster restarts.
Currently ongoing authentication flows are only stored in the internal caches that are cleared when {project_name} is shut down.
Users currently authenticating, changing their passwords, or resetting their passwords will need to restart the authentication flow once {project_name} is up and running again.
====
8 changes: 6 additions & 2 deletions docs/guides/server/caching.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,12 @@ to the node where their sessions were initially created. By doing that, you are
CPU, memory, and network utilization.

.Password brute force detection
The `loginFailures` distributed cache is used to track data about failed login attempts.
This cache is needed for the Brute Force Protection feature to work in a multi-node {project_name} setup.
Login failure data for brute force detection is stored in the database by default.
Deployments using the `multi-site` or `clusterless` features continue to store login failures in the external Infinispan `loginFailures` cache.
The embedded `loginFailures` distributed cache is available as a fallback when the deprecated `login-failures:v1` feature is explicitly enabled, but this mode will be removed in a future release.
When switching between storage modes (for example, from database to external Infinispan or vice versa), stale login failure entries may remain in the previous store.
These entries are not cleaned up automatically and can resurface if the deployment reverts to the previous storage mode.
Administrators should manually remove stale login failure data from the previous store after switching.

.Action tokens
Action tokens are used for scenarios when a user needs to confirm an action asynchronously, for example in the emails sent by the forgot password flow.
Expand Down
51 changes: 50 additions & 1 deletion docs/guides/server/db.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -390,12 +390,61 @@ Secure the connection by adding the options:
* `db-tls-trust-store-file=/path/to/certificate`: The path to the server's public certificate file on the client machine.
====

== Preparing for MySQL server
== Preparing for MySQL and MariaDB

=== Generated invisible primary keys (MySQL)

Beginning with MySQL 8.0.30, MySQL supports generated invisible primary keys for any InnoDB table that is created without an explicit primary key (more information https://dev.mysql.com/doc/refman/8.0/en/create-table-gipks.html[here]).
If this feature is enabled, the database schema initialization and also migrations will fail with the error message `Multiple primary key defined (1068)`.
You then need to disable it by setting the parameter `sql_generate_invisible_primary_key` to `OFF` in your MySQL server configuration before installing or upgrading {project_name}.

[#mysql-mariadb-transaction-isolation-level-in-stateless-mode]
=== Transaction isolation level in stateless mode

When the `stateless` feature is enabled, {project_name} automatically sets the transaction isolation level to `READ COMMITTED` for MySQL and MariaDB.
The default `REPEATABLE READ` isolation level acquires gap locks on upsert statements, which causes deadlocks under concurrent logins.
`READ COMMITTED` is the default isolation level used by PostgreSQL, Oracle, and Microsoft SQL Server.

This requires that binary logging is not configured with `binlog_format = STATEMENT`.
MySQL 8.0 and later default to `binlog_format = ROW`, and MariaDB 10.6 and later defaults to `binlog_format = MIXED`, both of which are compatible.

To verify your current setting, run:

[source,sql]
----
SHOW VARIABLES LIKE 'binlog_format';
----

If the result is `STATEMENT`, change it to `ROW` or `MIXED`:

[source,sql]
----
SET GLOBAL binlog_format = 'ROW';
----

Alternatively, update the MySQL or MariaDB configuration file (`my.cnf` / `my.ini`) to make the change persistent across database restarts.

[#mariadb-galera-cluster-considerations]
=== MariaDB Galera Cluster

WARNING: MariaDB Galera Cluster is not a supported database configuration for {project_name}. The guidance in this section is provided on a best-effort basis. Before reporting bugs, reproduce them with a supported database configuration first.

MariaDB Galera Cluster uses certification-based replication.
The `transaction_isolation` setting configured by {project_name} has no practical effect on Galera, as Galera internally operates under its own Snapshot Isolation model regardless of the configured isolation level.

On a multi-writer Galera setup, concurrent write transactions on different nodes that modify the same row can trigger certification failures.
{project_name} does not retry these operations, which causes the affected request to fail.
In `stateless` mode, authentication sessions and login failure data are written directly to the database, increasing the likelihood of such conflicts under concurrent logins.

To avoid certification failures, route all {project_name} write traffic to a single Galera node, using the remaining nodes as read replicas or failover targets.

Galera replication is asynchronous by default.
A write committed on one node may not yet be visible on other nodes.
This affects all modes of {project_name}: when data is written to one node and a subsequent request is routed to a different node that has not yet received the replication event, the read may return stale or missing data.
This can cause cache invalidation to race with replication, leading to stale data being served from the database after the cache has been cleared.
If read traffic is distributed across multiple nodes, set `wsrep_sync_wait = 1` on the reader nodes to enable causal reads.
This ensures that read operations wait for all pending replication events to be applied before returning results.

== Preparing for MS SQL server

On MS SQL Server, the default transaction isolation level is `READ_COMMITTED`, which can lead to deadlocks during high load. Therefore, the recommended isolation level for {project_name} is `READ_COMMITTED_SNAPSHOT`. This isolation level is used by default on Azure SQL.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,11 @@ protected EmbeddedCacheManager createEmbeddedCacheManager(KeycloakSession sessio
.forEach(holder.getNamedConfigurationBuilders()::remove);
}

// remove login-failure cache if V2 is active
if (Profile.isFeatureEnabled(Profile.Feature.LOGIN_FAILURES_V2)) {
holder.getNamedConfigurationBuilders().remove(LOGIN_FAILURE_CACHE_NAME);
}

StringBuilderWriter sw = new StringBuilderWriter();
ParserRegistry parser = new ParserRegistry();
try (ConfigurationWriter w = ConfigurationWriter.to(sw).prettyPrint(true).build()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public int order() {

@Override
public boolean isSupported(Config.Scope config) {
return !Profile.isFeatureEnabled(Profile.Feature.STATELESS) && InfinispanUtils.isEmbeddedInfinispan();
return Profile.isFeatureEnabled(Profile.Feature.LOGIN_FAILURES_V1) && InfinispanUtils.isEmbeddedInfinispan();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
@NamedQuery(
name = "insertRootAuthSessionIfAbsent",
query = "insert into RootAuthenticationSessionEntity (id, realmId, timestamp, version) values (:id, :realmId, :timestamp, 0)" +
" on conflict do nothing"
" on conflict (id) do nothing"
)
})
@Entity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,13 @@ private void lazyInit(KeycloakSession session) {
prepareOperationalInfo(connection);

String driverDialect = config.get("driverDialect");
// use configured dialect, else rely on Hibernate detection
if (driverDialect != null && !driverDialect.isBlank()) {
properties.put("hibernate.dialect", driverDialect);
} else {
String keycloakDialect = resolveKeycloakDialect(connection);
if (keycloakDialect != null) {
properties.put("hibernate.dialect", keycloakDialect);
}
}

migration(migrationStrategy, initializeEmpty, schema, databaseUpdateFile, connection, session);
Expand Down Expand Up @@ -381,6 +385,20 @@ public Connection getConnection() {
}
}

private static String resolveKeycloakDialect(Connection connection) {
try {
String dbKind = getDatabaseType(connection.getMetaData().getDatabaseProductName());
return switch (dbKind) {
case "h2" -> "org.keycloak.connections.jpa.dialect.KeycloakH2Dialect";
case "mssql" -> "org.keycloak.connections.jpa.dialect.KeycloakSQLServerDialect";
case "oracle" -> "org.keycloak.connections.jpa.dialect.KeycloakOracleDialect";
default -> null;
};
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
Comment thread
ahus1 marked this conversation as resolved.
Resolved

private String augmentJdbcUrl(String driver, String url) {
if (driver.equals("org.postgresql.xa.PGXADataSource") || driver.equals("org.postgresql.Driver")) {
url = addPostgreSQLKeywords(url);
Expand Down
Loading
Loading
0