Skip to content

fix(thirdparty): address the #268 review of Third Party form login (#249) - #270

Merged
dfcoffin merged 6 commits into
mainfrom
fix/268-review-followups
Nov 16, 2026
Merged

dfcoffin merged 6 commits into
mainfrom
fix/268-review-followups

Conversation

@dfcoffin

@dfcoffin dfcoffin commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Seed a local TP customer (review item 2). On local, LocalDevAccountSeedRunner (renamed from LocalDevAdminSeedRunner) now seeds customer/customer (ROLE_USER) beside admin/admin (ROLE_CUSTODIAN). Before, no account could reach the Data Access Authorization cards, so the TP → DC authorization flow could not be tried locally.
  • One authentication provider (item 3). The explicit DaoAuthenticationProvider duplicated the one Spring Security builds from the UserDetailsService and PasswordEncoder beans, so every failed login ran two lookups and two BCrypt checks. A spy test now checks a wrong password is looked up once.
  • Own message for a failed DC authorization (item 4). oauth2Login failures (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 for TP administrators, development profiles only (item 5). Before, /h2-console/** required ROLE_ADMIN, which no TP account holds. Developers now get the console for diagnostics. It runs any SQL and H2's CREATE ALIAS runs Java code, so:
    • Development only. A new H2ConsoleSecurityConfiguration with its own filter chain for the console's path (spring.h2.console.path, default /h2-console, trailing slashes removed) loads only where spring.h2.console.enabled=true (the local, dev and h2 profiles). The main chain denies the console's path and has no H2 exemptions, so in every other profile the console stays shut.
    • Signed-in TP administrator (ROLE_CUSTODIAN; admin/admin on local). Anonymous users go to /login and come back to the console after signing in.
    • Requests from the console itself only (SameOriginFetchAuthorizationManager). The entry page (a parameterless GET) may be opened as same-origin or none (typed URL, bookmark, link from another application). Every other console request must be same-origin and carry a Referer from 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's Referer, 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.
    • Localhost only: local sets web-allow-others: false, as dev and h2 already did.
    • SameSite=Lax on every profile (application.yml). Not Strict, because the redirect back from the AS must carry the session.
    • Adds spring-boot-h2console. Spring Boot 4 moved the console's auto-configuration into this module, so spring.h2.console.enabled had done nothing since the Boot 4 migration.
    • Intermediate commits in this PR first blocked the console for everyone, then opened it with weaker guards, after automated security reviews; this is the final design.
  • Success handler extends Spring's (item 6). ReturnToAuthenticationSuccessHandler now extends SavedRequestAwareAuthenticationSuccessHandler and overrides only the return_to check and the role landing page.
  • AssertJ chains (item 7). LocalDevAccountSeedRunnerTest uses one chain per object, as CLAUDE.md requires.

Fixes from the review of this PR

  • Sec-Fetch-Site: none limited to the console's entry page. A link opened from another application also arrives as none with the session cookie. It could have carried an action such as login.do?url=…;INIT=RUNSCRIPT FROM '…', which H2 would run because CSRF is off for the console. Now none is accepted only for a parameterless GET of the entry page. Checked in Chrome: the console's own requests after the entry page all arrive as same-origin, and a typed login.do?url=… gets 403.
  • Console path read from spring.h2.console.path in both chains instead of hard-coded /h2-console. Before, moving the console (for example to /db) would have left it under authenticated(), open to any signed-in customer. Boot's PathRequest.toH2Console() needs H2ConsoleProperties, which exists only when the console is enabled, so it can't serve the main chain. H2ConsoleSecurityTest now runs on /dbconsole.
  • Explicit form-login provider. customerAuthenticationProvider is a DaoAuthenticationProvider bean using the BCrypt customerPasswordEncoder. Spring Security no longer has to infer it from exactly one UserDetailsService and one PasswordEncoder; a second encoder bean would previously have broken every login. Still one check per login. Not http.authenticationManager(...), because that would drop the provider oauth2Login registers.
  • Sign-in bypass added to TP bring-up: missing JAXB Atom marshaller, narrow component scan, and broader OAuth2-client wiring gaps #146. oauth2Login lets 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 the oauth2Client() change described there.

Fixes from the second review of this PR

  • Console actions laundered through sign-in. Sec-Fetch-Site alone wasn't enough: the redirect after the login POST also arrives as same-origin. Starting signed out, an attacker's login.do?url=…;INIT=RUNSCRIPT … could be saved as the interrupted request, or passed as return_to, and then run by H2 once the admin signed in. Fixed by the console Referer rule above, and by saving only the entry page (without the ?continue marker) for the redirect back. Checked in Chrome, starting signed out:
    • an attacker's action, then sign-in → /custodian/home, not replayed;
    • return_to pointing at an action → 403;
    • the entry page → back on the console after sign-in, which connects, lists RETAIL_CUSTOMERS and runs a query, with no console request blocked.
  • Trailing slash in spring.h2.console.path. Spring Boot accepts /h2-console/, but appending /** gave /h2-console//**, which matches nothing, so the console fell through to authenticated(). Both chains now use the path with trailing slashes removed. H2ConsoleSecurityTest runs on /dbconsole/, and H2ConsoleBasePathTest covers the cleanup.
  • Banner after a lost session (minor item 4, fixed). On /?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.
  • Extra test context (minor item 3) is unchanged and stays recorded below.

Minor review findings: corrections, not made in this PR

  1. Saved request replayed for the wrong role. A customer who signs in from a link to an admin-only page (the H2 console or /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's WebInvocationPrivilegeEvaluator.isAllowed(uri, authentication), and otherwise use the role landing page. Add a test: a customer signs in after a saved /custodian/home and lands on /.
    Note: WebInvocationPrivilegeEvaluator evaluates 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.
  2. Duplicate requestCache field in the success handler. It mirrors the superclass's private cache and is kept in step by overriding setRequestCache.
    Correction: create one RequestCache in SecurityConfiguration, give it to both chains (http.requestCache(c -> c.requestCache(cache))) and to the handler's constructor. Keep it in a single final field, and stop extending SavedRequestAwareAuthenticationSuccessHandler (or call only its public API).
    Concurrency: safe to share. HttpSessionRequestCache keeps 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; the final field 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/home signed 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.
  3. Extra Spring test contexts. @MockitoSpyBean in FormLoginTest and the property-specific H2ConsoleSecurityTest each start another application context, a few seconds per mvn test run.
    Correction: replace the spy with a direct check that the AuthenticationManager holds a single DaoAuthenticationProvider. Then FormLoginTest shares the cached test context. H2ConsoleSecurityTest needs the console enabled, so it keeps its own context; that one is intended.
    Note: the tests run one class at a time (no parallel/forkCount setting in the POMs, no junit-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) with create-drop, so a new context recreates the tables under the cached ones. That is harmless now because FormLoginTest creates and deletes its own accounts. Before parallel tests are ever enabled, give each context its own database (jdbc:h2:mem:${random.uuid} in application-test.yml) or keep these classes non-parallel. Sharing more of one context, as this change does, would otherwise make collisions more likely.
  4. Misleading banner when the session was lost. Fixed in this PR (see the second review above). If the TP session expired during Data Custodian authorization, /?authorization_error says 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. With oauth2Client() (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

  • Item 1: authorizing a DC through oauth2Login replaces the TP sign-in, so customer pages then return 403. It needs the move to oauth2Client; details are in a comment on TP bring-up: missing JAXB Atom marshaller, narrow component scan, and broader OAuth2-client wiring gaps #146.
  • Item 8: the legacy RetailCustomerController saves plaintext passwords and binds role from the form. Its template does not exist, so it is unreachable today; it must be fixed before that admin screen is built.
  • Item 9: moving the copied UserDetailsService and seeder into openespi-common is a refactor for later.

Test plan

  • mvn verify -pl openespi-thirdparty: 97 tests, 0 failures (H2ConsoleSecurityTest covers the console enabled; FormLoginTest covers it disabled)
  • The four new tests failed before the fixes
  • Ran the TP on local: customer/customer lands on / with the authorization cards; /?authorization_error shows the new message
  • H2 console on local, in Chrome: not signed in → /login → back to the console after signing in as admin; connected and saw RETAIL_CUSTOMERS; customer gets 403; a page on another localhost port auto-submitting a POST to the console gets 403
  • Same console checks in Firefox 159 and WebKit 27.2 (Playwright 1.65.1 builds, Windows), at 57010b6a. 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). A return_to console action gets 403 (its Referer is the login page). A POST from a page on localhost:8099 gets 403 (Sec-Fetch-Site: same-site).
  • Real Safari on macOS (MacBook Pro M1), at 57010b6a, starting signed out each time: (1) the console works: sign in, connect, query RETAIL_CUSTOMERS; (2) a saved attacker action is not replayed, and sign-in lands on the Administration page; (3) a return_to console 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 in H2ConsoleSecurityTest. 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

)

- 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>
dfcoffin and others added 2 commits November 16, 2026 13:18
…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>
@dfcoffin
dfcoffin merged commit 51c72bb into main Nov 16, 2026
14 checks passed
@dfcoffin
dfcoffin deleted the fix/268-review-followups branch November 16, 2026 21:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants