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 @@
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: 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}.
+ *
+ */
+@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):
+ *
+ *
*
*
{@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