Repository navigation
fix: share the thread local security context between strategy instances - #25509
Merged
Artur- merged 2 commits intoSep 7, 2026
Merged
Conversation
`VaadinAwareSecurityContextHolderStrategy` kept its fallback `SecurityContext` in a per-instance `ThreadLocal`, while `SecurityContextHolder` holds one strategy per classloader and the strategy is contributed as a bean of an application context. With one application context that is the same object, so nothing shows. With several contexts in one JVM - typically the contexts cached by the Spring test framework, where every `@SpringBootTest` with a different configuration refreshes another one - each context creates its own instance and its `SmartInitializingSingleton` replaces the global strategy, while the beans of the previously refreshed contexts stay wired to their own instance. The two stores then diverge: `SecurityContextHolder`, and with it navigation access control and `AuthenticationContext`, reads the instance installed last, whereas the `@PreAuthorize` interceptors read their own context's instance. A test that authenticates through `SecurityContextHolder` gets `AuthenticationCredentialsNotFoundException` from a secured bean, `@WithMockUser` has the opposite effect, and because spring-security-test only clears the strategy bean, a context written into the static holder leaks into the next test class. Whether a suite is green depends on the order in which the test classes run. Storing the context in a static field, as Spring Security's own `ThreadLocalSecurityContextHolderStrategy` does, makes all instances interchangeable, so it no longer matters which one is installed. Fixes #25507 Fixes #16953
Now that the store is shared by all instances, thread scoping is the only thing keeping one request's SecurityContext out of another, so assert it: a second thread neither sees the context of the main thread nor leaks its own back into it. The auto-configuration test ended with a getContext() call, which lazily stores an empty context in the shared thread local, leaving it behind for the tests running afterwards on the same thread. Clear it along with restoring the previously installed strategy.
heruan
approved these changes
Sep 7, 2026
|
Contributor
Artur-
deleted the
issues/25507-static-security-context-holder-strategy
branch
September 7, 2026 10:44
vaadin-bot
added a commit
that referenced
this pull request
Sep 7, 2026
…es (#25509) (CP: 25.2) (#25514) This PR cherry-picks changes from the original PR #25509 to branch 25.2. --- #### Original PR description > ## What > > `VaadinAwareSecurityContextHolderStrategy` kept its fallback `SecurityContext` in a **per-instance** `ThreadLocal`. It is now stored in a `static` field, shared by all instances of the class, mirroring what Spring Security's own `ThreadLocalSecurityContextHolderStrategy` does. The class javadoc explains why. > > ## Why > > `SecurityContextHolder` holds one strategy **per classloader**, but the strategy is contributed as a **bean of an application context**. > > With a single application context those are the same object, so nothing shows. With several contexts in one JVM — typically the contexts cached by the Spring test framework, where every `@SpringBootTest` with a different configuration refreshes another one — each context creates its own instance and its `SmartInitializingSingleton` replaces the global strategy, while the beans of previously refreshed contexts stay wired to *their* instance. The two stores then diverge: > > - `SecurityContextHolder`, and with it navigation access control and `AuthenticationContext`, reads the instance installed **last**; > - the `@PreAuthorize` interceptors read **their own context's** instance. > > So a test that authenticates through `SecurityContextHolder` gets `AuthenticationCredentialsNotFoundException` from a secured bean, `@WithMockUser` has the opposite effect, and because spring-security-test only clears the strategy *bean*, a context written into the static holder leaks into the next test class. Whether a suite is green depends on the order in which the test classes run. > > Storing the context statically makes all instances interchangeable, so it no longer matters which one is installed. > > Fixes #25507 > Fixes #16953 > > ## Test summary > > | # | Status | What the test verifies | Why it matters | > |---|--------|------------------------|----------------| > | 1 | ✅ | A context set on one strategy instance is returned by another instance, and clearing on one clears it for all | This is the fix: divergent per-instance stores are what made `SecurityContextHolder` and the method security interceptors disagree | > | 2 | ✅ | The shared store is still thread scoped: a second thread neither sees the main thread's context nor leaks its own back into it | With a static store, thread scoping is the only thing keeping one request's `SecurityContext` out of another's — a regression here is a security bug | > | 3 | ✅ | With two refreshed application contexts, the strategy beans are distinct objects, yet a context written via `SecurityContextHolder` (served by the second context's bean) is seen by the first context's bean, and `clearContext()` propagates back | Reproduces the reported scenario end to end, including the leak-into-the-next-test half of it | > | 4 | ✅ | The auto-configuration test restores the previously installed strategy **and** clears the context it left behind | `getContext()` lazily stores an empty context in the now-shared thread local; leaving it behind would make the following tests on that thread order dependent | > | 5 | ❗ **gap** | A `@PreAuthorize`-secured bean from an earlier-refreshed context actually authorizes a user authenticated through `SecurityContextHolder` | Row 3 pins the mechanism, not the user-visible symptom (`AuthenticationCredentialsNotFoundException`); a full `@SpringBootTest` pair would be needed and is not added here | > > Tests added/changed on this branch: > > - `VaadinAwareSecurityContextHolderStrategyTest.separateInstances_shareThreadSecurityContext` → 1 > - `VaadinAwareSecurityContextHolderStrategyTest.separateThreads_doNotShareThreadSecurityContext` → 2 > - `SpringSecurityAutoConfigurationTest.multipleContexts_strategyBeansShareSecurityContext` → 3, 4 > - `VaadinAwareSecurityContextHolderStrategyTest.setup` / `.teardown` (changed) → clear the now-shared thread local between tests, so 1 and 2 cannot pass or fail because of leftovers from a previous test > > Deliberately not re-tested: the `VaadinSession`-bound branch of `getContext()` (session context taking precedence over the thread context, invalidated session falling back) is untouched by this change and stays covered by the pre-existing tests in the same class. Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Collaborator
|
This ticket/PR has been released with Vaadin 25.3.0-beta2. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



What
VaadinAwareSecurityContextHolderStrategykept its fallbackSecurityContextin a per-instanceThreadLocal. It is now stored in astaticfield, shared by all instances of the class, mirroring what Spring Security's ownThreadLocalSecurityContextHolderStrategydoes. The class javadoc explains why.Why
SecurityContextHolderholds one strategy per classloader, but the strategy is contributed as a bean of an application context.With a single application context those are the same object, so nothing shows. With several contexts in one JVM — typically the contexts cached by the Spring test framework, where every
@SpringBootTestwith a different configuration refreshes another one — each context creates its own instance and itsSmartInitializingSingletonreplaces the global strategy, while the beans of previously refreshed contexts stay wired to their instance. The two stores then diverge:SecurityContextHolder, and with it navigation access control andAuthenticationContext, reads the instance installed last;@PreAuthorizeinterceptors read their own context's instance.So a test that authenticates through
SecurityContextHoldergetsAuthenticationCredentialsNotFoundExceptionfrom a secured bean,@WithMockUserhas the opposite effect, and because spring-security-test only clears the strategy bean, a context written into the static holder leaks into the next test class. Whether a suite is green depends on the order in which the test classes run.Storing the context statically makes all instances interchangeable, so it no longer matters which one is installed.
Fixes #25507
Fixes #16953
Test summary
SecurityContextHolderand the method security interceptors disagreeSecurityContextout of another's — a regression here is a security bugSecurityContextHolder(served by the second context's bean) is seen by the first context's bean, andclearContext()propagates backgetContext()lazily stores an empty context in the now-shared thread local; leaving it behind would make the following tests on that thread order dependent@PreAuthorize-secured bean from an earlier-refreshed context actually authorizes a user authenticated throughSecurityContextHolderAuthenticationCredentialsNotFoundException); a full@SpringBootTestpair would be needed and is not added hereTests added/changed on this branch:
VaadinAwareSecurityContextHolderStrategyTest.separateInstances_shareThreadSecurityContext→ 1VaadinAwareSecurityContextHolderStrategyTest.separateThreads_doNotShareThreadSecurityContext→ 2SpringSecurityAutoConfigurationTest.multipleContexts_strategyBeansShareSecurityContext→ 3, 4VaadinAwareSecurityContextHolderStrategyTest.setup/.teardown(changed) → clear the now-shared thread local between tests, so 1 and 2 cannot pass or fail because of leftovers from a previous testDeliberately not re-tested: the
VaadinSession-bound branch ofgetContext()(session context taking precedence over the thread context, invalidated session falling back) is untouched by this change and stays covered by the pre-existing tests in the same class.