Repository navigation
fix(thirdparty): address the #268 review of Third Party form login (#249) - #270
Merged
Merged
Conversation
) - Seed a local-only TP customer (customer/customer, ROLE_USER) beside the admin, so the Data Access Authorization cards can be reached locally. LocalDevAdminSeedRunner is renamed LocalDevAccountSeedRunner. - Drop the explicit DaoAuthenticationProvider: Spring Security already builds one from the UserDetailsService and PasswordEncoder beans, so every failed login was checked twice. - A failed Data Custodian authorization (oauth2Login) now returns to /?authorization_error with its own message instead of the login page's "Invalid username or password". - The H2 console requires ROLE_CUSTODIAN (TP administrators) instead of ROLE_ADMIN, which no TP account can hold. - ReturnToAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler instead of re-implementing the saved-request redirect. - LocalDevAccountSeedRunnerTest uses one AssertJ chain per object. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 tasks
…inistrators The previous commit let ROLE_CUSTODIAN open /h2-console. The local profile seeds admin/admin with that role and set web-allow-others: true, and the H2 console runs arbitrary SQL (CREATE ALIAS runs Java code), so anyone who could reach the dev machine could get code execution. Before that commit the console was unreachable (ROLE_ADMIN, which no account holds). - /h2-console/** is denyAll; its CSRF exemption is removed. - The local profile sets web-allow-others: false. - The rule's comment names every profile that enables the console (local, dev, h2), not only local. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Blocking the H2 console for everyone (previous commit) overcorrected: developers need it for diagnostics. The risk was the combination of remote access (web-allow-others: true), seeded public credentials and an SQL console that can run Java code, not the console itself. - /h2-console/** requires ROLE_CUSTODIAN again, with its CSRF exemption (the console's own forms carry no token). - H2 answers localhost only (web-allow-others: false on local; dev and h2 already had it). - local sets the session cookie to SameSite=Lax explicitly, so a cross-site page cannot reach the CSRF-exempt console with the developer's session; Lax still allows the redirect back from the AS. - Add spring-boot-h2console: Spring Boot 4 moved the console's auto-configuration into that module, so spring.h2.console.enabled has done nothing in this module since the Boot 4 migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ite check A second security review showed the console was still reachable with the developer's session from other pages: SameSite=Lax was set on local only (dev and h2 enable the console too), and every localhost port is the same site, so a page on another local port could POST to the CSRF-exempt console with the admin's cookie. - H2ConsoleSecurityConfiguration: its own filter chain for /h2-console/**, loaded only where spring.h2.console.enabled=true (the local, dev and h2 profiles). It requires ROLE_CUSTODIAN and a same-origin or user-initiated request (Sec-Fetch-Site: same-origin or none; SameOriginFetchAuthorizationManager), sends anonymous users to /login, disables CSRF tokens for the console only, and allows same-origin frames. - The main chain now denies /h2-console/** and has no H2 exemptions, so every other profile keeps the console shut. - The session cookie is SameSite=Lax on every profile (application.yml), not Strict: the redirect back from the AS must carry the session. - Tests: H2ConsoleSecurityTest with the console enabled; FormLoginTest checks the chain is absent and the console closed when disabled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… path, explicit provider) - Sec-Fetch-Site: none is accepted only for a parameterless GET of the console's entry page. A link opened from another application (e-mail, chat, PDF) also arrives as none with the session cookie, and could otherwise carry an action such as login.do?url=...;INIT=RUNSCRIPT. Everything after the entry page is same-origin. - Both chains take the console's path from spring.h2.console.path instead of hard-coding /h2-console, so the rules follow the console if the path changes. (Boot's PathRequest.toH2Console() needs H2ConsoleProperties, which only exists when the console is enabled, so it cannot serve the main chain.) - The TP form-login DaoAuthenticationProvider is an explicit bean using the BCrypt customerPasswordEncoder, instead of the provider Spring Security infers from exactly one UserDetailsService and one PasswordEncoder. Still one check per login; not http.authenticationManager(...), which would drop oauth2Login's provider. - H2ConsoleSecurityTest runs on a non-default console path and covers the entry-page rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… normalise console path; session-ended banner Second review of #270: - A same-origin redirect after the login POST also arrives as Sec-Fetch-Site: same-origin, so an attacker's console action could be laundered through sign-in, either as the saved interrupted request or as return_to, and then run by H2. SameOriginFetchAuthorizationManager now requires, for anything but the entry page, a same-origin request whose Referer is a page of the console itself (the console's frames, forms and scripts always send one; a sign-in redirect carries the login page's). The console chain saves only the entry page for the redirect back after sign-in, without the ?continue marker. - spring.h2.console.path is normalised once (trailing slashes removed) for both chains: '/h2-console/' would otherwise give the pattern '/h2-console//**', which matches nothing. - After a failed Data Custodian authorization, a user whose TP session ended is told so and offered the login page, instead of a retry banner with no authorization cards to retry from. - Tests: signed-out flows (saved action not replayed, entry page replayed, return_to action refused), console Referer rules, the console test runs on '/dbconsole/', H2ConsoleBasePathTest, and the signed-out banner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Follow-up to #268 (Third Party form login, #249), fixing findings from its code review. Every change has a test that failed before the fix.
Changes
local,LocalDevAccountSeedRunner(renamed fromLocalDevAdminSeedRunner) now seedscustomer/customer(ROLE_USER) besideadmin/admin(ROLE_CUSTODIAN). Before, no account could reach the Data Access Authorization cards, so the TP → DC authorization flow could not be tried locally.DaoAuthenticationProviderduplicated the one Spring Security builds from theUserDetailsServiceandPasswordEncoderbeans, so every failed login ran two lookups and two BCrypt checks. A spy test now checks a wrong password is looked up once.oauth2Loginfailures (consent refused, token exchange failed) now go to/?authorization_error, which shows "The Data Custodian authorization did not complete". Before, they went to/login?error=true, which shows "Invalid username or password"./h2-console/**requiredROLE_ADMIN, which no TP account holds. Developers now get the console for diagnostics. It runs any SQL and H2'sCREATE ALIASruns Java code, so:H2ConsoleSecurityConfigurationwith its own filter chain for the console's path (spring.h2.console.path, default/h2-console, trailing slashes removed) loads only wherespring.h2.console.enabled=true(thelocal,devandh2profiles). The main chain denies the console's path and has no H2 exemptions, so in every other profile the console stays shut.ROLE_CUSTODIAN;admin/adminonlocal). Anonymous users go to/loginand come back to the console after signing in.SameOriginFetchAuthorizationManager). The entry page (a parameterless GET) may be opened assame-originornone(typed URL, bookmark, link from another application). Every other console request must besame-originand carry aRefererfrom a console page, which the console's own frames, forms and scripts always send. A same-origin redirect after sign-in carries the login page'sReferer, so an attacker's action URL can't be laundered through the sign-in. Only the entry page is saved for the redirect back after sign-in.localsetsweb-allow-others: false, asdevandh2already did.SameSite=Laxon every profile (application.yml). NotStrict, because the redirect back from the AS must carry the session.spring-boot-h2console. Spring Boot 4 moved the console's auto-configuration into this module, sospring.h2.console.enabledhad done nothing since the Boot 4 migration.ReturnToAuthenticationSuccessHandlernow extendsSavedRequestAwareAuthenticationSuccessHandlerand overrides only thereturn_tocheck and the role landing page.LocalDevAccountSeedRunnerTestuses one chain per object, as CLAUDE.md requires.Fixes from the review of this PR
Sec-Fetch-Site: nonelimited to the console's entry page. A link opened from another application also arrives asnonewith the session cookie. It could have carried an action such aslogin.do?url=…;INIT=RUNSCRIPT FROM '…', which H2 would run because CSRF is off for the console. Nownoneis accepted only for a parameterless GET of the entry page. Checked in Chrome: the console's own requests after the entry page all arrive assame-origin, and a typedlogin.do?url=…gets 403.spring.h2.console.pathin both chains instead of hard-coded/h2-console. Before, moving the console (for example to/db) would have left it underauthenticated(), open to any signed-in customer. Boot'sPathRequest.toH2Console()needsH2ConsoleProperties, which exists only when the console is enabled, so it can't serve the main chain.H2ConsoleSecurityTestnow runs on/dbconsole.customerAuthenticationProvideris aDaoAuthenticationProviderbean using the BCryptcustomerPasswordEncoder. Spring Security no longer has to infer it from exactly oneUserDetailsServiceand onePasswordEncoder; a second encoder bean would previously have broken every login. Still one check per login. Nothttp.authenticationManager(...), because that would drop the provideroauth2Loginregisters.oauth2Loginlets a visitor with no TP account sign in to the TP through a Data Custodian. This predates feat(thirdparty): username/password login matching the Data Custodian design (#249) #268 and is fixed by theoauth2Client()change described there.Fixes from the second review of this PR
Sec-Fetch-Sitealone wasn't enough: the redirect after the login POST also arrives assame-origin. Starting signed out, an attacker'slogin.do?url=…;INIT=RUNSCRIPT …could be saved as the interrupted request, or passed asreturn_to, and then run by H2 once the admin signed in. Fixed by the consoleRefererrule above, and by saving only the entry page (without the?continuemarker) for the redirect back. Checked in Chrome, starting signed out:/custodian/home, not replayed;return_topointing at an action → 403;RETAIL_CUSTOMERSand runs a query, with no console request blocked.spring.h2.console.path. Spring Boot accepts/h2-console/, but appending/**gave/h2-console//**, which matches nothing, so the console fell through toauthenticated(). Both chains now use the path with trailing slashes removed.H2ConsoleSecurityTestruns on/dbconsole/, andH2ConsoleBasePathTestcovers the cleanup./?authorization_error, signed-in users keep the retry message. Users whose TP session ended see "Your Third Party session ended during the Data Custodian authorization… Sign in and try again" with a link to/login, instead of a retry banner with no cards to retry from.Minor review findings: corrections, not made in this PR
/custodian/**) is sent back to it and gets 403, instead of their home page.Correction: in
ReturnToAuthenticationSuccessHandler, replay the saved request only if the signed-in user may open it. Check with Spring Security'sWebInvocationPrivilegeEvaluator.isAllowed(uri, authentication), and otherwise use the role landing page. Add a test: a customer signs in after a saved/custodian/homeand lands on/.Note:
WebInvocationPrivilegeEvaluatorevaluates only the security chains' URL rules, not@PreAuthorize, so a page protected only by method security would still be replayed. Also add/custodian/**→hasRole("CUSTODIAN")to the main chain; the H2 console is already covered by its own chain.Concurrency: the evaluator is a stateless singleton over chains that don't change after startup, so concurrent sign-ins don't interfere.
requestCachefield in the success handler. It mirrors the superclass's private cache and is kept in step by overridingsetRequestCache.Correction: create one
RequestCacheinSecurityConfiguration, give it to both chains (http.requestCache(c -> c.requestCache(cache))) and to the handler's constructor. Keep it in a singlefinalfield, and stop extendingSavedRequestAwareAuthenticationSuccessHandler(or call only its public API).Concurrency: safe to share.
HttpSessionRequestCachekeeps no state of its own; each saved request lives in that user's HTTP session. The current non-final field is written once during startup, before any request thread, so it isn't a live bug; thefinalfield removes the question. One race remains and is not introduced by this change: two requests in the same session overwrite each other's saved request (one session attribute, last write wins). For example, the user opens/custodian/homesigned out in one tab, then signs in from another tab and is taken there. It affects only one user's own tabs and is Spring Security's default behaviour; item 1's permission check bounds what can be replayed.@MockitoSpyBeaninFormLoginTestand the property-specificH2ConsoleSecurityTesteach start another application context, a few seconds permvn testrun.Correction: replace the spy with a direct check that the
AuthenticationManagerholds a singleDaoAuthenticationProvider. ThenFormLoginTestshares the cachedtestcontext.H2ConsoleSecurityTestneeds the console enabled, so it keeps its own context; that one is intended.Note: the tests run one class at a time (no
parallel/forkCountsetting in the POMs, nojunit-platform.properties), and Spring's context cache is thread-safe, so there is no thread conflict today. But every Spring test context shares one in-memory database (jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1) withcreate-drop, so a new context recreates the tables under the cached ones. That is harmless now becauseFormLoginTestcreates and deletes its own accounts. Before parallel tests are ever enabled, give each context its own database (jdbc:h2:mem:${random.uuid}inapplication-test.yml) or keep these classes non-parallel. Sharing more of one context, as this change does, would otherwise make collisions more likely./?authorization_errorsays no data access was granted but not that the user is signed out.Correction: in
home.html, show the existing message to signed-in users (sec:authorize="isAuthenticated()"). Show anonymous users "Your Third Party session ended during the Data Custodian authorization. Sign in and try again." with a link to/login. Withoauth2Client()(TP bring-up: missing JAXB Atom marshaller, narrow component scan, and broader OAuth2-client wiring gaps #146), the error comes from the authorization-code grant filter and the same split applies.Not in this PR
oauth2Loginreplaces the TP sign-in, so customer pages then return 403. It needs the move tooauth2Client; details are in a comment on TP bring-up: missing JAXB Atom marshaller, narrow component scan, and broader OAuth2-client wiring gaps #146.RetailCustomerControllersaves plaintext passwords and bindsrolefrom the form. Its template does not exist, so it is unreachable today; it must be fixed before that admin screen is built.UserDetailsServiceand seeder into openespi-common is a refactor for later.Test plan
mvn verify -pl openespi-thirdparty: 97 tests, 0 failures (H2ConsoleSecurityTestcovers the console enabled;FormLoginTestcovers it disabled)local:customer/customerlands on/with the authorization cards;/?authorization_errorshows the new messagelocal, in Chrome: not signed in →/login→ back to the console after signing in asadmin; connected and sawRETAIL_CUSTOMERS;customergets 403; a page on another localhost port auto-submitting a POST to the console gets 40357010b6a. In both: the console works, starting signed out (entry page → sign in → back to the console → connect →RETAIL_CUSTOMERS→ query), with no console request blocked. A saved attacker action is not replayed (sign-in lands on/custodian/home, nothing reaches H2). Areturn_toconsole action gets 403 (itsRefereris the login page). A POST from a page onlocalhost:8099gets 403 (Sec-Fetch-Site: same-site).57010b6a, starting signed out each time: (1) the console works: sign in, connect, queryRETAIL_CUSTOMERS; (2) a saved attacker action is not replayed, and sign-in lands on the Administration page; (3) areturn_toconsole action gets 403 after sign-in. Not run in Safari: the customer-refused check and the other-port POST, both covered in the other browsers and inH2ConsoleSecurityTest. Two things seen during testing that are not app behaviour: paths are case-sensitive, so/H2-console/is not the console and gives a 404 after sign-in; and Safari repeated some requests (/login) about every 25 ms, with nothing in the app causing it.🤖 Generated with Claude Code