Repository navigation
Simplifying session context handling, ensuring an always started transaction - #48471
Conversation
f3530b8 to
66c74a5
Compare
5c50386 to
1bf8f6a
Compare
|
@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! |
|
@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()) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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!
There was a problem hiding this comment.
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();
There was a problem hiding this comment.
I recall discussing keeping the TransactionalSessionHandler interface so that we easily identify the components involved in the lifecycle of "transactional (keycloak) sessions".
|
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. |
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. |
…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>
9c0c710 to
8bb8f4f
Compare
Signed-off-by: Alexander Schwartz <alexander.schwartz@ibm.com>
8bb8f4f to
dfa313e
Compare
…egration/resteasy/TransactionalSessionHandler.java Co-authored-by: Steven Hawkins <shawkins@redhat.com> Signed-off-by: Alexander Schwartz <alexander.schwartz@gmx.net>
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
I recall discussing keeping the TransactionalSessionHandler interface so that we easily identify the components involved in the lifecycle of "transactional (keycloak) sessions".
| 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); | ||
| } | ||
| }); | ||
| } |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
@vilmosnagy yes these changes caused that to happen. See #48838
cc @ahus1
Closes #48455