From b1e1c0e71e04d32abf599396125f5ea511f01f61 Mon Sep 17 00:00:00 2001 From: "Donald F. Coffin" Date: Tue, 17 Nov 2026 14:54:09 -0500 Subject: [PATCH 1/3] feat(thirdparty): Spring Security oauth2Client for the Data Custodian authorization (#146) The Third Party's customer flow now uses Spring Security 7 oauth2Client instead of oauth2Login: the TP customer stays signed in to the TP (form login) while authorizing it at the Data Custodian, and the tokens are kept for that customer. - Tokens are stored in the ESPI authorizations table through a new OAuth2AuthorizedClientService (EspiAuthorizationOAuth2AuthorizedClientService), with the REQ.21 token-response URIs (resourceURI, authorizationURI, customerResourceURI) captured from the token response. A refresh that does not repeat them keeps the stored URIs. - Flyway V6 adds authorizations.client_registration_id (MySQL, PostgreSQL, H2). - Only a signed-in TP customer (ROLE_USER) may start an authorization_code registration; anonymous visitors go to /login, the TP administrator gets 403. - datacustodian-admin is now the client_credentials registration for the TP's client access token (FB=34_35). The TP administrator obtains it on the admin page, which shows its scope, expiry, a token prefix and the authorizationURI, resourceURI (energy usage Bulk) and customerResourceURI (Customer PII Bulk) once the AS returns them (#202). - The TP home page lists the customer's authorizations. - PKCE is off in the TP until the AS carries code_challenge through the Data Custodian delegation (#274). - Removed the legacy /oauth/callback controller, the oauth2Login user-info settings and the openid/profile scopes. Co-Authored-By: Claude Opus 5.5 --- docs/LOCAL_TESTING.md | 22 +- .../domain/usage/AuthorizationEntity.java | 8 + .../mapper/usage/AuthorizationMapper.java | 1 + .../usage/AuthorizationRepository.java | 14 + ...d_authorization_client_registration_id.sql | 20 + .../config/ActuatorSecurityConfiguration.java | 2 +- .../config/SecurityConfiguration.java | 93 ++++- .../oauth/DataCustodianRegistrations.java} | 19 +- ...rizationOAuth2AuthorizedClientService.java | 188 +++++++++ .../oauth/EspiTokenResponseParameters.java | 96 +++++ ...pCustomerAuthorizationRequestResolver.java | 97 +++++ .../thirdparty/web/AuthorizationView.java | 58 +++ .../web/CustodianHomeController.java | 62 ++- .../espi/thirdparty/web/HomeController.java | 46 ++- .../web/ModernAuthorizationController.java | 288 -------------- .../web/OAuth2ClientController.java | 132 +++--- .../src/main/resources/application.yml | 31 +- .../resources/templates/custodian/home.html | 43 +- .../src/main/resources/templates/home.html | 61 ++- .../schema/AbstractThirdPartySchemaTest.java | 5 +- .../web/DataCustodianAuthorizationTest.java | 375 ++++++++++++++++++ .../espi/thirdparty/web/FormLoginTest.java | 3 +- .../thirdparty/web/HomeControllerTests.java | 29 +- .../src/test/resources/application-test.yml | 3 +- 24 files changed, 1236 insertions(+), 460 deletions(-) create mode 100644 openespi-common/src/main/resources/db/migration/V6__Add_authorization_client_registration_id.sql rename openespi-thirdparty/src/{test/java/org/greenbuttonalliance/espi/thirdparty/web/custodian/CustodianHomeControllerTests.java => main/java/org/greenbuttonalliance/espi/thirdparty/oauth/DataCustodianRegistrations.java} (50%) create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java create mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java delete mode 100644 openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/ModernAuthorizationController.java create mode 100644 openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java diff --git a/docs/LOCAL_TESTING.md b/docs/LOCAL_TESTING.md index a76250eb..6d03e226 100644 --- a/docs/LOCAL_TESTING.md +++ b/docs/LOCAL_TESTING.md @@ -32,8 +32,8 @@ Logs go to `.local-run/.log`. Run the smoke check before testing by hand; i | AS admin | `admin` / `admin` at http://localhost:9999/login | A passkey is enrolled at first login (`/webauthn/register`), by design. Override with `ESPI_BOOTSTRAP_ADMIN_USERNAME` / `ESPI_BOOTSTRAP_ADMIN_PASSWORD_HASH`. | | DC admin | `admin` / `admin` | Sandbox custodian user (dev/test profiles only). | | DC customer | `customer` / `customer` | Owns the sample UsagePoint (see "Sample data"). `local` profile only. | -| TP admin | `admin` / `admin` at http://localhost:8082/ThirdParty/login | TP administrator (`ROLE_CUSTODIAN`); also opens the H2 console at `/ThirdParty/h2-console/`. `local` profile only. | -| TP customer | `customer` / `customer` | TP customer (`ROLE_USER`); sees the Data Access Authorization cards. `local` profile only. | +| TP admin | `admin` / `admin` at http://localhost:8082/ThirdParty/login | TP administrator (`ROLE_CUSTODIAN`); obtains the TP's client access token on the admin page, and opens the H2 console at `/ThirdParty/h2-console/`. `local` profile only. | +| TP customer | `customer` / `customer` | TP customer (`ROLE_USER`); authorizes the TP at the DC from the Data Access Authorization cards (see "Customer flow"). `local` profile only. | ## OAuth clients (AS) @@ -106,12 +106,20 @@ On the `local` profile the DC seeds a small, deterministic ESPI dataset at start The schema values follow the most common shapes in the Green Button CMD certification test feeds. Every identifying value is synthetic (`example.com`, `555-01xx`, `SAMPLE-…` numbers). +## Customer flow (TP → AS → DC → TP) + +1. Sign in to the TP as `customer` / `customer` at http://localhost:8082/ThirdParty/login. +2. On the TP home page, choose **Authorize Monthly Access** (or Daily). The TP sends you to the AS, which hands the login and consent to the DC. +3. At the DC, sign in as `customer` / `customer` and approve the requested data on the Authorization Screen. +4. You return to the TP home page, still signed in to the TP, with "The Data Custodian authorized this Third Party". **Your authorizations** lists the scope, the access token's expiry, and the `resourceURI`, `authorizationURI` and `customerResourceURI` from the token response. + +The TP stores each token in its own ESPI `authorizations` table (Spring Security `oauth2Client`, #146), so the tokens survive a TP restart only on `dev-mysql` / `dev-postgresql`; on `local` the H2 database is in memory. + +The TP administrator (`admin` / `admin`) can obtain the TP's own client access token (client_credentials, `FB=34_35`) from the **Client Access Token** card on the admin page; it shows the scope, expiry, the first characters of the token only, and the token response's `authorizationURI`, `resourceURI` (energy usage Bulk) and `customerResourceURI` (Customer PII Bulk, when applicable). The AS does not return these URIs for client_credentials tokens yet (#202). + ## Known limitations -The customer flow does not complete yet. Open blockers, in the order they are hit (see the roadmap, #255): +The customer flow stops after the token is stored. Open items (see the roadmap, #255): -- **#249:** the TP has no user login page. -- **#232:** the AS → DC delegation (`/authorize/delegate`) drops the authorization parameters and returns 400. -- **#146 / #202:** the TP's token handling and the resource URIs in the token response. - **#197 / #89:** the TP cannot yet read and display the DC's feeds. -- **#211:** a customer narrowing the requested data at consent gets `invalid_scope`. +- **#202:** the AS's token-response URIs: `customerResourceURI` is gated on FB 54–62 instead of FB_51, a refresh re-provisions the subscription, and the `FB=34_35` client access token carries no `authorizationURI`, `resourceURI` (energy usage Bulk) or `customerResourceURI` (Customer PII Bulk). diff --git a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/domain/usage/AuthorizationEntity.java b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/domain/usage/AuthorizationEntity.java index abc3fc3d..17a1a5b4 100644 --- a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/domain/usage/AuthorizationEntity.java +++ b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/domain/usage/AuthorizationEntity.java @@ -230,6 +230,13 @@ public class AuthorizationEntity extends IdentifiedObject { @Column(name = "correlation_id", length = 256, unique = true) private String correlationId; + /** + * Third Party only (#146): the Spring OAuth2 client registration that obtained this + * Authorization's tokens (e.g. {@code datacustodian-monthly}). Not in the ESPI XSD; never exported. + */ + @Column(name = "client_registration_id", length = 100) + private String clientRegistrationId; + /** * Retail customer who granted this authorization. * Many authorizations can belong to one customer. @@ -509,6 +516,7 @@ public String toString() { "customerResourceURI = " + getCustomerResourceURI() + ", " + "thirdParty = " + getThirdParty() + ", " + "correlationId = " + getCorrelationId() + ", " + + "clientRegistrationId = " + getClientRegistrationId() + ", " + "description = " + getDescription() + ", " + "created = " + getCreated() + ", " + "updated = " + getUpdated() + ", " + diff --git a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/mapper/usage/AuthorizationMapper.java b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/mapper/usage/AuthorizationMapper.java index a344ad9e..fba5806e 100644 --- a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/mapper/usage/AuthorizationMapper.java +++ b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/mapper/usage/AuthorizationMapper.java @@ -106,6 +106,7 @@ public interface AuthorizationMapper { @Mapping(target = "retailCustomer", ignore = true) // Complex mapping, handle separately @Mapping(target = "subscriptions", ignore = true) // Aggregate children, managed via the subscription lifecycle @Mapping(target = "correlationId", ignore = true) // AS back-channel bookkeeping (#202), not in the XSD + @Mapping(target = "clientRegistrationId", ignore = true) // Third Party bookkeeping (#146), not in the XSD AuthorizationEntity toEntity(AuthorizationDto dto); } \ No newline at end of file diff --git a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java index b3848536..f05d24fa 100755 --- a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java +++ b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java @@ -49,6 +49,20 @@ public interface AuthorizationRepository extends JpaRepository findByState(String state); + /** + * Third Party token store (#146): the Authorization a TP customer obtained through one OAuth2 + * client registration (authorization_code). Newest first, in case of duplicates. + */ + Optional findFirstByClientRegistrationIdAndRetailCustomer_UsernameOrderByUpdatedDesc( + String clientRegistrationId, String username); + + /** + * Third Party token store (#146): the TP's own client access token (client_credentials), which + * belongs to the Third Party, not to a customer. + */ + Optional findFirstByClientRegistrationIdAndRetailCustomerIsNullOrderByUpdatedDesc( + String clientRegistrationId); + /** Back-channel idempotency lookup (#202): the Authorization provisioned for an AS grant. */ Optional findByCorrelationId(String correlationId); diff --git a/openespi-common/src/main/resources/db/migration/V6__Add_authorization_client_registration_id.sql b/openespi-common/src/main/resources/db/migration/V6__Add_authorization_client_registration_id.sql new file mode 100644 index 00000000..1f57f2da --- /dev/null +++ b/openespi-common/src/main/resources/db/migration/V6__Add_authorization_client_registration_id.sql @@ -0,0 +1,20 @@ +/* + * OpenESPI Authorization client registration id (#146) + * + * Copyright (c) 2018-2026 Green Button Alliance, Inc. + * Licensed under the Apache License, Version 2.0 + * + * The Third Party stores each token it obtains from a Data Custodian (access and refresh token, + * scope, resourceURI, authorizationURI, customerResourceURI) in its own authorizations table. A TP + * customer may hold one Authorization per Spring OAuth2 client registration (for example + * datacustodian-monthly and datacustodian-daily, which ask for different scopes), so the row records + * which registration obtained it. + * + * Additive and vendor-neutral (MySQL, PostgreSQL, H2): nullable, so existing rows and the Data + * Custodian's Authorizations (which never set it) are unaffected. Not part of the ESPI standard: + * Third Party bookkeeping, never exported in XML. + */ + +ALTER TABLE authorizations ADD COLUMN client_registration_id VARCHAR(100); + +CREATE INDEX idx_authorization_client_registration_id ON authorizations (client_registration_id); diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/ActuatorSecurityConfiguration.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/ActuatorSecurityConfiguration.java index 8c1a39c3..fd3f1633 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/ActuatorSecurityConfiguration.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/config/ActuatorSecurityConfiguration.java @@ -40,7 +40,7 @@ * ({@code ThirdParty_Admin_Access} by default). Endpoint access is read-only * ({@code management.endpoint.*.access} in application.yml).

* - *

Ordered first so actuator requests never reach the {@code oauth2Login} chain in + *

Ordered first so actuator requests never reach the browser (form login) chain in * {@link SecurityConfiguration}, which would redirect them to the login page.

*/ @Configuration 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 274540e7..fae22b16 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,7 +19,20 @@ package org.greenbuttonalliance.espi.thirdparty.config; +import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; +import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; +import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiTokenResponseParameters; +import org.greenbuttonalliance.espi.thirdparty.oauth.TpCustomerAuthorizationRequestResolver; import org.greenbuttonalliance.espi.thirdparty.security.RetailCustomerUserDetailsService; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; +import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest; +import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest; +import org.springframework.security.oauth2.client.endpoint.RestClientAuthorizationCodeTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.RestClientClientCredentialsTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.RestClientRefreshTokenTokenResponseClient; import org.greenbuttonalliance.espi.thirdparty.security.ReturnToAuthenticationSuccessHandler; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; @@ -74,8 +87,7 @@ public PasswordEncoder customerPasswordEncoder() { * {@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. + * failed login (two lookups, two BCrypt checks). */ @Bean public DaoAuthenticationProvider customerAuthenticationProvider(RetailCustomerUserDetailsService userDetailsService) { @@ -85,17 +97,26 @@ public DaoAuthenticationProvider customerAuthenticationProvider(RetailCustomerUs } /** - * 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. + * Two separate steps (#249, #146): a TP customer or administrator signs in to the Third Party + * with {@code formLogin} against the TP's own accounts ({@link #customerAuthenticationProvider}). + * A signed-in TP customer then authorizes the TP at a Data Custodian with {@code oauth2Client}: + * it completes the authorization-code grant and stores the token for the TP customer, without + * ever signing anyone in or changing who is signed in ({@code oauth2Login} replaced the customer's + * sign-in with the Data Custodian's, and signed in visitors who had no TP account). */ @Bean public SecurityFilterChain filterChain(HttpSecurity http, - @Value("${spring.h2.console.path:/h2-console}") String h2ConsolePath) + @Value("${spring.h2.console.path:/h2-console}") String h2ConsolePath, + ClientRegistrationRepository clientRegistrationRepository, + OAuth2AccessTokenResponseClient + authorizationCodeTokenResponseClient) throws Exception { http .authorizeHttpRequests(authz -> authz + // Starting a Data Custodian authorization is for a signed-in TP customer only (an + // anonymous visitor goes to the login page first; see TpCustomerAuthorizationRequestResolver). + .requestMatchers(TpCustomerAuthorizationRequestResolver.AUTHORIZATION_BASE_URI + "/**", + "/oauth2/authorize/**").hasAuthority(RetailCustomerEntity.ROLE_USER) // Public pages (Terms of Service and Usage Policy are linked from the navbar, About from // the footer) .requestMatchers("/", "/home", "/login", "/about", "/TermsOfService", "/UsagePolicy", "/error", @@ -121,13 +142,15 @@ public SecurityFilterChain filterChain(HttpSecurity http, .failureUrl("/login?error") .permitAll() ) - .oauth2Login(oauth2 -> oauth2 - .loginPage("/login") - .defaultSuccessUrl("/", 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") + // The Data Custodian redirects back to {baseUrl}/login/oauth2/code/{registrationId} (the + // redirect URIs the AS registers). OAuth2AuthorizationCodeGrantFilter exchanges the code and + // then redirects to that path again, with ?error=... if consent was refused or the exchange + // failed; OAuth2ClientController turns that into the home page's message. + .oauth2Client(client -> client + .authorizationCodeGrant(grant -> grant + .authorizationRequestResolver(new TpCustomerAuthorizationRequestResolver(clientRegistrationRepository)) + .accessTokenResponseClient(authorizationCodeTokenResponseClient) + ) ) .logout(logout -> logout .logoutUrl("/logout") @@ -156,18 +179,52 @@ public SecurityFilterChain filterChain(HttpSecurity http, } /** - * OAuth2 Authorized Client Manager for handling OAuth2 flows. - * Supports authorization_code, refresh_token flows with automatic token refresh. + * The Third Party's Data Custodian tokens live in its ESPI {@code authorizations} table, with the + * token response's ESPI URIs (#146), not in Spring's in-memory store. + */ + @Bean + public EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService( + ClientRegistrationRepository clientRegistrationRepository, + AuthorizationRepository authorizationRepository, + RetailCustomerRepository retailCustomerRepository) { + return new EspiAuthorizationOAuth2AuthorizedClientService(clientRegistrationRepository, + authorizationRepository, retailCustomerRepository); + } + + /** authorization_code token exchange, keeping the response's ESPI URIs for the token store. */ + @Bean + public OAuth2AccessTokenResponseClient authorizationCodeTokenResponseClient() { + return EspiTokenResponseParameters.capturing(new RestClientAuthorizationCodeTokenResponseClient()); + } + + /** refresh_token exchange, keeping the response's ESPI URIs (if it repeats them) for the token store. */ + @Bean + public OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient() { + return EspiTokenResponseParameters.capturing(new RestClientRefreshTokenTokenResponseClient()); + } + + /** client_credentials exchange (the TP's client access token), keeping any ESPI URIs for the token store. */ + @Bean + public OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient() { + return EspiTokenResponseParameters.capturing(new RestClientClientCredentialsTokenResponseClient()); + } + + /** + * Obtains and refreshes Data Custodian tokens: a customer's (authorization_code, refreshed with + * its refresh token) and the TP's client access token (client_credentials). */ @Bean public OAuth2AuthorizedClientManager authorizedClientManager( ClientRegistrationRepository clientRegistrationRepository, - OAuth2AuthorizedClientRepository authorizedClientRepository) { + OAuth2AuthorizedClientRepository authorizedClientRepository, + OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient, + OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient) { OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() - .refreshToken() + .refreshToken(refresh -> refresh.accessTokenResponseClient(refreshTokenTokenResponseClient)) + .clientCredentials(client -> client.accessTokenResponseClient(clientCredentialsTokenResponseClient)) .build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/custodian/CustodianHomeControllerTests.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/DataCustodianRegistrations.java similarity index 50% rename from openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/custodian/CustodianHomeControllerTests.java rename to openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/DataCustodianRegistrations.java index 27afd4f2..4d66b257 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/custodian/CustodianHomeControllerTests.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/DataCustodianRegistrations.java @@ -17,19 +17,20 @@ * */ -package org.greenbuttonalliance.espi.thirdparty.web.custodian; +package org.greenbuttonalliance.espi.thirdparty.oauth; -import org.greenbuttonalliance.espi.thirdparty.web.CustodianHomeController; -import org.junit.jupiter.api.Test; +/** The Spring OAuth2 client registration ids the Third Party uses with the Data Custodian (application.yml). */ +public final class DataCustodianRegistrations { -import static org.junit.jupiter.api.Assertions.assertEquals; + /** authorization_code: a TP customer's monthly usage data. */ + public static final String MONTHLY = "datacustodian-monthly"; + /** authorization_code: a TP customer's daily usage data. */ + public static final String DAILY = "datacustodian-daily"; -public class CustodianHomeControllerTests { + /** client_credentials: the TP's client access token (ESPI Authorization and Bulk APIs). */ + public static final String CLIENT_ACCESS = "datacustodian-admin"; - @Test - public void index_displaysCustodianHomeView() throws Exception { - CustodianHomeController controller = new CustodianHomeController(); - assertEquals("custodian/home", controller.index()); + private DataCustodianRegistrations() { } } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java new file mode 100644 index 00000000..ddd90db9 --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java @@ -0,0 +1,188 @@ +/* + * + * 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.oauth; + +import org.greenbuttonalliance.espi.common.domain.common.enums.GrantType; +import org.greenbuttonalliance.espi.common.domain.common.enums.TokenType; +import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; +import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; +import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; +import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.OAuth2RefreshToken; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * Stores the tokens the Third Party obtains from a Data Custodian in its ESPI {@code authorizations} + * table (#146), instead of Spring's in-memory store: they survive a restart, and the row keeps the + * REQ.21 token-response URIs ({@code resourceURI}, {@code authorizationURI}, + * {@code customerResourceURI}) that the TP later fetches data from. + * + *
    + *
  • authorization_code registrations ({@code datacustodian-monthly}, + * {@code datacustodian-daily}): one row per TP customer and registration, linked to the + * customer's {@link RetailCustomerEntity}. The principal is the signed-in TP customer.
  • + *
  • client_credentials ({@code datacustodian-admin}): the TP's client access + * token belongs to the Third Party, not to whoever asked for it, so it is one row with no + * customer, whatever the principal.
  • + *
+ * + *

Re-authorizing replaces the row's tokens and URIs. Removal (Spring calls it when a refresh token + * is rejected) revokes the row, which clears its tokens, so the history stays visible.

+ */ +public class EspiAuthorizationOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService { + + private final ClientRegistrationRepository clientRegistrationRepository; + private final AuthorizationRepository authorizationRepository; + private final RetailCustomerRepository retailCustomerRepository; + + public EspiAuthorizationOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository, + AuthorizationRepository authorizationRepository, + RetailCustomerRepository retailCustomerRepository) { + this.clientRegistrationRepository = clientRegistrationRepository; + this.authorizationRepository = authorizationRepository; + this.retailCustomerRepository = retailCustomerRepository; + } + + @Override + @Transactional(readOnly = true) + @SuppressWarnings("unchecked") + public T loadAuthorizedClient(String clientRegistrationId, String principalName) { + ClientRegistration registration = clientRegistrationRepository.findByRegistrationId(clientRegistrationId); + if (registration == null) { + return null; + } + return (T) find(registration, principalName) + .filter(authorization -> authorization.getAccessToken() != null && !authorization.isRevoked()) + .map(authorization -> toAuthorizedClient(registration, principalName, authorization)) + .orElse(null); + } + + /** The stored Authorization for a registration and principal, whatever its status. */ + @Transactional(readOnly = true) + public Optional findAuthorization(String clientRegistrationId, String principalName) { + ClientRegistration registration = clientRegistrationRepository.findByRegistrationId(clientRegistrationId); + return registration == null ? Optional.empty() : find(registration, principalName); + } + + @Override + @Transactional + public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { + ClientRegistration registration = authorizedClient.getClientRegistration(); + AuthorizationEntity authorization = find(registration, principal.getName()) + .orElseGet(() -> newAuthorization(registration, principal.getName())); + + OAuth2AccessToken accessToken = authorizedClient.getAccessToken(); + authorization.setAccessToken(accessToken.getTokenValue()); + authorization.setTokenType(TokenType.BEARER); + // AuthorizationEntity.isExpired() compares expiresIn with System.currentTimeMillis(). + authorization.setExpiresIn(accessToken.getExpiresAt() == null ? null : accessToken.getExpiresAt().toEpochMilli()); + authorization.setScope(accessToken.getScopes().isEmpty() ? null + : accessToken.getScopes().stream().sorted().collect(Collectors.joining(" "))); + authorization.setRefreshToken(authorizedClient.getRefreshToken() == null ? null + : authorizedClient.getRefreshToken().getTokenValue()); + authorization.setGrantType(isClientCredentials(registration) ? GrantType.CLIENT_CREDENTIALS + : GrantType.AUTHORIZATION_CODE); + // A refresh response that repeats no URI keeps the ones the authorization_code response gave. + EspiTokenResponseParameters.take(accessToken.getTokenValue()).ifPresent(uris -> { + if (uris.resourceUri() != null) { + authorization.setResourceURI(uris.resourceUri()); + } + if (uris.authorizationUri() != null) { + authorization.setAuthorizationURI(uris.authorizationUri()); + } + if (uris.customerResourceUri() != null) { + authorization.setCustomerResourceURI(uris.customerResourceUri()); + } + }); + authorization.activate(); + authorizationRepository.save(authorization); + } + + @Override + @Transactional + public void removeAuthorizedClient(String clientRegistrationId, String principalName) { + findAuthorization(clientRegistrationId, principalName).ifPresent(authorization -> { + authorization.revoke(); + authorizationRepository.save(authorization); + }); + } + + private Optional find(ClientRegistration registration, String principalName) { + return isClientCredentials(registration) + ? authorizationRepository.findFirstByClientRegistrationIdAndRetailCustomerIsNullOrderByUpdatedDesc( + registration.getRegistrationId()) + : authorizationRepository.findFirstByClientRegistrationIdAndRetailCustomer_UsernameOrderByUpdatedDesc( + registration.getRegistrationId(), principalName); + } + + private AuthorizationEntity newAuthorization(ClientRegistration registration, String principalName) { + RetailCustomerEntity customer = null; + if (!isClientCredentials(registration)) { + customer = retailCustomerRepository.findByUsername(principalName) + .orElseThrow(() -> new IllegalStateException( + "Only a Third Party customer can authorize " + registration.getRegistrationId())); + } + AuthorizationEntity authorization = new AuthorizationEntity(customer, null, null); + authorization.setId(UUID.randomUUID()); + authorization.setThirdParty(registration.getClientId()); + authorization.setClientRegistrationId(registration.getRegistrationId()); + return authorization; + } + + private static OAuth2AuthorizedClient toAuthorizedClient(ClientRegistration registration, String principalName, + AuthorizationEntity authorization) { + Instant expiresAt = authorization.getExpiresIn() == null ? null : Instant.ofEpochMilli(authorization.getExpiresIn()); + Instant issuedAt = issuedAt(authorization.getUpdated(), expiresAt); + Set scopes = authorization.getScope() == null ? Set.of() + : new LinkedHashSet<>(Arrays.asList(authorization.getScope().trim().split("\\s+"))); + OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, + authorization.getAccessToken(), issuedAt, expiresAt, scopes); + OAuth2RefreshToken refreshToken = authorization.getRefreshToken() == null ? null + : new OAuth2RefreshToken(authorization.getRefreshToken(), issuedAt); + return new OAuth2AuthorizedClient(registration, principalName, accessToken, refreshToken); + } + + /** When the row was last written; never after the expiry (Spring requires issuedAt before expiresAt). */ + private static Instant issuedAt(LocalDateTime updated, Instant expiresAt) { + Instant issuedAt = updated == null ? Instant.now() : updated.atZone(ZoneId.systemDefault()).toInstant(); + return expiresAt != null && !issuedAt.isBefore(expiresAt) ? expiresAt.minusSeconds(1) : issuedAt; + } + + private static boolean isClientCredentials(ClientRegistration registration) { + return AuthorizationGrantType.CLIENT_CREDENTIALS.equals(registration.getAuthorizationGrantType()); + } +} diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java new file mode 100644 index 00000000..37c148e5 --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java @@ -0,0 +1,96 @@ +/* + * + * 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.oauth; + +import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; + +import java.util.Map; +import java.util.Optional; + +/** + * Keeps the ESPI URIs of a token response until the token is stored (#146). + * + *

REQ.21 6.1.2 puts {@code resourceURI}, {@code authorizationURI} and (with FB_51) + * {@code customerResourceURI} in the token response, next to the access token. Spring Security parses + * them into {@link OAuth2AccessTokenResponse#getAdditionalParameters()}, but the + * {@code OAuth2AuthorizedClient} it then stores holds only the tokens, so they would be lost. The + * {@link #capturing capturing} token-response client keeps them as a request attribute, keyed by the + * access token, and {@link EspiAuthorizationOAuth2AuthorizedClientService} takes them when it stores + * that token in the same request.

+ * + *

Outside a request (no {@link RequestContextHolder} attributes) nothing is kept; the stored + * Authorization then keeps the URIs it already has.

+ */ +public final class EspiTokenResponseParameters { + + /** REQ.21 6.1.2 token-response parameter names (as the Authorization Server writes them). */ + public static final String RESOURCE_URI = "resourceURI"; + public static final String AUTHORIZATION_URI = "authorizationURI"; + public static final String CUSTOMER_RESOURCE_URI = "customerResourceURI"; + + private static final String ATTRIBUTE_PREFIX = EspiTokenResponseParameters.class.getName() + "."; + + /** The ESPI URIs of one token response; any of them may be {@code null}. */ + public record EspiUris(String resourceUri, String authorizationUri, String customerResourceUri) { + + static EspiUris from(Map additionalParameters) { + return new EspiUris(text(additionalParameters, RESOURCE_URI), text(additionalParameters, AUTHORIZATION_URI), + text(additionalParameters, CUSTOMER_RESOURCE_URI)); + } + + private static String text(Map parameters, String name) { + Object value = parameters.get(name); + return value == null || value.toString().isBlank() ? null : value.toString(); + } + } + + private EspiTokenResponseParameters() { + } + + /** Wraps a Spring token-response client so the ESPI URIs of each response are kept for storage. */ + public static OAuth2AccessTokenResponseClient capturing( + OAuth2AccessTokenResponseClient delegate) { + return grantRequest -> { + OAuth2AccessTokenResponse response = delegate.getTokenResponse(grantRequest); + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + if (attributes != null && response != null) { + attributes.setAttribute(ATTRIBUTE_PREFIX + response.getAccessToken().getTokenValue(), + EspiUris.from(response.getAdditionalParameters()), RequestAttributes.SCOPE_REQUEST); + } + return response; + }; + } + + /** The ESPI URIs that came with this access token in the current request, removed once taken. */ + static Optional take(String accessTokenValue) { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + if (attributes == null) { + return Optional.empty(); + } + String name = ATTRIBUTE_PREFIX + accessTokenValue; + Object uris = attributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST); + attributes.removeAttribute(name, RequestAttributes.SCOPE_REQUEST); + return uris instanceof EspiUris espiUris ? Optional.of(espiUris) : Optional.empty(); + } +} diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java new file mode 100644 index 00000000..94c7fa0a --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java @@ -0,0 +1,97 @@ +/* + * + * 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.oauth; + +import jakarta.servlet.http.HttpServletRequest; +import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver; +import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; +import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; +import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; + +/** + * Starts a Data Custodian authorization ({@code /oauth2/authorization/{registrationId}}) only for a + * signed-in TP customer ({@code ROLE_USER}) and only for an authorization_code registration (#146). + * + *

Spring's {@code OAuth2AuthorizationRequestRedirectFilter} runs before the authorization rules, + * so they cannot stop it. Returning {@code null} here lets the request through to them instead: an + * anonymous visitor is sent to the login page (and back here afterwards), a TP administrator gets + * 403, and a client_credentials registration ({@code datacustodian-admin}) is not a redirect at all, + * where Spring's resolver would answer 500.

+ */ +public class TpCustomerAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver { + + public static final String AUTHORIZATION_BASE_URI = "/oauth2/authorization"; + + private static final String REGISTRATION_ID = "registrationId"; + + private final ClientRegistrationRepository clientRegistrationRepository; + private final DefaultOAuth2AuthorizationRequestResolver delegate; + private final RequestMatcher authorizationRequestMatcher = PathPatternRequestMatcher.withDefaults() + .matcher(AUTHORIZATION_BASE_URI + "/{" + REGISTRATION_ID + "}"); + + public TpCustomerAuthorizationRequestResolver(ClientRegistrationRepository clientRegistrationRepository) { + this.clientRegistrationRepository = clientRegistrationRepository; + this.delegate = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, AUTHORIZATION_BASE_URI); + // No PKCE for now. Spring Security 7 adds it by default (a ClientRegistration's requireProofKey + // defaults to true for authorization_code), but the AS replays /oauth2/authorize after the Data + // Custodian's consent without code_challenge, so the code exchange then fails with invalid_grant; + // the AS registers third_party with requireProofKey(false) ("ESPI does not use PKCE", #148). + // Restore PKCE once the AS carries code_challenge through the delegation (#274). + this.delegate.setAuthorizationRequestCustomizer(builder -> builder + .attributes(attributes -> attributes.remove(PkceParameterNames.CODE_VERIFIER)) + .additionalParameters(parameters -> { + parameters.remove(PkceParameterNames.CODE_CHALLENGE); + parameters.remove(PkceParameterNames.CODE_CHALLENGE_METHOD); + })); + } + + @Override + public OAuth2AuthorizationRequest resolve(HttpServletRequest request) { + RequestMatcher.MatchResult match = authorizationRequestMatcher.matcher(request); + return match.isMatch() ? resolve(request, match.getVariables().get(REGISTRATION_ID)) : null; + } + + @Override + public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId) { + if (clientRegistrationId == null || !isTpCustomer()) { + return null; + } + ClientRegistration registration = clientRegistrationRepository.findByRegistrationId(clientRegistrationId); + if (registration == null + || !AuthorizationGrantType.AUTHORIZATION_CODE.equals(registration.getAuthorizationGrantType())) { + return null; + } + return delegate.resolve(request, clientRegistrationId); + } + + private static boolean isTpCustomer() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + return authentication != null && authentication.isAuthenticated() && authentication.getAuthorities().stream() + .anyMatch(authority -> RetailCustomerEntity.ROLE_USER.equals(authority.getAuthority())); + } +} diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java new file mode 100644 index 00000000..8ce8a6e8 --- /dev/null +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java @@ -0,0 +1,58 @@ +/* + * + * 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.web; + +import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; + +/** + * One stored Data Custodian authorization (#146) as the TP pages show it. Never carries a token + * value except {@link #tokenPrefix}, the first characters of the access token, for the administrator's + * client access token check. + */ +public record AuthorizationView(String access, String status, String scope, String expires, String obtained, + String tokenPrefix, String resourceUri, String authorizationUri, + String customerResourceUri) { + + private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z") + .withZone(ZoneId.systemDefault()); + private static final int TOKEN_PREFIX_LENGTH = 8; + + static AuthorizationView of(AuthorizationEntity authorization, ClientRegistrationRepository registrations) { + ClientRegistration registration = authorization.getClientRegistrationId() == null ? null + : registrations.findByRegistrationId(authorization.getClientRegistrationId()); + String access = registration == null ? authorization.getClientRegistrationId() : registration.getClientName(); + String expires = authorization.getExpiresIn() == null ? "-" + : TIME.format(Instant.ofEpochMilli(authorization.getExpiresIn())); + String obtained = authorization.getUpdated() == null ? "-" + : TIME.format(authorization.getUpdated().atZone(ZoneId.systemDefault())); + String token = authorization.getAccessToken(); + String tokenPrefix = token == null ? null + : token.substring(0, Math.min(TOKEN_PREFIX_LENGTH, token.length())) + "…"; + return new AuthorizationView(access, authorization.getStatus(), authorization.getScope(), expires, obtained, + tokenPrefix, authorization.getResourceURI(), authorization.getAuthorizationURI(), + authorization.getCustomerResourceURI()); + } +} diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java index e5e3b2b0..03825f47 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java @@ -19,20 +19,76 @@ package org.greenbuttonalliance.espi.thirdparty.web; - +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.greenbuttonalliance.espi.thirdparty.oauth.DataCustodianRegistrations; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -/** The Third Party administrator's landing page after login (#249). */ +/** + * The Third Party administrator's landing page after login (#249), with a check of the TP's ESPI + * client access token (#146): obtained from the Authorization Server with client_credentials + * ({@code datacustodian-admin}), stored in the {@code authorizations} table with no customer, and + * shown by scope, expiry, any ESPI URIs, and the first characters of the token only. + */ @Controller @RequestMapping("/custodian/home") @PreAuthorize("hasRole('ROLE_CUSTODIAN')") public class CustodianHomeController extends BaseController { + private static final Logger logger = LoggerFactory.getLogger(CustodianHomeController.class); + + private final OAuth2AuthorizedClientManager authorizedClientManager; + private final EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService; + private final ClientRegistrationRepository clientRegistrationRepository; + + public CustodianHomeController(OAuth2AuthorizedClientManager authorizedClientManager, + EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService, + ClientRegistrationRepository clientRegistrationRepository) { + this.authorizedClientManager = authorizedClientManager; + this.authorizedClientService = authorizedClientService; + this.clientRegistrationRepository = clientRegistrationRepository; + } + @GetMapping - public String index() { + public String index(Authentication authentication, Model model) { + authorizedClientService.findAuthorization(DataCustodianRegistrations.CLIENT_ACCESS, authentication.getName()) + .map(authorization -> AuthorizationView.of(authorization, clientRegistrationRepository)) + .ifPresent(view -> model.addAttribute("clientToken", view)); return "custodian/home"; } + + /** + * Obtains a new client access token: any stored one is revoked first, so this always asks the + * Authorization Server rather than returning the token already held. + */ + @PostMapping("/client-token") + public String obtainClientToken(Authentication authentication, HttpServletRequest request, + HttpServletResponse response) { + authorizedClientService.removeAuthorizedClient(DataCustodianRegistrations.CLIENT_ACCESS, authentication.getName()); + try { + authorizedClientManager.authorize(OAuth2AuthorizeRequest + .withClientRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS) + .principal(authentication) + .attribute(HttpServletRequest.class.getName(), request) + .attribute(HttpServletResponse.class.getName(), response) + .build()); + return "redirect:/custodian/home?client_token"; + } catch (OAuth2AuthorizationException | IllegalStateException ex) { + logger.warn("Could not obtain the TP client access token: {}", ex.getMessage()); + return "redirect:/custodian/home?client_token_error"; + } + } } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java index f133d1eb..32626072 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java @@ -19,31 +19,54 @@ package org.greenbuttonalliance.espi.thirdparty.web; +import jakarta.servlet.http.HttpServletRequest; +import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; +import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; +import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; -import jakarta.servlet.http.HttpServletRequest; +import java.time.LocalDateTime; +import java.util.Comparator; +import java.util.List; /** * The Third Party home page. A TP administrator ({@code ROLE_CUSTODIAN}) is sent to the admin page; * everyone else gets {@code home}, which for a signed-in TP customer ({@code ROLE_USER}) shows the - * Data Access Authorization cards used to authorize the TP at a Data Custodian (#249). + * Data Access Authorization cards (#249) and the customer's stored authorizations (#146). */ @Controller public class HomeController { + private final RetailCustomerRepository retailCustomerRepository; + private final AuthorizationRepository authorizationRepository; + private final ClientRegistrationRepository clientRegistrationRepository; + + public HomeController(RetailCustomerRepository retailCustomerRepository, + AuthorizationRepository authorizationRepository, + ClientRegistrationRepository clientRegistrationRepository) { + this.retailCustomerRepository = retailCustomerRepository; + this.authorizationRepository = authorizationRepository; + this.clientRegistrationRepository = clientRegistrationRepository; + } + @GetMapping("/") - public String index(HttpServletRequest request) { + public String index(HttpServletRequest request, Model model) { if (request.isUserInRole(RetailCustomerEntity.ROLE_CUSTODIAN)) { return "redirect:/custodian/home"; } + if (request.isUserInRole(RetailCustomerEntity.ROLE_USER) && request.getUserPrincipal() != null) { + model.addAttribute("authorizations", authorizationsOf(request.getUserPrincipal().getName())); + } return "home"; } @GetMapping("/home") - public String home(HttpServletRequest request) { - return index(request); + public String home(HttpServletRequest request, Model model) { + return index(request, model); } @GetMapping("/TermsOfService") @@ -56,4 +79,15 @@ public String usagePolicy() { return "/UsagePolicy"; } -} \ No newline at end of file + /** The customer's Data Custodian authorizations obtained by this TP, newest first. */ + private List authorizationsOf(String username) { + return retailCustomerRepository.findByUsername(username) + .map(customer -> authorizationRepository.findAllByRetailCustomerId(customer.getId()).stream() + .filter(authorization -> authorization.getClientRegistrationId() != null) + .sorted(Comparator.comparing(AuthorizationEntity::getUpdated, + Comparator.nullsLast(Comparator.reverseOrder()))) + .map(authorization -> AuthorizationView.of(authorization, clientRegistrationRepository)) + .toList()) + .orElse(List.of()); + } +} diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/ModernAuthorizationController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/ModernAuthorizationController.java deleted file mode 100644 index 46462222..00000000 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/ModernAuthorizationController.java +++ /dev/null @@ -1,288 +0,0 @@ -/* - * - * 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.web; - -import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; -import org.greenbuttonalliance.espi.common.domain.usage.ApplicationInformationEntity; -import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; -import org.greenbuttonalliance.espi.common.domain.common.enums.GrantType; -import org.greenbuttonalliance.espi.common.domain.common.enums.TokenType; -import org.greenbuttonalliance.espi.common.domain.common.enums.OAuthError; -import org.greenbuttonalliance.espi.common.service.AuthorizationService; -import org.greenbuttonalliance.espi.common.service.RetailCustomerService; -import org.greenbuttonalliance.espi.thirdparty.repository.UsagePointRESTRepository; -import org.greenbuttonalliance.espi.thirdparty.service.WebClientService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.reactive.function.client.WebClientResponseException; -import org.springframework.web.server.ResponseStatusException; - -import jakarta.persistence.NoResultException; -import jakarta.xml.bind.JAXBException; -import java.security.Principal; -import java.time.LocalDateTime; -import java.util.Map; -import java.util.UUID; - -/** - * Modern authorization controller using WebClient and Spring Boot 3.5 patterns. - * - * Handles OAuth2 authorization code flow for Green Button third party applications. - */ -@Controller -public class ModernAuthorizationController { - - private static final Logger logger = LoggerFactory.getLogger(ModernAuthorizationController.class); - - @Autowired - private AuthorizationService authorizationService; - - @Autowired - private RetailCustomerService retailCustomerService; - - @Autowired - private UsagePointRESTRepository usagePointRESTRepository; - - @Autowired - private WebClientService webClientService; - - /** - * Handles OAuth2 authorization callback from Data Custodian. - * Modern replacement for legacy RestTemplate usage. - */ - @GetMapping("/oauth/callback") - public String authorizationCallback( - @RequestParam(required = false) String code, - @RequestParam(required = false) String state, - ModelMap model, - Principal principal, - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "error_description", required = false) String errorDescription, - @RequestParam(value = "error_uri", required = false) String errorUri) { - - try { - // Validate OAuth state parameter - AuthorizationEntity authorization = authorizationService.findByState(state); - if (authorization == null) { - logger.warn("Invalid OAuth state parameter received: {}", state); - return "redirect:/home?error=invalid_state"; - } - - ApplicationInformationEntity applicationInfo = authorization.getApplicationInformation(); - - // Handle OAuth2 error responses - if (error != null) { - logger.warn("OAuth2 authorization error: {} - {}", error, errorDescription); - handleAuthorizationError(authorization, error, errorDescription, errorUri); - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, - "Authorization failed: " + errorDescription); - } - - // Handle successful authorization with code - if (code != null) { - processAuthorizationCode(authorization, applicationInfo, code, principal); - return "redirect:/RetailCustomer/" + getCurrentCustomerId(principal) + "/AuthorizationList"; - } else { - logger.error("No authorization code received in callback"); - return "redirect:/home?error=no_code"; - } - - } catch (NoResultException | EmptyResultDataAccessException e) { - logger.warn("Invalid authorization state received: {}", state); - return "redirect:/home?error=invalid_request"; - } catch (Exception e) { - logger.error("Error processing authorization callback", e); - return "redirect:/home?error=server_error"; - } - } - - /** - * Shows authorization list for the current retail customer. - */ - @GetMapping("/authorizations") - public String authorizationList(ModelMap model, Principal principal) { - try { - Long customerId = getCurrentCustomerId(principal); - var authorizations = authorizationService.findAllByRetailCustomerId(customerId); - model.put("authorizationList", authorizations); - return "/RetailCustomer/AuthorizationList/index"; - } catch (Exception e) { - logger.error("Error loading authorization list", e); - return "redirect:/home?error=server_error"; - } - } - - /** - * Processes the authorization code by exchanging it for an access token. - * Uses modern WebClient instead of legacy RestTemplate. - */ - private void processAuthorizationCode(AuthorizationEntity authorization, - ApplicationInformationEntity applicationInfo, - String code, - Principal principal) { - try { - // Update authorization record with code - authorization.setCode(code); - authorization.setGrantType(GrantType.AUTHORIZATION_CODE); - authorization.setUpdated(LocalDateTime.now()); - authorizationService.save(authorization); - - // Create authenticated WebClient for token exchange - WebClient authenticatedClient = webClientService.createAuthenticatedClient( - applicationInfo.getClientId(), - applicationInfo.getClientSecret() - ); - - // Build token endpoint URL - String tokenUrl = String.format("%s?redirect_uri=%s&code=%s&grant_type=authorization_code", - applicationInfo.getAuthorizationServerTokenEndpoint(), - applicationInfo.getRedirectUri(), - code); - - logger.debug("Requesting access token from: {}", - applicationInfo.getAuthorizationServerTokenEndpoint()); - - // Exchange authorization code for access token using WebClient - Map tokenResponse = webClientService.getForObject( - authenticatedClient, tokenUrl, Map.class); - - if (tokenResponse != null && tokenResponse.containsKey("access_token")) { - updateAuthorizationWithToken(authorization, tokenResponse); - importInitialData(principal); - } else { - logger.error("Token exchange failed - no access token in response"); - markAuthorizationAsFailed(authorization, "no_access_token", "Token exchange failed"); - } - - } catch (WebClientResponseException e) { - logger.error("HTTP error during token exchange: {} - {}", - e.getStatusCode(), e.getResponseBodyAsString()); - markAuthorizationAsFailed(authorization, "token_exchange_error", e.getMessage()); - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Token exchange failed"); - } catch (Exception e) { - logger.error("Error processing authorization code", e); - markAuthorizationAsFailed(authorization, "processing_error", e.getMessage()); - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Processing failed"); - } - } - - /** - * Updates authorization entity with token response data. - */ - private void updateAuthorizationWithToken(AuthorizationEntity authorization, Map tokenResponse) { - authorization.setAccessToken((String) tokenResponse.get("access_token")); - authorization.setTokenType(TokenType.fromValue((String) tokenResponse.get("token_type"))); - authorization.setExpiresIn(getLongValue(tokenResponse, "expires_in")); - authorization.setRefreshToken((String) tokenResponse.get("refresh_token")); - authorization.setScope((String) tokenResponse.get("scope")); - authorization.setAuthorizationURI((String) tokenResponse.get("authorization_uri")); - authorization.setResourceURI((String) tokenResponse.get("resource_uri")); - authorization.setUpdated(LocalDateTime.now()); - authorization.setStatus("1"); // Active - authorization.setState(null); // Clear state for security - - authorizationService.save(authorization); - logger.info("Successfully updated authorization with access token"); - } - - /** - * Handles authorization errors by updating the authorization record. - */ - private void handleAuthorizationError(AuthorizationEntity authorization, - String error, - String errorDescription, - String errorUri) { - authorization.setError(error != null ? OAuthError.fromValue(error) : null); - authorization.setErrorDescription(errorDescription); - authorization.setErrorUri(errorUri); - authorization.setUpdated(LocalDateTime.now()); - authorization.setStatus("2"); // Denied - authorization.setState(null); // Clear state for security - - authorizationService.save(authorization); - } - - /** - * Marks authorization as failed with error details. - */ - private void markAuthorizationAsFailed(AuthorizationEntity authorization, String error, String description) { - authorization.setError(error != null ? OAuthError.fromValue(error) : null); - authorization.setErrorDescription(description); - authorization.setUpdated(LocalDateTime.now()); - authorization.setStatus("2"); // Failed - authorization.setState(null); - - authorizationService.save(authorization); - } - - /** - * Attempts initial data import from the authorized resource. - */ - private void importInitialData(Principal principal) { - try { - Long customerId = getCurrentCustomerId(principal); - usagePointRESTRepository.findAllByRetailCustomerId(customerId); - logger.debug("Successfully imported initial usage point data"); - } catch (JAXBException e) { - logger.info("No initial data available for import - will import later on demand"); - } catch (Exception e) { - logger.warn("Error during initial data import: {}", e.getMessage()); - } - } - - /** - * Gets the current customer ID from the authenticated principal. - */ - private Long getCurrentCustomerId(Principal principal) { - if (principal instanceof Authentication auth) { - var customer = retailCustomerService.findByUsername(auth.getName()); - if (customer != null) { - return customer.getId(); - } - } - throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Customer not found"); - } - - /** - * Safely extracts Long value from token response map. - */ - private Long getLongValue(Map map, String key) { - Object value = map.get(key); - if (value instanceof Number) { - return ((Number) value).longValue(); - } else if (value instanceof String) { - try { - return Long.parseLong((String) value); - } catch (NumberFormatException e) { - logger.warn("Invalid number format for {}: {}", key, value); - } - } - return null; - } -} \ No newline at end of file diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java index d109d91e..cc6c3e15 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java @@ -19,103 +19,67 @@ package org.greenbuttonalliance.espi.thirdparty.web; +import org.greenbuttonalliance.espi.thirdparty.oauth.DataCustodianRegistrations; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; -import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; -import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import java.util.Map; /** - * Modern OAuth2 Client Controller using Spring Security 6.x OAuth2 client features. - * - * Replaces legacy manual OAuth2 handling with Spring Security's built-in capabilities. - * Supports multiple OAuth2 client registrations for different ESPI scope requirements. + * A TP customer authorizing the Third Party at a Data Custodian (#146), with Spring Security's + * {@code oauth2Client}: the home page's cards start the authorization-code flow, and the customer + * comes back here when it has finished. */ @Controller -@RequestMapping("/oauth2") public class OAuth2ClientController { - private static final Logger logger = LoggerFactory.getLogger(OAuth2ClientController.class); + private static final Logger logger = LoggerFactory.getLogger(OAuth2ClientController.class); - /** - * Initiate OAuth2 authorization flow for monthly usage data access. - * Uses Spring Security's OAuth2 client with predefined scope configuration. - */ - @GetMapping("/authorize/monthly") - public String authorizeMonthly() { - logger.info("Initiating OAuth2 flow for monthly usage data access"); - return "redirect:/oauth2/authorization/datacustodian-monthly"; - } + private final EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService; - /** - * Initiate OAuth2 authorization flow for daily usage data access. - * Uses Spring Security's OAuth2 client with predefined scope configuration. - */ - @GetMapping("/authorize/daily") - public String authorizeDaily() { - logger.info("Initiating OAuth2 flow for daily usage data access"); - return "redirect:/oauth2/authorization/datacustodian-daily"; - } + public OAuth2ClientController(EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService) { + this.authorizedClientService = authorizedClientService; + } - /** - * Initiate OAuth2 authorization flow for admin access. - * Uses Spring Security's OAuth2 client with admin scope configuration. - */ - @GetMapping("/authorize/admin") - public String authorizeAdmin() { - logger.info("Initiating OAuth2 flow for admin access"); - return "redirect:/oauth2/authorization/datacustodian-admin"; - } + /** Monthly usage data, 1-hour intervals (the home page's "Monthly Data" card). */ + @GetMapping("/oauth2/authorize/monthly") + public String authorizeMonthly() { + return "redirect:/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY; + } - /** - * Display authorized client information after successful OAuth2 flow. - * Demonstrates how to access OAuth2 tokens and user information. - */ - @GetMapping("/client/{registrationId}") - public String clientInfo(@PathVariable String registrationId, - @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient, - @AuthenticationPrincipal OAuth2User oauth2User, - Model model) { - - logger.info("Displaying client info for registration: {}", registrationId); - - if (authorizedClient != null) { - model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName()); - model.addAttribute("userName", oauth2User.getName()); - model.addAttribute("userAttributes", oauth2User.getAttributes()); - model.addAttribute("accessToken", authorizedClient.getAccessToken().getTokenValue()); - model.addAttribute("scopes", authorizedClient.getAccessToken().getScopes()); - - // Token expiration info - if (authorizedClient.getAccessToken().getExpiresAt() != null) { - model.addAttribute("expiresAt", authorizedClient.getAccessToken().getExpiresAt().toString()); - } - - // Refresh token availability - if (authorizedClient.getRefreshToken() != null) { - model.addAttribute("hasRefreshToken", true); - } - } - - return "oauth2/client-info"; - } + /** Daily usage data, 15-minute intervals (the home page's "Daily Data" card). */ + @GetMapping("/oauth2/authorize/daily") + public String authorizeDaily() { + return "redirect:/oauth2/authorization/" + DataCustodianRegistrations.DAILY; + } - /** - * Home page after successful OAuth2 authentication. - */ - @GetMapping("/success") - public String success(@AuthenticationPrincipal OAuth2User oauth2User, Model model) { - logger.info("OAuth2 authentication successful for user: {}", oauth2User.getName()); - - model.addAttribute("userName", oauth2User.getName()); - model.addAttribute("userAttributes", oauth2User.getAttributes()); - - return "oauth2/success"; - } -} \ No newline at end of file + /** + * Where the customer lands after the Data Custodian: {@code OAuth2AuthorizationCodeGrantFilter} + * has handled the callback (exchanged the code and stored the token) and redirects here again, + * without parameters on success and with {@code ?error=...} when consent was refused or the + * exchange failed. A callback the filter did not recognise (no authorization in progress in this + * session, or a forged one) also arrives here, still carrying {@code code} and {@code state}. + * Success is reported only if a token is actually stored for this customer. + */ + @GetMapping("/login/oauth2/code/{registrationId}") + public String authorizationFinished(@PathVariable String registrationId, + @RequestParam Map parameters, + Authentication authentication) { + boolean callbackParameters = parameters.containsKey(OAuth2ParameterNames.ERROR) + || parameters.containsKey(OAuth2ParameterNames.CODE) || parameters.containsKey(OAuth2ParameterNames.STATE); + if (!callbackParameters + && authorizedClientService.loadAuthorizedClient(registrationId, authentication.getName()) != null) { + return "redirect:/?authorized"; + } + logger.info("Data Custodian authorization for {} did not complete: error={}", registrationId, + parameters.getOrDefault(OAuth2ParameterNames.ERROR, "(none, no token stored)")); + return "redirect:/?authorization_error"; + } +} diff --git a/openespi-thirdparty/src/main/resources/application.yml b/openespi-thirdparty/src/main/resources/application.yml index 79d3b0a9..70910840 100644 --- a/openespi-thirdparty/src/main/resources/application.yml +++ b/openespi-thirdparty/src/main/resources/application.yml @@ -91,47 +91,48 @@ spring: suffix: .html static-path-pattern: /** - # OAuth2 Client Configuration - ESPI Third Party + # OAuth2 Client Configuration - ESPI Third Party (#146). Spring Security's oauth2Client (not + # oauth2Login): a signed-in TP customer authorizes the TP at the Data Custodian, and the tokens are + # stored in the TP's ESPI authorizations table. ESPI scopes only: the AS issues opaque ESPI tokens, + # never OpenID Connect ones (#134), so no openid/profile and no user-info endpoint. security: oauth2: client: registration: - # Monthly usage data with 1-hour intervals + # Monthly usage data with 1-hour intervals (a customer's authorization, authorization_code) datacustodian-monthly: client-id: ${OAUTH2_CLIENT_ID:third_party} client-secret: ${OAUTH2_CLIENT_SECRET:secret} authorization-grant-type: authorization_code redirect-uri: "${espi.thirdparty.base-url}/login/oauth2/code/datacustodian-monthly" - scope: "openid,profile,FB=4_5_15;IntervalDuration=3600;BlockDuration=monthly;HistoryLength=13" + scope: "FB=4_5_15;IntervalDuration=3600;BlockDuration=monthly;HistoryLength=13" client-name: Data Custodian (Monthly) provider: datacustodian - - # Daily usage data with 15-minute intervals + + # Daily usage data with 15-minute intervals (a customer's authorization, authorization_code) datacustodian-daily: client-id: ${OAUTH2_CLIENT_ID:third_party} client-secret: ${OAUTH2_CLIENT_SECRET:secret} authorization-grant-type: authorization_code redirect-uri: "${espi.thirdparty.base-url}/login/oauth2/code/datacustodian-daily" - scope: "openid,profile,FB=4_5_15;IntervalDuration=900;BlockDuration=daily;HistoryLength=7" + scope: "FB=4_5_15;IntervalDuration=900;BlockDuration=daily;HistoryLength=7" client-name: Data Custodian (Daily) provider: datacustodian - - # Admin access for third party applications + + # The TP's ESPI client access token (client_credentials, never customer consent): the only TP + # token the Data Custodian's Authorization and Bulk APIs accept. datacustodian-admin: client-id: ${OAUTH2_CLIENT_ID:third_party} client-secret: ${OAUTH2_CLIENT_SECRET:secret} - authorization-grant-type: authorization_code - redirect-uri: "${espi.thirdparty.base-url}/login/oauth2/code/datacustodian-admin" - scope: "openid,profile,ThirdParty_Admin_Access" - client-name: Data Custodian (Admin) + authorization-grant-type: client_credentials + scope: "FB=34_35" + client-name: Data Custodian (Client Access) provider: datacustodian - + provider: datacustodian: authorization-uri: ${OAUTH2_AUTHORIZATION_URI:http://localhost:9999/oauth2/authorize} token-uri: ${OAUTH2_TOKEN_URI:http://localhost:9999/oauth2/token} - user-info-uri: ${OAUTH2_USER_INFO_URI:http://localhost:8081/DataCustodian/espi/1_1/resource/Authorization} - user-name-attribute: uuid # Server Configuration server: diff --git a/openespi-thirdparty/src/main/resources/templates/custodian/home.html b/openespi-thirdparty/src/main/resources/templates/custodian/home.html index c1b9e26e..d064ff5e 100644 --- a/openespi-thirdparty/src/main/resources/templates/custodian/home.html +++ b/openespi-thirdparty/src/main/resources/templates/custodian/home.html @@ -8,7 +8,7 @@
-
+

Third Party Administration

@@ -17,6 +17,47 @@

+ + +
+

Client Access Token

+
+ + + +

The Third Party's own token (OAuth client_credentials grant), used for the Data Custodian's ESPI + Authorization and Bulk APIs. It belongs to the Third Party, not to a customer.

+ +
+
Status
ACTIVE
+
Scope
FB=34_35
+
Obtained
-
+
Expires
-
+
Token
+
abcd1234…
+
Authorization URI
+
+
Resource URI (energy usage Bulk)
+
+
Customer Resource URI (Customer PII Bulk)
+
+
+

No client access token has been obtained yet.

+ +
+ +
+
+
diff --git a/openespi-thirdparty/src/main/resources/templates/home.html b/openespi-thirdparty/src/main/resources/templates/home.html index 8bae935b..90107385 100644 --- a/openespi-thirdparty/src/main/resources/templates/home.html +++ b/openespi-thirdparty/src/main/resources/templates/home.html @@ -8,8 +8,14 @@
- + + + @@ -45,15 +51,15 @@

Welcome to the Green Button Third Party

- -
+ +

Data Access Authorization

Authorize this application to access your energy usage data from the Data Custodian. Choose the appropriate access level based on your needs:

-
+
@@ -66,7 +72,7 @@

Monthly Data

-
+
@@ -79,19 +85,38 @@

Daily Data

-
-
-
- -

Admin Access

-

Administrative access for third party application management and configuration.

- - Authorize Admin Access - -
-
-
+ + + +

Your authorizations

+
+ + + + + + + + + + + + + + + + + + + +
AccessStatusScopeAccess token expiresData Custodian resources
Data Custodian (Monthly)ACTIVEFB=4_5_15- +
Resource:
+
Authorization:
+
Customer:
+
+
+
diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/schema/AbstractThirdPartySchemaTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/schema/AbstractThirdPartySchemaTest.java index a3161619..755e444a 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/schema/AbstractThirdPartySchemaTest.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/schema/AbstractThirdPartySchemaTest.java @@ -44,11 +44,12 @@ abstract class AbstractThirdPartySchemaTest { /** - * The openespi-common migrations: V1 and V3 shared, V2 vendor-specific, V5 shared. V4 is the Data + * The openespi-common migrations: V1 and V3 shared, V2 vendor-specific, V5 and V6 (the TP's + * authorization client registration id, #146) shared. V4 is the Data * Custodian's handoff-nonce table from openespi-handoff, which the Third Party does not use; the * gap is expected. */ - static final String[] EXPECTED_VERSIONS = {"1", "2", "3", "5"}; + static final String[] EXPECTED_VERSIONS = {"1", "2", "3", "5", "6"}; @Autowired private Flyway flyway; diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java new file mode 100644 index 00000000..a27e5234 --- /dev/null +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java @@ -0,0 +1,375 @@ +/* + * + * 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.web; + +import com.sun.net.httpserver.HttpServer; +import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; +import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; +import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; +import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.greenbuttonalliance.espi.thirdparty.oauth.DataCustodianRegistrations; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +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.mock.web.MockHttpSession; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextImpl; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.web.util.UriComponentsBuilder; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +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.redirectedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * A TP customer authorizing the Third Party at a Data Custodian with {@code oauth2Client} (#146), and + * the TP's client access token. The Authorization Server's token endpoint is a stub that answers as + * the real one does, with the REQ.21 ESPI URIs next to the token. + */ +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +class DataCustodianAuthorizationTest { + + private static final String CUSTOMER = "tp-oauth-customer"; + private static final String ADMIN = "tp-oauth-admin"; + private static final String TP_BASE = "http://localhost:8082/ThirdParty"; + private static final String CALLBACK = "/login/oauth2/code/" + DataCustodianRegistrations.MONTHLY; + private static final String RESOURCE_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Subscription/5/UsagePoint"; + private static final String AUTHORIZATION_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Authorization/7"; + private static final String CUSTOMER_RESOURCE_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Batch/RetailCustomer/3"; + // The client access token's URIs name the Bulk feeds: energy usage and Customer (PII) data (#202). + private static final String BULK_RESOURCE_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Batch/Bulk/11"; + private static final String BULK_AUTHORIZATION_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Authorization/12"; + private static final String BULK_CUSTOMER_RESOURCE_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Batch/Bulk/13"; + private static final String MONTHLY_SCOPE ="FB=4_5_15;IntervalDuration=3600;BlockDuration=monthly;HistoryLength=13"; + + private static HttpServer tokenEndpoint; + + /** The form parameters of each token request the stub received, by grant type. */ + private static final Map tokenRequests = new ConcurrentHashMap<>(); + + @BeforeAll + static void startTokenEndpoint() throws IOException { + tokenEndpoint = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + tokenEndpoint.createContext("/oauth2/token", exchange -> { + String form = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + String grantType = UriComponentsBuilder.newInstance().query(form).build().getQueryParams().getFirst("grant_type"); + tokenRequests.put(grantType, form); + String body = "client_credentials".equals(grantType) + ? "{\"access_token\":\"cc-token-1234567890\",\"token_type\":\"Bearer\",\"expires_in\":3600," + + "\"scope\":\"FB=34_35\",\"resourceURI\":\"" + BULK_RESOURCE_URI + "\"," + + "\"authorizationURI\":\"" + BULK_AUTHORIZATION_URI + "\"," + + "\"customerResourceURI\":\"" + BULK_CUSTOMER_RESOURCE_URI + "\"}" + : "{\"access_token\":\"customer-token-1234\",\"token_type\":\"Bearer\",\"expires_in\":3600," + + "\"refresh_token\":\"customer-refresh\",\"scope\":\"" + MONTHLY_SCOPE + "\"," + + "\"resourceURI\":\"" + RESOURCE_URI + "\",\"authorizationURI\":\"" + AUTHORIZATION_URI + "\"," + + "\"customerResourceURI\":\"" + CUSTOMER_RESOURCE_URI + "\"}"; + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8"); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + tokenEndpoint.start(); + } + + @AfterAll + static void stopTokenEndpoint() { + tokenEndpoint.stop(0); + } + + @DynamicPropertySource + static void tokenUri(DynamicPropertyRegistry registry) { + registry.add("spring.security.oauth2.client.provider.datacustodian.token-uri", + () -> "http://127.0.0.1:" + tokenEndpoint.getAddress().getPort() + "/oauth2/token"); + registry.add("espi.thirdparty.base-url", () -> TP_BASE); + } + + @Autowired + private MockMvc mockMvc; + + @Autowired + private RetailCustomerRepository retailCustomerRepository; + + @Autowired + private AuthorizationRepository authorizationRepository; + + @Autowired + private EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService; + + @Autowired + private ClientRegistrationRepository clientRegistrationRepository; + + @BeforeEach + void createAccounts() { + cleanUp(); + retailCustomerRepository.save(account(CUSTOMER, RetailCustomerEntity.ROLE_USER)); + retailCustomerRepository.save(account(ADMIN, RetailCustomerEntity.ROLE_CUSTODIAN)); + } + + @AfterEach + void cleanUp() { + authorizationRepository.findAll().stream() + .filter(authorization -> authorization.getClientRegistrationId() != null) + .forEach(authorizationRepository::delete); + List.of(CUSTOMER, ADMIN).forEach(name -> + retailCustomerRepository.findByUsername(name).ifPresent(retailCustomerRepository::delete)); + tokenRequests.clear(); + } + + private static RetailCustomerEntity account(String username, String role) { + RetailCustomerEntity entity = new RetailCustomerEntity(username, "Test", "Account", username + "@example.local", role); + entity.setPassword("{noop}unused"); + entity.setEnabled(Boolean.TRUE); + entity.setAccountLocked(Boolean.FALSE); + return entity; + } + + /** A session in which the TP customer is signed in with form login, as after /login. */ + private static MockHttpSession signedInSession(String username, String role) { + Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(username, null, + AuthorityUtils.createAuthorityList(role)); + MockHttpSession session = new MockHttpSession(); + session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + new SecurityContextImpl(authentication)); + return session; + } + + @Test + @DisplayName("a TP customer is sent to the AS authorize endpoint with the ESPI scope and the TP callback") + void customer_starts_authorization() throws Exception { + String location = mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY) + .session(signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER))) + .andExpect(status().is3xxRedirection()) + .andReturn().getResponse().getRedirectedUrl(); + + assertThat(UriComponentsBuilder.fromUriString(location).build()) + .satisfies(uri -> assertThat(uri.toUriString()).startsWith("http://localhost:9999/oauth2/authorize")) + .extracting(uri -> uri.getQueryParams().toSingleValueMap()) + .satisfies(params -> assertThat(params) + .containsEntry("client_id", "third_party") + .containsEntry("response_type", "code") + .containsKey("state") + // No PKCE until the AS keeps code_challenge through the DC delegation (#274) + .doesNotContainKeys("nonce", "code_challenge", "code_challenge_method")) + .satisfies(params -> assertThat(decode(params.get("redirect_uri"))).isEqualTo(TP_BASE + CALLBACK)) + .satisfies(params -> assertThat(decode(params.get("scope"))).isEqualTo(MONTHLY_SCOPE)); + } + + @Test + @DisplayName("an anonymous visitor is sent to the TP login page, not to the Data Custodian") + void anonymous_cannot_start_authorization() throws Exception { + mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY)) + .andExpect(redirectedUrl("/login")); + mockMvc.perform(get("/oauth2/authorize/monthly")) + .andExpect(redirectedUrl("/login")); + } + + @Test + @DisplayName("a TP administrator may not start a customer authorization; a client_credentials registration is no redirect") + void only_customers_start_authorization_code_flows() throws Exception { + mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY) + .session(signedInSession(ADMIN, RetailCustomerEntity.ROLE_CUSTODIAN))) + .andExpect(status().isForbidden()); + // Spring's own resolver answers 500 for a client_credentials registration. + mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.CLIENT_ACCESS) + .session(signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER))) + .andExpect(status().isNotFound()); + } + + @Test + @DisplayName("the callback stores the token and ESPI URIs for the TP customer, who stays signed in to the TP") + void callback_stores_token_and_keeps_tp_sign_in() throws Exception { + MockHttpSession session = signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER); + String state = startAuthorization(session); + + MvcResult callback = mockMvc.perform(get(TP_BASE + CALLBACK).queryParam("code", "the-code") + .queryParam("state", state).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl(TP_BASE + CALLBACK)) + .andReturn(); + + assertThat(tokenRequests.get("authorization_code")) + .contains("code=the-code", "redirect_uri=" + encode(TP_BASE + CALLBACK)) + .doesNotContain("code_verifier"); + assertThat(authorizationRepository.findFirstByClientRegistrationIdAndRetailCustomer_UsernameOrderByUpdatedDesc( + DataCustodianRegistrations.MONTHLY, CUSTOMER)) + .hasValueSatisfying(authorization -> assertThat(authorization) + .extracting(AuthorizationEntity::getAccessToken, AuthorizationEntity::getRefreshToken, + AuthorizationEntity::getScope, AuthorizationEntity::getStatus, + AuthorizationEntity::getResourceURI, AuthorizationEntity::getAuthorizationURI, + AuthorizationEntity::getCustomerResourceURI, AuthorizationEntity::getThirdParty) + .containsExactly("customer-token-1234", "customer-refresh", MONTHLY_SCOPE, + AuthorizationEntity.STATUS_ACTIVE, RESOURCE_URI, AUTHORIZATION_URI, + CUSTOMER_RESOURCE_URI, "third_party")); + + // Still the TP customer (ROLE_USER, form login), not a Data Custodian principal. + assertThat(((SecurityContext) callback.getRequest().getSession() + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).getAuthentication()) + .satisfies(authentication -> assertThat(authentication.getName()).isEqualTo(CUSTOMER)) + .satisfies(authentication -> assertThat(AuthorityUtils.authorityListToSet(authentication.getAuthorities())) + .containsExactly(RetailCustomerEntity.ROLE_USER)); + + mockMvc.perform(get(TP_BASE + CALLBACK).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl("/ThirdParty/?authorized")); + assertThat(mockMvc.perform(get("/").param("authorized", "").session(session)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()) + .contains("The Data Custodian authorized this Third Party", "Your authorizations", + "Data Custodian (Monthly)", RESOURCE_URI, AUTHORIZATION_URI, CUSTOMER_RESOURCE_URI) + .doesNotContain("customer-token-1234", "customer-refresh"); + } + + @Test + @DisplayName("consent refused at the Data Custodian: nothing is stored and the customer gets the home page's message") + void refused_consent_stores_nothing() throws Exception { + MockHttpSession session = signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER); + String state = startAuthorization(session); + + String location = mockMvc.perform(get(TP_BASE + CALLBACK).queryParam("error", "access_denied") + .queryParam("state", state).contextPath("/ThirdParty").session(session)) + .andExpect(status().is3xxRedirection()) + .andReturn().getResponse().getRedirectedUrl(); + assertThat(location).startsWith(TP_BASE + CALLBACK + "?error=access_denied"); + + mockMvc.perform(get(location).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl("/ThirdParty/?authorization_error")); + assertThat(tokenRequests).isEmpty(); + assertThat(authorizedClientService.findAuthorization(DataCustodianRegistrations.MONTHLY, CUSTOMER)).isEmpty(); + } + + @Test + @DisplayName("a callback with no authorization in progress in this session is not accepted") + void forged_callback_is_rejected() throws Exception { + mockMvc.perform(get(TP_BASE + CALLBACK + "?code=stolen&state=guessed").contextPath("/ThirdParty") + .session(signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER))) + .andExpect(redirectedUrl("/ThirdParty/?authorization_error")); + assertThat(tokenRequests).isEmpty(); + } + + @Test + @DisplayName("a refreshed token keeps the ESPI URIs when the refresh response does not repeat them") + void refresh_keeps_espi_uris() throws Exception { + MockHttpSession session = signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER); + mockMvc.perform(get(TP_BASE + CALLBACK).queryParam("code", "the-code") + .queryParam("state", startAuthorization(session)).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl(TP_BASE + CALLBACK)); + + OAuth2AccessToken refreshed = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "refreshed-token", + Instant.now(), Instant.now().plusSeconds(3600), Set.of(MONTHLY_SCOPE)); + authorizedClientService.saveAuthorizedClient(new OAuth2AuthorizedClient( + clientRegistrationRepository.findByRegistrationId(DataCustodianRegistrations.MONTHLY), CUSTOMER, + refreshed, null), + UsernamePasswordAuthenticationToken.authenticated(CUSTOMER, null, + AuthorityUtils.createAuthorityList(RetailCustomerEntity.ROLE_USER))); + + assertThat(authorizedClientService.findAuthorization(DataCustodianRegistrations.MONTHLY, CUSTOMER)) + .hasValueSatisfying(authorization -> assertThat(authorization) + .extracting(AuthorizationEntity::getAccessToken, AuthorizationEntity::getResourceURI, + AuthorizationEntity::getAuthorizationURI) + .containsExactly("refreshed-token", RESOURCE_URI, AUTHORIZATION_URI)); + assertThat(authorizationRepository.findAllByRetailCustomerId( + retailCustomerRepository.findByUsername(CUSTOMER).orElseThrow().getId())).hasSize(1); + } + + @Test + @DisplayName("the TP administrator obtains the client access token (client_credentials) and its Bulk URIs; it belongs to no customer") + void admin_obtains_client_access_token() throws Exception { + MockHttpSession session = signedInSession(ADMIN, RetailCustomerEntity.ROLE_CUSTODIAN); + mockMvc.perform(post("/custodian/home/client-token").with(csrf()).session(session)) + .andExpect(redirectedUrl("/custodian/home?client_token")); + + assertThat(tokenRequests.get("client_credentials")).contains("scope=FB%3D34_35"); + assertThat(authorizationRepository.findFirstByClientRegistrationIdAndRetailCustomerIsNullOrderByUpdatedDesc( + DataCustodianRegistrations.CLIENT_ACCESS)) + .hasValueSatisfying(authorization -> assertThat(authorization) + .extracting(AuthorizationEntity::getAccessToken, AuthorizationEntity::getScope, + AuthorizationEntity::getRetailCustomer, AuthorizationEntity::getStatus, + AuthorizationEntity::getResourceURI, AuthorizationEntity::getAuthorizationURI, + AuthorizationEntity::getCustomerResourceURI) + .containsExactly("cc-token-1234567890", "FB=34_35", null, AuthorizationEntity.STATUS_ACTIVE, + BULK_RESOURCE_URI, BULK_AUTHORIZATION_URI, BULK_CUSTOMER_RESOURCE_URI)); + + assertThat(mockMvc.perform(get("/custodian/home").param("client_token", "").session(session)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString()) + .contains("A new client access token was obtained", "FB=34_35", "cc-token…", + BULK_RESOURCE_URI, BULK_AUTHORIZATION_URI, BULK_CUSTOMER_RESOURCE_URI) + .doesNotContain("cc-token-1234567890"); + } + + @Test + @DisplayName("a TP customer may not obtain the client access token") + void customer_cannot_obtain_client_access_token() throws Exception { + mockMvc.perform(post("/custodian/home/client-token").with(csrf()).with(user(CUSTOMER).roles("USER"))) + .andExpect(status().isForbidden()); + assertThat(tokenRequests).isEmpty(); + } + + /** Starts the monthly authorization in this session and returns the state the TP sent to the AS. */ + private String startAuthorization(MockHttpSession session) throws Exception { + String location = mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY) + .session(session)) + .andExpect(status().is3xxRedirection()) + .andReturn().getResponse().getRedirectedUrl(); + // Spring's state ends in Base64 '=' padding, which arrives URL-encoded: decode it, and send it + // back with queryParam (which encodes it once). + return decode(UriComponentsBuilder.fromUriString(location).build().getQueryParams().getFirst("state")); + } + + private static String decode(String value) { + return java.net.URLDecoder.decode(value, StandardCharsets.UTF_8); + } + + private static String encode(String value) { + return java.net.URLEncoder.encode(value, StandardCharsets.UTF_8); + } +} 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 53dabe34..76d80f86 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 @@ -244,7 +244,8 @@ void wrong_password_is_checked_once() throws Exception { @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). + // No authorization in progress in this session, so the grant filter passes the callback on and + // OAuth2ClientController reports it as not completed. mockMvc.perform(get("/login/oauth2/code/datacustodian").with(user(CUSTOMER).roles("USER")) .param("error", "access_denied").param("state", "unknown")) .andExpect(redirectedUrl("/?authorization_error")); diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java index a3368179..c9d1d3be 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java @@ -19,47 +19,66 @@ package org.greenbuttonalliance.espi.thirdparty.web; +import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; +import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.ui.ExtendedModelMap; + +import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class HomeControllerTests { - private final HomeController controller = new HomeController(); + private final RetailCustomerRepository retailCustomerRepository = mock(RetailCustomerRepository.class); + + private final HomeController controller = new HomeController(retailCustomerRepository, + mock(AuthorizationRepository.class), mock(ClientRegistrationRepository.class)); private MockHttpServletRequest request; + private ExtendedModelMap model; + @BeforeEach void setup() { request = new MockHttpServletRequest(); + model = new ExtendedModelMap(); } @Test void index_whenCustodian_redirectsToCustodianHome() { request.addUserRole("ROLE_CUSTODIAN"); - assertThat(controller.index(request)).isEqualTo("redirect:/custodian/home"); + assertThat(controller.index(request, model)).isEqualTo("redirect:/custodian/home"); } @Test void index_whenCustomer_displaysHomeViewWithTheAuthorizationCards() { request.addUserRole("ROLE_USER"); + request.setUserPrincipal(new TestingAuthenticationToken("customer", null, "ROLE_USER")); + when(retailCustomerRepository.findByUsername("customer")).thenReturn(Optional.empty()); - assertThat(controller.index(request)).isEqualTo("home"); + assertThat(controller.index(request, model)).isEqualTo("home"); + assertThat(model).containsKey("authorizations"); } @Test void index_whenAnonymous_displaysHomeView() { - assertThat(controller.index(request)).isEqualTo("home"); + assertThat(controller.index(request, model)).isEqualTo("home"); + assertThat(model).doesNotContainKey("authorizations"); } @Test void home_delegatesToIndex() { request.addUserRole("ROLE_CUSTODIAN"); - assertThat(controller.home(request)).isEqualTo("redirect:/custodian/home"); + assertThat(controller.home(request, model)).isEqualTo("redirect:/custodian/home"); } @Test diff --git a/openespi-thirdparty/src/test/resources/application-test.yml b/openespi-thirdparty/src/test/resources/application-test.yml index 5ce2b738..38fb1a7a 100644 --- a/openespi-thirdparty/src/test/resources/application-test.yml +++ b/openespi-thirdparty/src/test/resources/application-test.yml @@ -32,12 +32,11 @@ spring: client-secret: test-secret authorization-grant-type: authorization_code redirect-uri: "http://localhost:8082/ThirdParty/login/oauth2/code/datacustodian" - scope: "openid,profile,FB=4_5_15" + scope: "FB=4_5_15" provider: datacustodian: authorization-uri: http://localhost:9999/oauth2/authorize token-uri: http://localhost:9999/oauth2/token - user-info-uri: http://localhost:8081/DataCustodian/espi/1_1/resource/Authorization logging: level: From 17cbb15cf961f266fed5d1ccc320d49834539091 Mon Sep 17 00:00:00 2001 From: "Donald F. Coffin" Date: Tue, 17 Nov 2026 15:32:44 -0500 Subject: [PATCH 2/3] fix(thirdparty): address the #275 review of the oauth2Client token store (#146) - Obtaining a new client access token no longer revokes the current one first: the new token is requested directly and replaces the stored one only once issued and saved. A refusal, an unreachable AS or a persistence error (DataAccessException) shows client_token_error and keeps the token in use. - Authorization rows get a deterministic UUID5 id from the registration and customer (EspiIdGeneratorService.generateEntityId) instead of a random v4 id, so racing saves cannot insert a duplicate row. - The callback page reports success only for authorization_code registrations; the TP's client access token never counts as a customer's authorization. - The ESPI token-response URIs are handed to the store through an in-memory map keyed by access token (entries expire after 5 minutes) instead of request attributes, so a token refreshed outside a web request keeps them. - The home page loads the customer's authorizations with one derived query. - Removed the unreachable "session ended" message from home.html; the test now checks that a callback after the session ended requires sign-in. Co-Authored-By: Claude Opus 5.5 --- .../usage/AuthorizationRepository.java | 4 ++ ...rizationOAuth2AuthorizedClientService.java | 17 ++++- .../oauth/EspiTokenResponseParameters.java | 46 +++++++------ .../web/CustodianHomeController.java | 46 +++++++------ .../espi/thirdparty/web/HomeController.java | 21 ++---- .../web/OAuth2ClientController.java | 16 ++++- .../src/main/resources/templates/home.html | 10 +-- .../EspiTokenResponseParametersTest.java | 69 +++++++++++++++++++ .../web/DataCustodianAuthorizationTest.java | 48 ++++++++++++- .../espi/thirdparty/web/FormLoginTest.java | 13 ++-- .../thirdparty/web/HomeControllerTests.java | 13 ++-- 11 files changed, 216 insertions(+), 87 deletions(-) create mode 100644 openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java diff --git a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java index f05d24fa..28028d41 100755 --- a/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java +++ b/openespi-common/src/main/java/org/greenbuttonalliance/espi/common/repositories/usage/AuthorizationRepository.java @@ -63,6 +63,10 @@ Optional findFirstByClientRegistrationIdAndRetailCustomer_U Optional findFirstByClientRegistrationIdAndRetailCustomerIsNullOrderByUpdatedDesc( String clientRegistrationId); + /** Third Party token store (#146): every Authorization a TP customer obtained, newest first. */ + List findAllByRetailCustomer_UsernameAndClientRegistrationIdIsNotNullOrderByUpdatedDesc( + String username); + /** Back-channel idempotency lookup (#202): the Authorization provisioned for an AS grant. */ Optional findByCorrelationId(String correlationId); diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java index ddd90db9..476d4b3c 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java @@ -25,6 +25,7 @@ import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.greenbuttonalliance.espi.common.service.EspiIdGeneratorService; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; @@ -65,9 +66,12 @@ */ public class EspiAuthorizationOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService { + private static final String AUTHORIZATION_ENTITY_TYPE = "ThirdPartyAuthorization"; + private final ClientRegistrationRepository clientRegistrationRepository; private final AuthorizationRepository authorizationRepository; private final RetailCustomerRepository retailCustomerRepository; + private final EspiIdGeneratorService idGenerator = new EspiIdGeneratorService(); public EspiAuthorizationOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository, AuthorizationRepository authorizationRepository, @@ -157,12 +161,23 @@ private AuthorizationEntity newAuthorization(ClientRegistration registration, St "Only a Third Party customer can authorize " + registration.getRegistrationId())); } AuthorizationEntity authorization = new AuthorizationEntity(customer, null, null); - authorization.setId(UUID.randomUUID()); + authorization.setId(authorizationId(registration, principalName)); authorization.setThirdParty(registration.getClientId()); authorization.setClientRegistrationId(registration.getRegistrationId()); return authorization; } + /** + * The row's id: a UUID5 of the registration and, for authorization_code, the customer. Each pair + * has exactly one row, so two saves racing to create it cannot both insert one: the second fails + * on the primary key instead of adding a duplicate. + */ + UUID authorizationId(ClientRegistration registration, String principalName) { + String naturalKey = isClientCredentials(registration) ? registration.getRegistrationId() + : registration.getRegistrationId() + ":" + principalName; + return idGenerator.generateEntityId(AUTHORIZATION_ENTITY_TYPE, naturalKey); + } + private static OAuth2AuthorizedClient toAuthorizedClient(ClientRegistration registration, String principalName, AuthorizationEntity authorization) { Instant expiresAt = authorization.getExpiresIn() == null ? null : Instant.ofEpochMilli(authorization.getExpiresIn()); diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java index 37c148e5..338c3308 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java @@ -22,11 +22,11 @@ import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest; import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; - +import java.time.Duration; +import java.time.Instant; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; /** * Keeps the ESPI URIs of a token response until the token is stored (#146). @@ -35,12 +35,13 @@ * {@code customerResourceURI} in the token response, next to the access token. Spring Security parses * them into {@link OAuth2AccessTokenResponse#getAdditionalParameters()}, but the * {@code OAuth2AuthorizedClient} it then stores holds only the tokens, so they would be lost. The - * {@link #capturing capturing} token-response client keeps them as a request attribute, keyed by the - * access token, and {@link EspiAuthorizationOAuth2AuthorizedClientService} takes them when it stores - * that token in the same request.

+ * {@link #capturing capturing} token-response client keeps them in memory, keyed by the access token, + * and {@link EspiAuthorizationOAuth2AuthorizedClientService} takes them when it stores that token.

* - *

Outside a request (no {@link RequestContextHolder} attributes) nothing is kept; the stored - * Authorization then keeps the URIs it already has.

+ *

The hand-over does not depend on a servlet request, so a token obtained or refreshed on another + * thread (a {@code WebClient} call, a scheduled import) keeps its URIs too. Spring stores the token + * right after the response in the same call, so an entry normally lives for milliseconds; one that is + * never taken (the store failed) is dropped after {@link #RETENTION}.

*/ public final class EspiTokenResponseParameters { @@ -49,7 +50,14 @@ public final class EspiTokenResponseParameters { public static final String AUTHORIZATION_URI = "authorizationURI"; public static final String CUSTOMER_RESOURCE_URI = "customerResourceURI"; - private static final String ATTRIBUTE_PREFIX = EspiTokenResponseParameters.class.getName() + "."; + /** How long the URIs of a token response wait to be taken before they are dropped. */ + static final Duration RETENTION = Duration.ofMinutes(5); + + private record Pending(EspiUris uris, Instant received) { + } + + /** Token responses whose token has not been stored yet, by access token value. */ + private static final Map PENDING = new ConcurrentHashMap<>(); /** The ESPI URIs of one token response; any of them may be {@code null}. */ public record EspiUris(String resourceUri, String authorizationUri, String customerResourceUri) { @@ -73,24 +81,18 @@ public static OAuth2AccessTo OAuth2AccessTokenResponseClient delegate) { return grantRequest -> { OAuth2AccessTokenResponse response = delegate.getTokenResponse(grantRequest); - RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); - if (attributes != null && response != null) { - attributes.setAttribute(ATTRIBUTE_PREFIX + response.getAccessToken().getTokenValue(), - EspiUris.from(response.getAdditionalParameters()), RequestAttributes.SCOPE_REQUEST); + if (response != null) { + Instant now = Instant.now(); + PENDING.values().removeIf(pending -> pending.received().isBefore(now.minus(RETENTION))); + PENDING.put(response.getAccessToken().getTokenValue(), + new Pending(EspiUris.from(response.getAdditionalParameters()), now)); } return response; }; } - /** The ESPI URIs that came with this access token in the current request, removed once taken. */ + /** The ESPI URIs that came with this access token, removed once taken. */ static Optional take(String accessTokenValue) { - RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); - if (attributes == null) { - return Optional.empty(); - } - String name = ATTRIBUTE_PREFIX + accessTokenValue; - Object uris = attributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST); - attributes.removeAttribute(name, RequestAttributes.SCOPE_REQUEST); - return uris instanceof EspiUris espiUris ? Optional.of(espiUris) : Optional.empty(); + return Optional.ofNullable(PENDING.remove(accessTokenValue)).map(Pending::uris); } } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java index 03825f47..72060f25 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java @@ -19,23 +19,26 @@ package org.greenbuttonalliance.espi.thirdparty.web; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import org.greenbuttonalliance.espi.thirdparty.oauth.DataCustodianRegistrations; import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest; -import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest; +import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.client.RestClientException; /** * The Third Party administrator's landing page after login (#249), with a check of the TP's ESPI @@ -50,14 +53,15 @@ public class CustodianHomeController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(CustodianHomeController.class); - private final OAuth2AuthorizedClientManager authorizedClientManager; + private final OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient; private final EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService; private final ClientRegistrationRepository clientRegistrationRepository; - public CustodianHomeController(OAuth2AuthorizedClientManager authorizedClientManager, - EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService, - ClientRegistrationRepository clientRegistrationRepository) { - this.authorizedClientManager = authorizedClientManager; + public CustodianHomeController( + OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient, + EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService, + ClientRegistrationRepository clientRegistrationRepository) { + this.clientCredentialsTokenResponseClient = clientCredentialsTokenResponseClient; this.authorizedClientService = authorizedClientService; this.clientRegistrationRepository = clientRegistrationRepository; } @@ -71,22 +75,22 @@ public String index(Authentication authentication, Model model) { } /** - * Obtains a new client access token: any stored one is revoked first, so this always asks the - * Authorization Server rather than returning the token already held. + * Obtains a new client access token from the Authorization Server, even while a valid one is + * stored, and replaces the stored one only once the new one has been issued and saved. If the AS + * is unreachable or refuses, or the save fails, the token already held stays in use. */ @PostMapping("/client-token") - public String obtainClientToken(Authentication authentication, HttpServletRequest request, - HttpServletResponse response) { - authorizedClientService.removeAuthorizedClient(DataCustodianRegistrations.CLIENT_ACCESS, authentication.getName()); + public String obtainClientToken(Authentication authentication) { + ClientRegistration registration = clientRegistrationRepository + .findByRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS); try { - authorizedClientManager.authorize(OAuth2AuthorizeRequest - .withClientRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS) - .principal(authentication) - .attribute(HttpServletRequest.class.getName(), request) - .attribute(HttpServletResponse.class.getName(), response) - .build()); + OAuth2AccessTokenResponse tokenResponse = clientCredentialsTokenResponseClient + .getTokenResponse(new OAuth2ClientCredentialsGrantRequest(registration)); + authorizedClientService.saveAuthorizedClient(new OAuth2AuthorizedClient(registration, + authentication.getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()), + authentication); return "redirect:/custodian/home?client_token"; - } catch (OAuth2AuthorizationException | IllegalStateException ex) { + } catch (OAuth2AuthorizationException | RestClientException | DataAccessException ex) { logger.warn("Could not obtain the TP client access token: {}", ex.getMessage()); return "redirect:/custodian/home?client_token_error"; } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java index 32626072..e672cf4d 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/HomeController.java @@ -20,17 +20,13 @@ package org.greenbuttonalliance.espi.thirdparty.web; import jakarta.servlet.http.HttpServletRequest; -import org.greenbuttonalliance.espi.common.domain.usage.AuthorizationEntity; import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; -import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; -import java.time.LocalDateTime; -import java.util.Comparator; import java.util.List; /** @@ -41,14 +37,11 @@ @Controller public class HomeController { - private final RetailCustomerRepository retailCustomerRepository; private final AuthorizationRepository authorizationRepository; private final ClientRegistrationRepository clientRegistrationRepository; - public HomeController(RetailCustomerRepository retailCustomerRepository, - AuthorizationRepository authorizationRepository, + public HomeController(AuthorizationRepository authorizationRepository, ClientRegistrationRepository clientRegistrationRepository) { - this.retailCustomerRepository = retailCustomerRepository; this.authorizationRepository = authorizationRepository; this.clientRegistrationRepository = clientRegistrationRepository; } @@ -81,13 +74,9 @@ public String usagePolicy() { /** The customer's Data Custodian authorizations obtained by this TP, newest first. */ private List authorizationsOf(String username) { - return retailCustomerRepository.findByUsername(username) - .map(customer -> authorizationRepository.findAllByRetailCustomerId(customer.getId()).stream() - .filter(authorization -> authorization.getClientRegistrationId() != null) - .sorted(Comparator.comparing(AuthorizationEntity::getUpdated, - Comparator.nullsLast(Comparator.reverseOrder()))) - .map(authorization -> AuthorizationView.of(authorization, clientRegistrationRepository)) - .toList()) - .orElse(List.of()); + return authorizationRepository + .findAllByRetailCustomer_UsernameAndClientRegistrationIdIsNotNullOrderByUpdatedDesc(username).stream() + .map(authorization -> AuthorizationView.of(authorization, clientRegistrationRepository)) + .toList(); } } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java index cc6c3e15..f93aff75 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/OAuth2ClientController.java @@ -24,6 +24,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @@ -43,9 +46,12 @@ public class OAuth2ClientController { private static final Logger logger = LoggerFactory.getLogger(OAuth2ClientController.class); private final EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService; + private final ClientRegistrationRepository clientRegistrationRepository; - public OAuth2ClientController(EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService) { + public OAuth2ClientController(EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService, + ClientRegistrationRepository clientRegistrationRepository) { this.authorizedClientService = authorizedClientService; + this.clientRegistrationRepository = clientRegistrationRepository; } /** Monthly usage data, 1-hour intervals (the home page's "Monthly Data" card). */ @@ -66,7 +72,8 @@ public String authorizeDaily() { * without parameters on success and with {@code ?error=...} when consent was refused or the * exchange failed. A callback the filter did not recognise (no authorization in progress in this * session, or a forged one) also arrives here, still carrying {@code code} and {@code state}. - * Success is reported only if a token is actually stored for this customer. + * Success is reported only for a customer (authorization_code) registration and only if a token is + * actually stored for this customer; the TP's own client access token never counts. */ @GetMapping("/login/oauth2/code/{registrationId}") public String authorizationFinished(@PathVariable String registrationId, @@ -74,7 +81,10 @@ public String authorizationFinished(@PathVariable String registrationId, Authentication authentication) { boolean callbackParameters = parameters.containsKey(OAuth2ParameterNames.ERROR) || parameters.containsKey(OAuth2ParameterNames.CODE) || parameters.containsKey(OAuth2ParameterNames.STATE); - if (!callbackParameters + ClientRegistration registration = clientRegistrationRepository.findByRegistrationId(registrationId); + boolean customerRegistration = registration != null + && AuthorizationGrantType.AUTHORIZATION_CODE.equals(registration.getAuthorizationGrantType()); + if (customerRegistration && !callbackParameters && authorizedClientService.loadAuthorizedClient(registrationId, authentication.getName()) != null) { return "redirect:/?authorized"; } diff --git a/openespi-thirdparty/src/main/resources/templates/home.html b/openespi-thirdparty/src/main/resources/templates/home.html index 90107385..e35e26e9 100644 --- a/openespi-thirdparty/src/main/resources/templates/home.html +++ b/openespi-thirdparty/src/main/resources/templates/home.html @@ -15,19 +15,13 @@ + failed, or no authorization was in progress in this session (e.g. the TP session ended during the + round trip; the callback requires sign-in, so the customer signs in again first). --> - diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java new file mode 100644 index 00000000..7e598f1d --- /dev/null +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java @@ -0,0 +1,69 @@ +/* + * + * 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.oauth; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest; +import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.web.context.request.RequestContextHolder; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import static org.assertj.core.api.Assertions.assertThat; + +class EspiTokenResponseParametersTest { + + private static final String RESOURCE_URI = "https://dc.example/espi/1_1/resource/Batch/Subscription/1"; + private static final String AUTHORIZATION_URI = "https://dc.example/espi/1_1/resource/Authorization/2"; + + private static OAuth2AccessTokenResponseClient capturing(String tokenValue) { + return EspiTokenResponseParameters.capturing(grantRequest -> OAuth2AccessTokenResponse.withToken(tokenValue) + .tokenType(OAuth2AccessToken.TokenType.BEARER) + .expiresIn(3600) + .additionalParameters(Map.of(EspiTokenResponseParameters.RESOURCE_URI, RESOURCE_URI, + EspiTokenResponseParameters.AUTHORIZATION_URI, AUTHORIZATION_URI)) + .build()); + } + + @Test + @DisplayName("a token refreshed outside a web request (another thread) keeps its ESPI URIs for storage") + void hand_over_works_without_a_request() throws Exception { + CompletableFuture.runAsync(() -> { + assertThat(RequestContextHolder.getRequestAttributes()).isNull(); + capturing("off-request-token").getTokenResponse(null); + }).get(); + + assertThat(EspiTokenResponseParameters.take("off-request-token")) + .hasValue(new EspiTokenResponseParameters.EspiUris(RESOURCE_URI, AUTHORIZATION_URI, null)); + } + + @Test + @DisplayName("the URIs are handed over once: a second take finds nothing") + void uris_are_taken_once() { + capturing("once-token").getTokenResponse(null); + + assertThat(EspiTokenResponseParameters.take("once-token")).isPresent(); + assertThat(EspiTokenResponseParameters.take("once-token")).isEmpty(); + } +} diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java index a27e5234..bf19b63c 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java @@ -98,6 +98,9 @@ class DataCustodianAuthorizationTest { /** The form parameters of each token request the stub received, by grant type. */ private static final Map tokenRequests = new ConcurrentHashMap<>(); + /** When set, the stub token endpoint answers 401 invalid_client, as an AS that refuses the TP. */ + private static volatile boolean tokenEndpointRefuses; + @BeforeAll static void startTokenEndpoint() throws IOException { tokenEndpoint = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); @@ -105,6 +108,15 @@ static void startTokenEndpoint() throws IOException { String form = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); String grantType = UriComponentsBuilder.newInstance().query(form).build().getQueryParams().getFirst("grant_type"); tokenRequests.put(grantType, form); + if (tokenEndpointRefuses) { + byte[] error = "{\"error\":\"invalid_client\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json;charset=UTF-8"); + exchange.sendResponseHeaders(401, error.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(error); + } + return; + } String body = "client_credentials".equals(grantType) ? "{\"access_token\":\"cc-token-1234567890\",\"token_type\":\"Bearer\",\"expires_in\":3600," + "\"scope\":\"FB=34_35\",\"resourceURI\":\"" + BULK_RESOURCE_URI + "\"," @@ -166,6 +178,7 @@ void cleanUp() { List.of(CUSTOMER, ADMIN).forEach(name -> retailCustomerRepository.findByUsername(name).ifPresent(retailCustomerRepository::delete)); tokenRequests.clear(); + tokenEndpointRefuses = false; } private static RetailCustomerEntity account(String username, String role) { @@ -248,10 +261,11 @@ void callback_stores_token_and_keeps_tp_sign_in() throws Exception { .extracting(AuthorizationEntity::getAccessToken, AuthorizationEntity::getRefreshToken, AuthorizationEntity::getScope, AuthorizationEntity::getStatus, AuthorizationEntity::getResourceURI, AuthorizationEntity::getAuthorizationURI, - AuthorizationEntity::getCustomerResourceURI, AuthorizationEntity::getThirdParty) + AuthorizationEntity::getCustomerResourceURI, AuthorizationEntity::getThirdParty, + stored -> stored.getId().version()) .containsExactly("customer-token-1234", "customer-refresh", MONTHLY_SCOPE, AuthorizationEntity.STATUS_ACTIVE, RESOURCE_URI, AUTHORIZATION_URI, - CUSTOMER_RESOURCE_URI, "third_party")); + CUSTOMER_RESOURCE_URI, "third_party", 5)); // Still the TP customer (ROLE_USER, form login), not a Data Custodian principal. assertThat(((SecurityContext) callback.getRequest().getSession() @@ -346,6 +360,36 @@ void admin_obtains_client_access_token() throws Exception { .doesNotContain("cc-token-1234567890"); } + @Test + @DisplayName("when the AS refuses a new client access token, the one already held stays in use") + void refused_client_token_keeps_the_current_one() throws Exception { + MockHttpSession session = signedInSession(ADMIN, RetailCustomerEntity.ROLE_CUSTODIAN); + mockMvc.perform(post("/custodian/home/client-token").with(csrf()).session(session)) + .andExpect(redirectedUrl("/custodian/home?client_token")); + + tokenEndpointRefuses = true; + mockMvc.perform(post("/custodian/home/client-token").with(csrf()).session(session)) + .andExpect(redirectedUrl("/custodian/home?client_token_error")); + + assertThat(authorizedClientService.loadAuthorizedClient( + DataCustodianRegistrations.CLIENT_ACCESS, ADMIN)) + .isNotNull() + .extracting(client -> client.getAccessToken().getTokenValue()) + .isEqualTo("cc-token-1234567890"); + } + + @Test + @DisplayName("the TP's client access token never counts as a customer's authorization on the callback page") + void callback_page_ignores_the_client_access_token() throws Exception { + mockMvc.perform(post("/custodian/home/client-token").with(csrf()) + .session(signedInSession(ADMIN, RetailCustomerEntity.ROLE_CUSTODIAN))) + .andExpect(redirectedUrl("/custodian/home?client_token")); + + mockMvc.perform(get("/login/oauth2/code/" + DataCustodianRegistrations.CLIENT_ACCESS) + .session(signedInSession(CUSTOMER, RetailCustomerEntity.ROLE_USER))) + .andExpect(redirectedUrl("/?authorization_error")); + } + @Test @DisplayName("a TP customer may not obtain the client access token") void customer_cannot_obtain_client_access_token() throws Exception { 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 76d80f86..9223b8b1 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 @@ -253,17 +253,14 @@ 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", "you can try again below") - .doesNotContain("Invalid username or password", "Your Third Party session ended"); + .doesNotContain("Invalid username or password"); } @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"); + @DisplayName("a DC callback after the TP session ended asks the customer to sign in first") + void dc_callback_after_session_ended_requires_sign_in() throws Exception { + mockMvc.perform(get("/login/oauth2/code/datacustodian-monthly").param("code", "a-code").param("state", "a-state")) + .andExpect(redirectedUrl("/login")); } @Test diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java index c9d1d3be..d4a657bf 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/HomeControllerTests.java @@ -20,7 +20,6 @@ package org.greenbuttonalliance.espi.thirdparty.web; import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; -import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; @@ -28,7 +27,7 @@ import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.ui.ExtendedModelMap; -import java.util.Optional; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -36,10 +35,10 @@ class HomeControllerTests { - private final RetailCustomerRepository retailCustomerRepository = mock(RetailCustomerRepository.class); + private final AuthorizationRepository authorizationRepository = mock(AuthorizationRepository.class); - private final HomeController controller = new HomeController(retailCustomerRepository, - mock(AuthorizationRepository.class), mock(ClientRegistrationRepository.class)); + private final HomeController controller = new HomeController(authorizationRepository, + mock(ClientRegistrationRepository.class)); private MockHttpServletRequest request; @@ -62,7 +61,9 @@ void index_whenCustodian_redirectsToCustodianHome() { void index_whenCustomer_displaysHomeViewWithTheAuthorizationCards() { request.addUserRole("ROLE_USER"); request.setUserPrincipal(new TestingAuthenticationToken("customer", null, "ROLE_USER")); - when(retailCustomerRepository.findByUsername("customer")).thenReturn(Optional.empty()); + when(authorizationRepository + .findAllByRetailCustomer_UsernameAndClientRegistrationIdIsNotNullOrderByUpdatedDesc("customer")) + .thenReturn(List.of()); assertThat(controller.index(request, model)).isEqualTo("home"); assertThat(model).containsKey("authorizations"); From 3067f5ced4ab7660715dc930d9426a9a880aab37 Mon Sep 17 00:00:00 2001 From: "Donald F. Coffin" Date: Tue, 17 Nov 2026 16:11:12 -0500 Subject: [PATCH 3/3] fix(thirdparty): address the second #275 review of the oauth2Client flow (#146) - A visitor who starts a Data Custodian authorization signed out no longer consents twice: starting an authorization clears the request saved before sign-in, which OAuth2AuthorizationCodeGrantFilter would otherwise redirect to after the code exchange instead of the callback. - Obtaining a client access token shows client_token_error for a missing datacustodian-admin registration and for any failure while obtaining or saving the token; the token already held stays in use. - EspiTokenResponseParameters is a Spring bean shared by the token-response clients and the token store instead of static state; entries never taken expire on both put and take. - The token store gets EspiIdGeneratorService injected, and the expiry is read with AuthorizationEntity.getExpirationInstant() in both places. Co-Authored-By: Claude Opus 5.5 --- .../config/SecurityConfiguration.java | 28 +++++-- ...rizationOAuth2AuthorizedClientService.java | 13 ++- .../oauth/EspiTokenResponseParameters.java | 54 +++++++++---- ...pCustomerAuthorizationRequestResolver.java | 14 +++- .../thirdparty/web/AuthorizationView.java | 4 +- .../web/CustodianHomeController.java | 14 ++-- .../EspiTokenResponseParametersTest.java | 51 ++++++++++-- ...ustodianHomeControllerClientTokenTest.java | 79 +++++++++++++++++++ .../web/DataCustodianAuthorizationTest.java | 25 ++++++ 9 files changed, 241 insertions(+), 41 deletions(-) create mode 100644 openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeControllerClientTokenTest.java 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 fae22b16..3b961e21 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 @@ -22,6 +22,7 @@ import org.greenbuttonalliance.espi.common.domain.usage.RetailCustomerEntity; import org.greenbuttonalliance.espi.common.repositories.usage.AuthorizationRepository; import org.greenbuttonalliance.espi.common.repositories.usage.RetailCustomerRepository; +import org.greenbuttonalliance.espi.common.service.EspiIdGeneratorService; import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; import org.greenbuttonalliance.espi.thirdparty.oauth.EspiTokenResponseParameters; import org.greenbuttonalliance.espi.thirdparty.oauth.TpCustomerAuthorizationRequestResolver; @@ -186,27 +187,38 @@ public SecurityFilterChain filterChain(HttpSecurity http, public EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService( ClientRegistrationRepository clientRegistrationRepository, AuthorizationRepository authorizationRepository, - RetailCustomerRepository retailCustomerRepository) { + RetailCustomerRepository retailCustomerRepository, + EspiIdGeneratorService espiIdGeneratorService, + EspiTokenResponseParameters espiTokenResponseParameters) { return new EspiAuthorizationOAuth2AuthorizedClientService(clientRegistrationRepository, - authorizationRepository, retailCustomerRepository); + authorizationRepository, retailCustomerRepository, espiIdGeneratorService, espiTokenResponseParameters); + } + + /** Hands each token response's ESPI URIs from the token-response clients to the token store. */ + @Bean + public EspiTokenResponseParameters espiTokenResponseParameters() { + return new EspiTokenResponseParameters(); } /** authorization_code token exchange, keeping the response's ESPI URIs for the token store. */ @Bean - public OAuth2AccessTokenResponseClient authorizationCodeTokenResponseClient() { - return EspiTokenResponseParameters.capturing(new RestClientAuthorizationCodeTokenResponseClient()); + public OAuth2AccessTokenResponseClient authorizationCodeTokenResponseClient( + EspiTokenResponseParameters espiTokenResponseParameters) { + return espiTokenResponseParameters.capturing(new RestClientAuthorizationCodeTokenResponseClient()); } /** refresh_token exchange, keeping the response's ESPI URIs (if it repeats them) for the token store. */ @Bean - public OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient() { - return EspiTokenResponseParameters.capturing(new RestClientRefreshTokenTokenResponseClient()); + public OAuth2AccessTokenResponseClient refreshTokenTokenResponseClient( + EspiTokenResponseParameters espiTokenResponseParameters) { + return espiTokenResponseParameters.capturing(new RestClientRefreshTokenTokenResponseClient()); } /** client_credentials exchange (the TP's client access token), keeping any ESPI URIs for the token store. */ @Bean - public OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient() { - return EspiTokenResponseParameters.capturing(new RestClientClientCredentialsTokenResponseClient()); + public OAuth2AccessTokenResponseClient clientCredentialsTokenResponseClient( + EspiTokenResponseParameters espiTokenResponseParameters) { + return espiTokenResponseParameters.capturing(new RestClientClientCredentialsTokenResponseClient()); } /** diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java index 476d4b3c..5e3a1f19 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiAuthorizationOAuth2AuthorizedClientService.java @@ -71,14 +71,19 @@ public class EspiAuthorizationOAuth2AuthorizedClientService implements OAuth2Aut private final ClientRegistrationRepository clientRegistrationRepository; private final AuthorizationRepository authorizationRepository; private final RetailCustomerRepository retailCustomerRepository; - private final EspiIdGeneratorService idGenerator = new EspiIdGeneratorService(); + private final EspiIdGeneratorService idGenerator; + private final EspiTokenResponseParameters tokenResponseParameters; public EspiAuthorizationOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository, AuthorizationRepository authorizationRepository, - RetailCustomerRepository retailCustomerRepository) { + RetailCustomerRepository retailCustomerRepository, + EspiIdGeneratorService idGenerator, + EspiTokenResponseParameters tokenResponseParameters) { this.clientRegistrationRepository = clientRegistrationRepository; this.authorizationRepository = authorizationRepository; this.retailCustomerRepository = retailCustomerRepository; + this.idGenerator = idGenerator; + this.tokenResponseParameters = tokenResponseParameters; } @Override @@ -121,7 +126,7 @@ public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authen authorization.setGrantType(isClientCredentials(registration) ? GrantType.CLIENT_CREDENTIALS : GrantType.AUTHORIZATION_CODE); // A refresh response that repeats no URI keeps the ones the authorization_code response gave. - EspiTokenResponseParameters.take(accessToken.getTokenValue()).ifPresent(uris -> { + tokenResponseParameters.take(accessToken.getTokenValue()).ifPresent(uris -> { if (uris.resourceUri() != null) { authorization.setResourceURI(uris.resourceUri()); } @@ -180,7 +185,7 @@ UUID authorizationId(ClientRegistration registration, String principalName) { private static OAuth2AuthorizedClient toAuthorizedClient(ClientRegistration registration, String principalName, AuthorizationEntity authorization) { - Instant expiresAt = authorization.getExpiresIn() == null ? null : Instant.ofEpochMilli(authorization.getExpiresIn()); + Instant expiresAt = authorization.getExpirationInstant(); Instant issuedAt = issuedAt(authorization.getUpdated(), expiresAt); Set scopes = authorization.getScope() == null ? Set.of() : new LinkedHashSet<>(Arrays.asList(authorization.getScope().trim().split("\\s+"))); diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java index 338c3308..d7739bed 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParameters.java @@ -22,6 +22,8 @@ import org.springframework.security.oauth2.client.endpoint.AbstractOAuth2AuthorizationGrantRequest; import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; + +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Map; @@ -29,19 +31,21 @@ import java.util.concurrent.ConcurrentHashMap; /** - * Keeps the ESPI URIs of a token response until the token is stored (#146). + * Keeps the ESPI URIs of a token response until the token is stored (#146). One instance (a Spring + * bean) is shared by the token-response clients and {@link EspiAuthorizationOAuth2AuthorizedClientService}. * *

REQ.21 6.1.2 puts {@code resourceURI}, {@code authorizationURI} and (with FB_51) * {@code customerResourceURI} in the token response, next to the access token. Spring Security parses * them into {@link OAuth2AccessTokenResponse#getAdditionalParameters()}, but the * {@code OAuth2AuthorizedClient} it then stores holds only the tokens, so they would be lost. The * {@link #capturing capturing} token-response client keeps them in memory, keyed by the access token, - * and {@link EspiAuthorizationOAuth2AuthorizedClientService} takes them when it stores that token.

+ * and the token store {@link #take takes} them when it stores that token.

* *

The hand-over does not depend on a servlet request, so a token obtained or refreshed on another * thread (a {@code WebClient} call, a scheduled import) keeps its URIs too. Spring stores the token * right after the response in the same call, so an entry normally lives for milliseconds; one that is - * never taken (the store failed) is dropped after {@link #RETENTION}.

+ * never taken (the store failed) is dropped once it is older than {@link #RETENTION}, the next time a + * token response arrives or a token is stored.

*/ public final class EspiTokenResponseParameters { @@ -53,12 +57,6 @@ public final class EspiTokenResponseParameters { /** How long the URIs of a token response wait to be taken before they are dropped. */ static final Duration RETENTION = Duration.ofMinutes(5); - private record Pending(EspiUris uris, Instant received) { - } - - /** Token responses whose token has not been stored yet, by access token value. */ - private static final Map PENDING = new ConcurrentHashMap<>(); - /** The ESPI URIs of one token response; any of them may be {@code null}. */ public record EspiUris(String resourceUri, String authorizationUri, String customerResourceUri) { @@ -73,18 +71,30 @@ private static String text(Map parameters, String name) { } } - private EspiTokenResponseParameters() { + private record Pending(EspiUris uris, Instant received) { + } + + /** Token responses whose token has not been stored yet, by access token value. */ + private final Map pending = new ConcurrentHashMap<>(); + private final Clock clock; + + public EspiTokenResponseParameters() { + this(Clock.systemUTC()); + } + + EspiTokenResponseParameters(Clock clock) { + this.clock = clock; } /** Wraps a Spring token-response client so the ESPI URIs of each response are kept for storage. */ - public static OAuth2AccessTokenResponseClient capturing( + public OAuth2AccessTokenResponseClient capturing( OAuth2AccessTokenResponseClient delegate) { return grantRequest -> { OAuth2AccessTokenResponse response = delegate.getTokenResponse(grantRequest); if (response != null) { - Instant now = Instant.now(); - PENDING.values().removeIf(pending -> pending.received().isBefore(now.minus(RETENTION))); - PENDING.put(response.getAccessToken().getTokenValue(), + Instant now = clock.instant(); + dropExpired(now); + pending.put(response.getAccessToken().getTokenValue(), new Pending(EspiUris.from(response.getAdditionalParameters()), now)); } return response; @@ -92,7 +102,19 @@ public static OAuth2AccessTo } /** The ESPI URIs that came with this access token, removed once taken. */ - static Optional take(String accessTokenValue) { - return Optional.ofNullable(PENDING.remove(accessTokenValue)).map(Pending::uris); + Optional take(String accessTokenValue) { + Optional uris = Optional.ofNullable(pending.remove(accessTokenValue)).map(Pending::uris); + dropExpired(clock.instant()); + return uris; + } + + /** How many token responses are waiting to be taken (for tests). */ + int pendingCount() { + return pending.size(); + } + + private void dropExpired(Instant now) { + Instant oldest = now.minus(RETENTION); + pending.values().removeIf(entry -> entry.received().isBefore(oldest)); } } diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java index 94c7fa0a..1f42767a 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/oauth/TpCustomerAuthorizationRequestResolver.java @@ -30,6 +30,8 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @@ -51,6 +53,8 @@ public class TpCustomerAuthorizationRequestResolver implements OAuth2Authorizati private final ClientRegistrationRepository clientRegistrationRepository; private final DefaultOAuth2AuthorizationRequestResolver delegate; + /** Spring Security's default request cache, which the form login and the grant filter both use. */ + private final RequestCache requestCache = new HttpSessionRequestCache(); private final RequestMatcher authorizationRequestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(AUTHORIZATION_BASE_URI + "/{" + REGISTRATION_ID + "}"); @@ -86,7 +90,15 @@ public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String cli || !AuthorizationGrantType.AUTHORIZATION_CODE.equals(registration.getAuthorizationGrantType())) { return null; } - return delegate.resolve(request, clientRegistrationId); + OAuth2AuthorizationRequest authorizationRequest = delegate.resolve(request, clientRegistrationId); + if (authorizationRequest != null) { + // A request saved before sign-in (e.g. this very /oauth2/authorization URL, when an anonymous + // visitor started here) has been used by now. Left in the session, OAuth2AuthorizationCodeGrantFilter + // would redirect to it after the code exchange instead of to the callback, starting a second + // round trip to the Data Custodian or skipping the "authorized" message. + requestCache.removeRequest(request, null); + } + return authorizationRequest; } private static boolean isTpCustomer() { diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java index 8ce8a6e8..9326d554 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/AuthorizationView.java @@ -44,8 +44,8 @@ static AuthorizationView of(AuthorizationEntity authorization, ClientRegistratio ClientRegistration registration = authorization.getClientRegistrationId() == null ? null : registrations.findByRegistrationId(authorization.getClientRegistrationId()); String access = registration == null ? authorization.getClientRegistrationId() : registration.getClientName(); - String expires = authorization.getExpiresIn() == null ? "-" - : TIME.format(Instant.ofEpochMilli(authorization.getExpiresIn())); + Instant expiresAt = authorization.getExpirationInstant(); + String expires = expiresAt == null ? "-" : TIME.format(expiresAt); String obtained = authorization.getUpdated() == null ? "-" : TIME.format(authorization.getUpdated().atZone(ZoneId.systemDefault())); String token = authorization.getAccessToken(); diff --git a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java index 72060f25..80b9409b 100644 --- a/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java +++ b/openespi-thirdparty/src/main/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeController.java @@ -23,7 +23,6 @@ import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.dao.DataAccessException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; @@ -31,14 +30,12 @@ import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; -import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.client.RestClientException; /** * The Third Party administrator's landing page after login (#249), with a check of the TP's ESPI @@ -83,6 +80,11 @@ public String index(Authentication authentication, Model model) { public String obtainClientToken(Authentication authentication) { ClientRegistration registration = clientRegistrationRepository .findByRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS); + if (registration == null) { + logger.warn("No {} client registration is configured, so no client access token can be obtained", + DataCustodianRegistrations.CLIENT_ACCESS); + return "redirect:/custodian/home?client_token_error"; + } try { OAuth2AccessTokenResponse tokenResponse = clientCredentialsTokenResponseClient .getTokenResponse(new OAuth2ClientCredentialsGrantRequest(registration)); @@ -90,8 +92,10 @@ public String obtainClientToken(Authentication authentication) { authentication.getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()), authentication); return "redirect:/custodian/home?client_token"; - } catch (OAuth2AuthorizationException | RestClientException | DataAccessException ex) { - logger.warn("Could not obtain the TP client access token: {}", ex.getMessage()); + } catch (RuntimeException ex) { + // Any failure (the AS refusing or unreachable, an unreadable response, the save or its commit) + // leaves the token already held in use; the admin gets the error message, never a 500. + logger.warn("Could not obtain the TP client access token", ex); return "redirect:/custodian/home?client_token_error"; } } diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java index 7e598f1d..f1d68684 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/oauth/EspiTokenResponseParametersTest.java @@ -27,6 +27,10 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.web.context.request.RequestContextHolder; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -37,8 +41,35 @@ class EspiTokenResponseParametersTest { private static final String RESOURCE_URI = "https://dc.example/espi/1_1/resource/Batch/Subscription/1"; private static final String AUTHORIZATION_URI = "https://dc.example/espi/1_1/resource/Authorization/2"; - private static OAuth2AccessTokenResponseClient capturing(String tokenValue) { - return EspiTokenResponseParameters.capturing(grantRequest -> OAuth2AccessTokenResponse.withToken(tokenValue) + /** A clock the test moves forward. */ + private static final class MovableClock extends Clock { + private Instant now = Instant.parse("2026-11-17T12:00:00Z"); + + void advance(java.time.Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } + + private final MovableClock clock = new MovableClock(); + private final EspiTokenResponseParameters parameters = new EspiTokenResponseParameters(clock); + + private OAuth2AccessTokenResponseClient capturing(String tokenValue) { + return parameters.capturing(grantRequest -> OAuth2AccessTokenResponse.withToken(tokenValue) .tokenType(OAuth2AccessToken.TokenType.BEARER) .expiresIn(3600) .additionalParameters(Map.of(EspiTokenResponseParameters.RESOURCE_URI, RESOURCE_URI, @@ -54,7 +85,7 @@ void hand_over_works_without_a_request() throws Exception { capturing("off-request-token").getTokenResponse(null); }).get(); - assertThat(EspiTokenResponseParameters.take("off-request-token")) + assertThat(parameters.take("off-request-token")) .hasValue(new EspiTokenResponseParameters.EspiUris(RESOURCE_URI, AUTHORIZATION_URI, null)); } @@ -63,7 +94,17 @@ void hand_over_works_without_a_request() throws Exception { void uris_are_taken_once() { capturing("once-token").getTokenResponse(null); - assertThat(EspiTokenResponseParameters.take("once-token")).isPresent(); - assertThat(EspiTokenResponseParameters.take("once-token")).isEmpty(); + assertThat(parameters.take("once-token")).isPresent(); + assertThat(parameters.take("once-token")).isEmpty(); + } + + @Test + @DisplayName("URIs never taken (the store failed) are dropped after the retention, also when only a take follows") + void untaken_uris_expire() { + capturing("stranded-token").getTokenResponse(null); + clock.advance(EspiTokenResponseParameters.RETENTION.plusSeconds(1)); + + assertThat(parameters.take("some-other-token")).isEmpty(); + assertThat(parameters.pendingCount()).isZero(); } } diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeControllerClientTokenTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeControllerClientTokenTest.java new file mode 100644 index 00000000..8e705007 --- /dev/null +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/CustodianHomeControllerClientTokenTest.java @@ -0,0 +1,79 @@ +/* + * + * 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.web; + +import org.greenbuttonalliance.espi.thirdparty.oauth.DataCustodianRegistrations; +import org.greenbuttonalliance.espi.thirdparty.oauth.EspiAuthorizationOAuth2AuthorizedClientService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; +import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.core.AuthorizationGrantType; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * The admin's "Obtain a new client access token" action never ends in a 500: whatever fails, the token + * already held stays in use and the admin gets the error message (#275 review). + */ +class CustodianHomeControllerClientTokenTest { + + private static final String ERROR = "redirect:/custodian/home?client_token_error"; + + @SuppressWarnings("unchecked") + private final OAuth2AccessTokenResponseClient tokenResponseClient = + mock(OAuth2AccessTokenResponseClient.class); + private final EspiAuthorizationOAuth2AuthorizedClientService authorizedClientService = + mock(EspiAuthorizationOAuth2AuthorizedClientService.class); + private final ClientRegistrationRepository registrations = mock(ClientRegistrationRepository.class); + private final CustodianHomeController controller = + new CustodianHomeController(tokenResponseClient, authorizedClientService, registrations); + private final Authentication admin = new TestingAuthenticationToken("admin", null, "ROLE_CUSTODIAN"); + + @Test + @DisplayName("no client_credentials registration configured: the error message, no token request") + void missing_registration() { + assertThat(controller.obtainClientToken(admin)).isEqualTo(ERROR); + verifyNoInteractions(tokenResponseClient, authorizedClientService); + } + + @Test + @DisplayName("a failure outside the OAuth2 exceptions (an unreadable response) still gives the error message") + void unexpected_failure() { + when(registrations.findByRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS)).thenReturn( + ClientRegistration.withRegistrationId(DataCustodianRegistrations.CLIENT_ACCESS) + .clientId("third_party") + .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) + .tokenUri("http://localhost:9999/oauth2/token") + .build()); + when(tokenResponseClient.getTokenResponse(any())).thenThrow(new IllegalArgumentException("no access_token")); + + assertThat(controller.obtainClientToken(admin)).isEqualTo(ERROR); + verifyNoInteractions(authorizedClientService); + } +} diff --git a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java index bf19b63c..e2b9d090 100644 --- a/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java +++ b/openespi-thirdparty/src/test/java/org/greenbuttonalliance/espi/thirdparty/web/DataCustodianAuthorizationTest.java @@ -93,6 +93,9 @@ class DataCustodianAuthorizationTest { private static final String BULK_CUSTOMER_RESOURCE_URI = "http://localhost:8081/DataCustodian/espi/1_1/resource/Batch/Bulk/13"; private static final String MONTHLY_SCOPE ="FB=4_5_15;IntervalDuration=3600;BlockDuration=monthly;HistoryLength=13"; + /** HttpSessionRequestCache's session attribute: the request saved for after sign-in. */ + private static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST"; + private static HttpServer tokenEndpoint; /** The form parameters of each token request the stub received, by grant type. */ @@ -283,6 +286,28 @@ void callback_stores_token_and_keeps_tp_sign_in() throws Exception { .doesNotContain("customer-token-1234", "customer-refresh"); } + @Test + @DisplayName("a visitor who starts signed out signs in, consents once, and lands on the callback, not on a second authorization") + void start_signed_out_then_consent_once() throws Exception { + MockHttpSession session = new MockHttpSession(); + mockMvc.perform(get("/oauth2/authorization/" + DataCustodianRegistrations.MONTHLY).session(session)) + .andExpect(redirectedUrl("/login")); + assertThat(session.getAttribute(SAVED_REQUEST)).as("the request saved for after sign-in").isNotNull(); + + // Signed in by form login, which resumes the saved /oauth2/authorization request. + session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + new SecurityContextImpl(UsernamePasswordAuthenticationToken.authenticated(CUSTOMER, null, + AuthorityUtils.createAuthorityList(RetailCustomerEntity.ROLE_USER)))); + String state = startAuthorization(session); + assertThat(session.getAttribute(SAVED_REQUEST)).as("the saved request, used up").isNull(); + + mockMvc.perform(get(TP_BASE + CALLBACK).queryParam("code", "the-code") + .queryParam("state", state).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl(TP_BASE + CALLBACK)); + mockMvc.perform(get(TP_BASE + CALLBACK).contextPath("/ThirdParty").session(session)) + .andExpect(redirectedUrl("/ThirdParty/?authorized")); + } + @Test @DisplayName("consent refused at the Data Custodian: nothing is stored and the customer gets the home page's message") void refused_consent_stores_nothing() throws Exception {