8000 Simplifying session context handling, ensuring an always started transaction by ahus1 · Pull Request #48471 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Diff view
12 changes: 12 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-26_7_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ As before, for any rolling update or scaling up or down, we require to do this o

Use the `shutdown-timeout` option to adjust the timeout to your environment. Restore the original behavior by setting it to `1s`.

=== Extensions must not restart a Keycloak transaction

This change might affect custom {project_name} extensions.

The implicit transaction handling in {project_name} previously assumed that a transaction is started once per session, which is usually request-scoped. If it was started a second time, this might have led to an inconsistent state.

Starting with this version, this is now enforced and a session's transaction can only be started once. This prevents difficult-to-track errors and lost commits. It also ensures that at the start of the transaction, all nested transactions are started if they have not been started earlier.

A transaction is started automatically before the REST endpoint code is invoked, even if the session was created earlier in a filter.

As before, transactions can be nested, which will pause the outer transaction once the nested transaction starts, and will resume the outer transaction once the nested transaction ends.

=== Realm search now matches by display name

When searching for realms in the admin console, the search now also matches against the realm's display name in addition to the realm name.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public class KeycloakBeanProducer implements TransactionalSessionHandler {

@RequestScoped
public KeycloakSession getKeycloakSession() {
// This is triggered lazily on the first method call on the session.
// Do not start the transaction here as it could still be inside the event loop when used with a (prematching) filter.
// JTA transactions must only be used in a blocking thread, so defer this until later.
return factory.create();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022 Red Hat, Inc. and/or its affiliates
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -22,6 +22,7 @@
import java.util.stream.Stream;

import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
Expand All @@ -30,13 +31,22 @@
import jakarta.ws.rs.core.StreamingOutput;
import jakarta.ws.rs.ext.Provider;

import org.keycloak.utils.KeycloakSessionUtil;
import org.keycloak.models.KeycloakSession;

/**
* Closing the session at the end of the request.
* <p>
* This ensures the tranaction is committed and data is written to the database and the caches before the response is closed.
* Without this filter a request that runs shortly after the first request completed might return still stale data.
*/
@Provider
@PreMatching
@Priority(1)
public class CloseSessionFilter implements ContainerResponseFilter, org.keycloak.quarkus.runtime.transaction.TransactionalSessionHandler {

@Inject
KeycloakSession session;

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
Expand Down Expand Up @@ -66,6 +76,6 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
}

private void closeSession() {
close(KeycloakSessionUtil.getKeycloakSession());
close(session);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,32 @@
package org.keycloak.quarkus.runtime.integration.resteasy;

import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakTransactionManager;
import org.keycloak.utils.KeycloakSessionUtil;

import io.quarkus.arc.Arc;
import io.quarkus.arc.ClientProxy;
import org.jboss.resteasy.reactive.common.core.BlockingOperationSupport;
import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
import org.jboss.resteasy.reactive.server.spi.ServerRestHandler;

public final class TransactionalSessionHandler implements ServerRestHandler, org.keycloak.quarkus.runtime.transaction.TransactionalSessionHandler {

@Override
public void handle(ResteasyReactiveRequestContext requestContext) {
// This method might be invoked multiple times within a request when resolving sub-resources.

requestContext.requireCDIRequestScope();
KeycloakSession currentSession = Arc.container().instance(KeycloakSession.class).get();
// this handler might be invoked multiple times when resolving sub-resources
// make sure the transaction is began once when the session is first associated with the thread
if (KeycloakSessionUtil.setKeycloakSession(currentSession) == null) {
beginTransaction(currentSession);

if (BlockingOperationSupport.isBlockingAllowed()) {
// ClientProxy.unwrap() resolves a proxy that is lazily initialized on the first method call or on unwrap.
KeycloakSession currentSession = ClientProxy.unwrap(Arc.container().instance(KeycloakSession.class).get());
KeycloakTransactionManager transactionManager = currentSession.getTransactionManager();
if (!transactionManager.isActive()) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recall starting the transaction when the session was not assoicated with the thread because that should only be done once for the lifecylce. My concern with isActive is that it will return false after the transaction is complete, so we could be starting multiple transactions when not intended for the nested calls.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shawkins - I don't think starting a transaction a second time will happen as the transaction is supposed to be closed at the end of the request, not earlier. And once it is bound to a thread, it will not leave the thread.

I've updated Keycloak's default transaction to ensure that a transaction is not started or augmented after it has completed. The tests are green, I only needed to update two tests that were obviously wrong.

The alternative would be to add another method to the KeycloakTransactionManager, but I think this way is just safer. You're about to do something very wrong when you close the transaction earlier, or try to start it multiple times.

Let me know your thoughts. Thanks!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had responded here #48471 (comment) without seeing this initially.

I'm good with the change to the transaction manager.

Given that refinement using isActive here is good - should a developer do something that completes the session transaction early, we'll get an exception here.

The only other thought is that in the past @pedroigor wanted the methods of TransactionalSessionHandler to be used, rather than direct calls to transactionManager.begin();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recall discussing keeping the TransactionalSessionHandler interface so that we easily identify the components involved in the lifecycle of "transactional (keycloak) sessions".

// This handler is always running in a blocking thread.
beginTransaction(currentSession);
}
KeycloakSessionUtil.setKeycloakSession(currentSession);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ public DefaultKeycloakTransactionManager(KeycloakSession session) {

@Override
public void enlist(KeycloakTransaction transaction) {
if (completed) {
throw new IllegalStateException("Transaction already completed");
}
if (active && !transaction.isActive()) {
transaction.begin();
}
Expand All @@ -58,6 +61,9 @@ public void enlist(KeycloakTransaction transaction) {

@Override
public void enlistAfterCompletion(KeycloakTransaction transaction) {
if (completed) {
throw new IllegalStateException("Transaction already completed");
}
if (active && !transaction.isActive()) {
transaction.begin();
}
Expand All @@ -67,6 +73,9 @@ public void enlistAfterCompletion(KeycloakTransaction transaction) {

@Override
public void enlistPrepare(KeycloakTransaction transaction) {
if (completed) {
throw new IllegalStateException("Transaction already completed");
}
if (active && !transaction.isActive()) {
transaction.begin();
}
Expand All @@ -87,12 +96,13 @@ public void setJTAPolicy(JTAPolicy policy) {

@Override
public void begin() {
if (completed) {
throw new IllegalStateException("Transaction already completed");
}
if (active) {
throw new IllegalStateException("Transaction already active");
}

completed = false;

if (jtaPolicy == JTAPolicy.REQUIRES_NEW) {
JtaTransactionManagerLookup jtaLookup = session.getProvider(JtaTransactionManagerLookup.class);
if (jtaLookup != null) {
Expand All @@ -104,7 +114,21 @@ public void begin() {
}

for (KeycloakTransaction tx : transactions) {
tx.begin();
if (!tx.isActive()) {
tx.begin();
}
}

for (KeycloakTransaction tx : prepare) {
if (!tx.isActive()) {
tx.begin();
}
}

for (KeycloakTransaction tx : afterCompletion) {
if (!tx.isActive()) {
tx.begin();
}
}

active = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jakarta.inject.Inject;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
Expand All @@ -19,14 +20,12 @@
import org.keycloak.forms.login.MessageType;
import org.keycloak.forms.login.freemarker.model.UrlBean;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionTaskWithResult;
import org.keycloak.models.KeycloakTransaction;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.ModelException;
import org.keycloak.models.ModelIllegalStateException;
import org.keycloak.models.ModelValidationException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.messages.Messages;
Expand All @@ -36,16 +35,13 @@
import org.keycloak.theme.beans.MessageBean;
import org.keycloak.theme.beans.MessageFormatterMethod;
import org.keycloak.theme.freemarker.FreeMarkerProvider;
import org.keycloak.utils.KeycloakSessionUtil;
import org.keycloak.utils.MediaType;
import org.keycloak.utils.MediaTypeMatcher;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.jboss.logging.Logger;

import static org.keycloak.services.resources.KeycloakApplication.getSessionFactory;

@Provider
public class KeycloakErrorHandler implements ExceptionMapper<Throwable> {

Expand All @@ -56,21 +52,11 @@ public class KeycloakErrorHandler implements ExceptionMapper<Throwable> {
public static final String UNCAUGHT_SERVER_ERROR_TEXT = "Uncaught server error";
public static final String ERROR_RESPONSE_TEXT = "Error response {0}";

@Inject
KeycloakSession session;

@Override
public Response toResponse(Throwable throwable) {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();

if (session == null) {
// errors might be thrown when handling errors from JAX-RS before the session is available
return KeycloakModelUtils.runJobInTransactionWithResult(getSessionFactory(),
new KeycloakSessionTaskWithResult<Response>() {
@Override
public Response run(KeycloakSession session) {
return getResponse(session, throwable);
}
});
}
Comment on lines -63 to -72
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible that this change causes that running tests from IDE results in a NPE? I try to run KcOidcFirstBrokerLoginTest::shouldOfferOidcOptionOnLoginPageAfterUserTriedToLogInButDecidedNotTo on the current main branch, and the field session seems to be null, which suppresses the original Exception and throws an NPE from getResponse's first line.

The suppressed exception is (though this seems normal, as the test appears to try a cleanup at the beginning and handles the NotFoundException correctly):

jakarta.ws.rs.NotFoundException: Realm not found.
	at org.keycloak.services.resources.admin.RealmsAdminResource.getRealmAdmin(RealmsAdminResource.java:212)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
	at java.base/java.lang.reflect.Method.invoke(Method.java:565)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.constructLocator(ResourceLocatorInvoker.java:105)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.resolveTargetFromLocator(ResourceLocatorInvoker.java:86)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:137)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.invokeOnTargetObject(ResourceLocatorInvoker.java:168)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:131)
	at org.jboss.resteasy.core.ResourceLocatorInvoker.invoke(ResourceLocatorInvoker.java:33)
	at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:429)
	at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:240)
	at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:154)
	at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:321)
	at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:157)
	at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:229)
	at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:222)
	at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
	at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
	at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:614)
	at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
	at org.keycloak.testsuite.UndertowRequestFilter.lambda$doFilter$0(UndertowRequestFilter.java:55)
	at org.keycloak.models.utils.KeycloakModelUtils.lambda$runJobInTransaction$0(KeycloakModelUtils.java:355)
	at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransactionWithResult(KeycloakModelUtils.java:469)
	at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:354)
	at org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction(KeycloakModelUtils.java:344)
	at org.keycloak.testsuite.UndertowRequestFilter.doFilter(UndertowRequestFilter.java:51)
	at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:67)
	at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
	at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
	at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
	at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
	at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
	at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
	at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
	at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
	at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
	at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
	at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
	at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:75)
	at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
	at io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
	at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
	at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:278)
	at io.undertow.servlet.handlers.ServletInitialHandler$1.call(ServletInitialHandler.java:131)
	at io.undertow.servlet.handlers.ServletInitialHandler$1.call(ServletInitialHandler.java:128)
	at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
	at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
	at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:258)
	at io.undertow.servlet.handlers.ServletInitialHandler.lambda$new$1(ServletInitialHandler.java:100)
	at io.undertow.server.Connectors.executeRootHandler(Connectors.java:418)
	at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:938)
	at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
	at org.jboss.threads.EnhancedQueueExecutor$Task.doRunWith(EnhancedQueueExecutor.java:2651)
	at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2630)
	at org.jboss.threads.EnhancedQueueExecutor.runThreadBody(EnhancedQueueExecutor.java:1622)
	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1589)
	at org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1282)
	at java.base/java.lang.Thread.run(Thread.java:1474)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vilmosnagy yes these changes caused that to happen. See #48838

cc @ahus1


return getResponse(session, throwable);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public void testGetCredentialOfferWithABrokenNote() {
public void testGetCredentialOffer() {
String token = getBearerToken(oauth);

runOnServer.run(session -> {
String nonce = runOnServer.fetchString(session -> {
BearerTokenAuthenticator authenticator = new BearerTokenAuthenticator(session);
authenticator.setTokenString(token);

Expand All @@ -299,20 +299,27 @@ public void testGetCredentialOffer() {
CredentialOfferStorage offerStorage = session.getProvider(CredentialOfferStorage.class);
CredentialOfferState offerState = new CredentialOfferState(credOffer, null, null, Time.currentTime() + 60, null);
offerStorage.putOfferState(offerState);
return offerState.getNonce();
// The cache transactions need to be committed
});

// The cache transactions need to be committed explicitly in the test.
// Without that, the OAuth2Code will only be committed to the cache after .run((session)-> ...)
session.getTransactionManager().commit();

runOnServer.run(session -> {
BearerTokenAuthenticator authenticator = new BearerTokenAuthenticator(session);
authenticator.setTokenString(token);
OID4VCIssuerEndpoint issuerEndpoint = prepareIssuerEndpoint(session, authenticator);
Response credentialOfferResponse = issuerEndpoint.getCredentialOffer(offerState.getNonce());
Response credentialOfferResponse = issuerEndpoint.getCredentialOffer(nonce);

CredentialOfferStorage offerStorage = session.getProvider(CredentialOfferStorage.class);
offerStorage.getOfferStateByNonce(nonce);

assertEquals(HttpStatus.SC_OK, credentialOfferResponse.getStatus(), "The offer should have been returned.");
Object credentialOfferEntity = credentialOfferResponse.getEntity();
assertNotNull(credentialOfferEntity, "An actual offer should be in the response.");

CredentialsOffer retrievedCredentialsOffer = JsonSerialization.mapper.convertValue(credentialOfferEntity, CredentialsOffer.class);
assertEquals(credOffer, retrievedCredentialsOffer, "The offer should be the one prepared with for the session.");
assertEquals("the-issuer", retrievedCredentialsOffer.getCredentialIssuer());
assertEquals(new PreAuthorizedCodeGrant().setPreAuthorizedCode("the-code"), retrievedCredentialsOffer.getPreAuthorizedGrant());
assertEquals(List.of("credential-configuration-id"), retrievedCredentialsOffer.getCredentialConfigurationIds());
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public void testTransactionActive() {
Assertions.assertTrue(session.getTransactionManager().isActive());
session.getTransactionManager().commit();
Assertions.assertFalse(session.getTransactionManager().isActive());

session.getTransactionManager().begin();
});
runOnServer.run(session -> {
Assertions.assertTrue(session.getTransactionManager().isActive());
session.getTransactionManager().rollback();
Assertions.assertFalse(session.getTransactionManager().isActive());
Expand Down
Loading
0