Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions openespi-thirdparty/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,14 @@
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- H2 web console (Spring Boot 4 moved its auto-configuration into this module). Active only
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. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-h2console</artifactId>
<scope>runtime</scope>
</dependency>

<!-- Flyway for Database Migrations -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -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/**}.
*
* <p>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:</p>
* <ul>
* <li>H2 itself answering localhost only ({@code web-allow-others: false} on every profile that
* enables the console);</li>
* <li>a signed-in TP administrator ({@code ROLE_CUSTODIAN}; the session from the TP's form login
* applies here too);</li>
* <li>{@link SameOriginFetchAuthorizationManager}: the browser must report the request as
* 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.</li>
* </ul>
*/
@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)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
// 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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")
Expand All @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
* <ul>
* <li>{@code admin} / {@code admin}, a TP administrator ({@code ROLE_CUSTODIAN});</li>
* <li>{@code customer} / {@code customer}, a TP customer ({@code ROLE_USER}), who sees the
* Data Access Authorization cards and can try the TP &rarr; Data Custodian authorization.</li>
* </ul>
*
* <p><strong>DEV ONLY.</strong> 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}.</p>
* an account that already exists is left alone. Mirrors the DC's {@code DevSandboxAdminSeedRunner}.</p>
*/
@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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -36,38 +36,45 @@
* Form-login success handler for the Third Party (#249). Redirects to, in order:
* <ol>
* <li>the {@code return_to} form parameter, when it is a same-origin path;</li>
* <li>the request the login page interrupted;</li>
* <li>the request the login page interrupted (Spring Security's
* {@link SavedRequestAwareAuthenticationSuccessHandler} behavior);</li>
* <li>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.</li>
* </ol>
*/
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) {
Expand Down
Loading
Loading