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

Simplifying session context handling, ensuring an always started transaction - #48471

Merged
ahus1 merged 6 commits into
keycloak:mainfrom
ahus1:is-48455-no-context-in-error-handler
May 7, 2026
Merged

ahus1 merged 6 commits into
keycloak:mainfrom
ahus1:is-48455-no-context-in-error-handler

Conversation

@ahus1
@ahus1 ahus1 commented Apr 24, 2026
Copy link
Copy Markdown
Member

Closes #48455

@ahus1 ahus1 self-assigned this Apr 24, 2026
@ahus1
ahus1 force-pushed the is-48455-no-context-in-error-handler branch 2 times, most recently from f3530b8 to 66c74a5 Compare April 24, 2026 15:02
@keycloak-github-bot keycloak-github-bot Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreported flaky test detected, please review

@keycloak keycloak deleted a comment from keycloak-github-bot Bot Apr 24, 2026
@ahus1
ahus1 force-pushed the is-48455-no-context-in-error-handler branch from 5c50386 to 1bf8f6a Compare April 24, 2026 16:26
@ahus1
ahus1 marked this pull request as ready for review April 27, 2026 08:57
@ahus1
ahus1 requested review from a team as code owners April 27, 2026 08:57
@ahus1
ahus1 commented Apr 27, 2026
Copy link
Copy Markdown
Member Author

@shawkins / @pedroigor - I've been investigating some strange behavior around sessions last week, and I think I found a possible corner case in the current session handling.

After some back and forth, and understanding pitfalls and the current handling, I'm suggesting this PR as a possible fix for a loophole in the transaction handling.

Can you please give it a review, and let me know if you think it is an improvement?

Thanks!

@shawkins
Copy link
Copy Markdown
Contributor

@ahus1 seems good as a simplification to use injection when possible - I tried to do that with KeycloakSessionFactory and it's recent conversion to a CDI bean, but hadn't gone back and looked at all the places we're getting the session.

I'll add a comment to the change about starting a transaction.

// 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".

@shawkins
shawkins commented Apr 29, 2026 •
Copy link
Copy Markdown
Contributor

This enforces that the lifecycle of the transactionmanager is a single transaction - that violates the principle of least surprise given the class name, so it should be documented on the interface.

edit - an additional thought is that KeycloakTransactionManager is part of the public spi, this change would need to be listed as a potential breaking change as in theory custom code could be relying on this behavior.

Alternatively you could expose a getStatus or wasCompleted method and use that instead of isActive - or just use the KeycloakSession thread local as was done previously.

@shawkins
Copy link
Copy Markdown
Contributor

This enforces that the lifecycle of the transactionmanager is a single transaction - that violates the principle of least surprise given the class name, so it should be documented on the interface.

edit - an additional thought is that KeycloakTransactionManager is part of the public spi, this change would need to be listed as a potential breaking change as in theory custom code could be relying on this behavior.

After trying out more scenarios, I see that our notion of transaction management is inheritly tied to the KeycloakSession. You cannot create a new transaction in an existing session and have things work as the provider creation is what utilizes all the enlist methods, so I was mistaken to look just at the KeycloakTransactionManager and infer that begin being called after completed was supported.

8000

ahus1 added 4 commits May 5, 2026 13:56
…saction

Closes keycloak#48455

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>
@ahus1
ahus1 force-pushed the is-48455-no-context-in-error-handler branch from 9c0c710 to 8bb8f4f Compare May 5, 2026 12:21
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
@ahus1
ahus1 force-pushed the is-48455-no-context-in-error-handler branch from 8bb8f4f to dfa313e Compare May 5, 2026 12:28
…egration/resteasy/TransactionalSessionHandler.java

Co-authored-by: Steven Hawkins <shawkins@redhat.com>
Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
@ahus1
ahus1 requested a review from shawkins May 5, 2026 14:46
@shawkins shawkins left a comment
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.

LGTM, @pedroigor do you want to check as well?

// 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 discussing keeping the TransactionalSessionHandler interface so that we easily identify the components involved in the lifecycle of "transactional (keycloak) sessions".

@ahus1
ahus1 merged commit 202b64d into keycloak:main May 7, 2026
142 of 146 checks passed
Comment on lines -63 to -72
10000
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);
}
});
}
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ContextNotActiveException during error handling

4 participants

0