Skip to content

fix: share the thread local security context between strategy instances - #25509

Merged
Artur- merged 2 commits into
mainfrom
issues/25507-static-security-context-holder-strategy
Sep 7, 2026
Merged

Artur- merged 2 commits into
mainfrom
issues/25507-static-security-context-holder-strategy

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

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.

`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.
@github-actions github-actions Bot added the +0.0.1 label Sep 7, 2026
@sonarqubecloud

sonarqubecloud Bot commented Sep 7, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Test Results

 1 434 files  ±0   1 518 suites  ±0   1h 35m 54s ⏱️ + 2m 34s
11 885 tests +3  11 817 ✅ +3  68 💤 ±0  0 ❌ ±0 
12 203 runs  +3  12 135 ✅ +3  68 💤 ±0  0 ❌ ±0 

Results for commit 7c41b82. ± Comparison against base commit c88b90e.

@Artur-
Artur- added this pull request to the merge queue Sep 7, 2026
Merged via the queue into main with commit 665fb9f Sep 7, 2026
48 checks passed
@Artur-
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>
@vaadin-bot

Copy link
Copy Markdown
Collaborator

This ticket/PR has been released with Vaadin 25.3.0-beta2.

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