diff --git a/openespi-thirdparty/pom.xml b/openespi-thirdparty/pom.xml index f7fb6d8f..18d267ee 100644 --- a/openespi-thirdparty/pom.xml +++ b/openespi-thirdparty/pom.xml @@ -199,6 +199,14 @@ h2 runtime + + + org.springframework.boot + spring-boot-h2console + runtime + 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..8788635c --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityConfiguration.java @@ -0,0 +1,114 @@ +/* + * + * 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.beans.factory.annotation.Value; +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; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; + +/** + * 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:

+ * + */ +@Configuration +@ConditionalOnProperty(name = "spring.h2.console.enabled", havingValue = "true") +public class H2ConsoleSecurityConfiguration { + + /** + * 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, + @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"), + 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 7f705094..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 @@ -21,6 +21,7 @@ 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; @@ -69,19 +70,31 @@ 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. + * 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 SecurityFilterChain filterChain(HttpSecurity http, - RetailCustomerUserDetailsService userDetailsService, - PasswordEncoder customerPasswordEncoder) throws Exception { + public DaoAuthenticationProvider customerAuthenticationProvider(RetailCustomerUserDetailsService userDetailsService) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService); - provider.setPasswordEncoder(customerPasswordEncoder); + 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 ({@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, + @Value("${spring.h2.console.path:/h2-console}") String h2ConsolePath) + 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 +105,11 @@ 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 (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(H2ConsoleSecurityConfiguration.basePath(h2ConsolePath) + "/**")).denyAll() .anyRequest().authenticated() ) .formLogin(form -> form @@ -107,7 +124,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,10 +148,9 @@ 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. .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/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): + * * *

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: *
    *
  1. the {@code return_to} form parameter, when it is a same-origin path;
  2. - *
  3. the request the login page interrupted;
  4. + *
  5. the request the login page interrupted (Spring Security's + * {@link SavedRequestAwareAuthenticationSuccessHandler} behavior);
  6. *
  7. 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.
  8. *
*/ -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/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..26891520 --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/security/SameOriginFetchAuthorizationManager.java @@ -0,0 +1,110 @@ +/* + * + * 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 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; +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.net.URI; +import java.util.function.Supplier; + +/** + * Request-origin check for a tool, such as the H2 console, that is exempt from CSRF tokens. Allows: + * + * + *

{@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 that are too old or strip the {@code Referer}).

+ */ +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} (no trailing slash) */ + public SameOriginFetchAuthorizationManager(String basePath) { + Assert.hasText(basePath, "basePath must not be empty"); + Assert.isTrue(basePath.startsWith("/") && !basePath.endsWith("/"), + "basePath must start with '/' and must not end with '/': " + basePath); + this.basePath = basePath; + } + + @Override + public AuthorizationResult authorize(Supplier authentication, + RequestAuthorizationContext context) { + HttpServletRequest request = context.getRequest(); + String site = request.getHeader(SEC_FETCH_SITE); + 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); + } + + /** 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; + } + 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/application-local.yml b/openespi-thirdparty/src/main/resources/application-local.yml index 3e62666e..8ba423fe 100644 --- a/openespi-thirdparty/src/main/resources/application-local.yml +++ b/openespi-thirdparty/src/main/resources/application-local.yml @@ -35,7 +35,9 @@ spring: enabled: true path: /h2-console settings: - web-allow-others: true + # 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 logging: 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/main/resources/templates/home.html b/openespi-thirdparty/src/main/resources/templates/home.html index 3876602f..8bae935b 100644 --- a/openespi-thirdparty/src/main/resources/templates/home.html +++ b/openespi-thirdparty/src/main/resources/templates/home.html @@ -8,6 +8,22 @@
+ + + + + +
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 new file mode 100644 index 00000000..5cf2ba38 --- /dev/null +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/config/H2ConsoleSecurityTest.java @@ -0,0 +1,229 @@ +/* + * + * 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.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; +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.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; +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. + * 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=/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; + + @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() { + 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(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(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").header("Referer", CONSOLE_REFERER) + .with(user("customer").roles("USER"))) + .andExpect(status().isForbidden()); + } + + @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")); + } + + @Test + @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").header("Referer", CONSOLE_REFERER) + .with(user("admin").roles("CUSTODIAN"))) + .andExpect(status().isNotFound()); + } + + @Test + @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 + "/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") + .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 entryRequest = get(CONSOLE + "/").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); + } + 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/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..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 @@ -21,6 +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; @@ -31,11 +34,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 +72,12 @@ class FormLoginTest { @Autowired private PasswordEncoder customerPasswordEncoder; + @MockitoSpyBean + private RetailCustomerUserDetailsService userDetailsService; + + @Autowired + private ApplicationContext applicationContext; + @BeforeEach void createAccounts() { cleanUp(); @@ -217,6 +230,53 @@ 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", "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 + @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()); + } + @Test @DisplayName("the DC's Notification POST is exempt from CSRF") void notification_post_is_not_blocked_by_csrf() throws Exception {