Skip to content

Harden synchronizer token consumption - #15803

Merged
borinquenkid merged 4 commits into
8.0.xfrom
fix/synchronizer-token-hardening
Aug 6, 2026
Merged

borinquenkid merged 4 commits into
8.0.xfrom
fix/synchronizer-token-hardening

Conversation

@jamesfredley

@jamesfredley jamesfredley commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

What was found

The synchronizer-token holder backing withForm kept token state in the HTTP session with no per-session bounds, and withForm validation reset token state as a separate step from validation. That left two hardening gaps:

  • A client could grow session token state across many URLs or repeated token generations.
  • Concurrent submits could both validate the same token before either request reset it, weakening the one-time-token guarantee.

What changed

  • Bound synchronizer-token storage to 100 URL buckets and 100 tokens per URL.
  • Trim already-oversized URL maps and per-URL token sets during token generation.
  • Add holder-level atomic validate-and-reset, and route withForm through it.
  • Preserve the existing URL-keyed public contract: generateToken(url), isValid(url, token), resetToken(url, token), and the TOKEN_URI request parameter continue to define the token scope.
  • Treat malformed token payloads as invalid without mutating holder state.
  • Document single-use atomic consumption and session bounds.

URL-scope rationale

This PR does not introduce a new URL-scoping policy. Grails already keys synchronizer tokens by URL through the holder API and TOKEN_URI; changing that contract here would be a separate compatibility decision. The hardening keeps the current URL-keyed model because it limits replay to the action that generated the token, preserves existing applications and tests, and still fixes the security issue this PR targets: unbounded session growth and non-atomic token consumption.

Verification

  • ./gradlew --no-daemon :grails-test-suite-web:test --tests "org.grails.web.servlet.mvc.SynchronizerTokensHolderTests" :grails-test-suite-uber:test --tests "org.grails.web.metaclass.WithFormMethodTests"
  • Earlier branch verification also covered the demo33 form-token synchronization example specs and :grails-web-mvc:check.

Contributor Checklist

Issue and Scope

  • This PR has no acknowledged issue yet; the background above explains why the hardening is necessary.
  • This PR addresses bounded storage and atomic token consume without changing token URL scope.
  • This PR contains a single focused synchronizer-token hardening change.
  • This PR targets 8.0.x, where behavior-hardening changes are permitted for discussion.

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR.
  • I ran the focused verification listed above.
  • The change follows the project's code style and avoids mass reformatting.
  • Generative AI tooling was used as an ai-generated starting point and reviewed before submission.

Licensing and Attribution

  • All contributed code is provided under the Apache License 2.0.
  • I have the necessary rights to submit this contribution and confirm it is my own original work.
  • Generative AI tooling use is labeled on the PR.

Documentation

  • User-facing token retention and single-use behavior are documented.
  • The PR description explains what changed and why.

Rebased on 8.0.x

Merged the latest 8.0.x (clean, no conflicts). Confirmed both Copilot eviction comments were already resolved (URL-count and per-URL eviction both loop-trim to their bounds), and re-ran SynchronizerTokensHolderTests + WithFormMethodTests successfully. See the latest comment for the clustered-session scope note.

Bound the per-session synchronizer token holder by URL and per-URL token count, and consume withForm tokens through a single holder-level atomic validate-and-reset operation. This prevents unbounded token growth and closes the race where concurrent submits could validate the same token before reset.

Assisted-by: opencode:gpt-5.5
Copilot AI review requested due to automatic review settings July 1, 2026 08:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR strengthens Grails’ synchronizer-token (double-submit) mechanism by bounding per-session token storage and making withForm token consumption a single atomic validate-and-reset operation, with expanded regression coverage across unit and example app tests.

Changes:

  • Add bounded token storage by URL count and tokens-per-URL, and introduce an atomic isValidAndResetToken() operation in SynchronizerTokensHolder.
  • Update Controller.withForm(...) to consume tokens via the new holder-level atomic operation and remove the session holder when empty.
  • Add/extend regression tests for bounded storage and one-time token consumption behavior (including concurrent consumption).

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/SynchronizerTokensHolder.groovy Adds synchronized validation/consumption, bounded storage, and ordered eviction of URLs/tokens.
grails-test-suite-web/src/test/groovy/org/grails/web/servlet/mvc/SynchronizerTokensHolderTests.groovy Adds unit tests for bounds, one-time consumption, malformed tokens, sibling tokens, and concurrent consume.
grails-test-examples/hibernate7/demo33/src/test/groovy/demo/TestControllerSpec.groovy Extends example spec to assert withForm reuse/double-submit results in invalid token handling.
grails-test-examples/demo33/src/test/groovy/demo/TestControllerSpec.groovy Same as above for the non-hibernate7 demo example.
grails-controllers/src/main/groovy/grails/artefact/Controller.groovy Switches withForm to consume-and-reset atomically via the holder, and clears the holder from session when empty.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 0.0000%. Comparing base (b980413) to head (1ffe64e).
⚠️ Report is 113 commits behind head on 8.0.x.

Additional details and impacted files

Impacted file tree graph

@@      Coverage Diff       @@
##   8.0.x   #15803   +/-   ##
==============================
==============================
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jdaugherty jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm missing something - aren't session tokens supposed to be valid for all URLs?

@jdaugherty

Copy link
Copy Markdown
Contributor

This PR doesn't adhere to our PR summary guidelines. Please update it.

@jamesfredley

Copy link
Copy Markdown
Contributor Author

Thanks. I updated the PR body to follow the summary policy more explicitly: it now separates "What was found", "What was fixed", and "Verification".

On URL scope: this PR preserves the existing holder contract, which already stores and validates tokens by URL (generateToken(url), isValid(url, token), resetToken(url, token), and the TOKEN_URI request parameter used by withForm). The change only bounds that existing URL-keyed storage and makes validation plus reset atomic so a token cannot be accepted twice under concurrency.

Ensure existing oversized synchronizer token holders are reduced to the configured URL and per-URL token limits in a single token generation. Cover upgraded-session states where older unbounded holders may already exceed the new limits.

Assisted-by: Hephaestus:openai/gpt-5.5
@jamesfredley

Copy link
Copy Markdown
Contributor Author

Maintenance pass complete. The two Copilot threads were already replied to and marked resolved, and I confirmed that status through the review-thread API. I reran the focused SynchronizerTokensHolderTests and WithFormMethodTests successfully. I also documented the Codecov/TestLens bot feedback in the PR body: Codecov's low patch coverage is covered by focused tests, and TestLens flagged unrelated scaffolding test flakiness while reporting checks completed.

Document single-use atomic token consumption for withForm and the bounded
session token storage (100 URL buckets, 100 tokens per URL) introduced by
the synchronizer token hardening, in the form tokens guide and the withForm
reference page.

Assisted-by: opencode:gpt-5.5
@jamesfredley

Copy link
Copy Markdown
Contributor Author

Pre-release review pass (2026-07-02, dual-reviewer: GPT-5.5 oracle + Codex CLI): NEEDS-IMPROVEMENT, now addressed.

Findings: the new bounded token retention (100 URL buckets / 100 tokens per URL, oldest trimmed) is user-visible but was undocumented (med) - fixed in 5130d3c4ac (form tokens guide + withForm reference). The reviewers confirmed the atomic consume path closes the concurrent double-submit race and that public holder methods and serialization remain compatible. One low-severity observation (pre-existing, unchanged by this PR): a concurrent same-session form render can race the empty-holder session removal and produce a rare false invalidToken.

@jdaugherty

Copy link
Copy Markdown
Contributor

Thanks. I updated the PR body to follow the summary policy more explicitly: it now separates "What was found", "What was fixed", and "Verification".

On URL scope: this PR preserves the existing holder contract, which already stores and validates tokens by URL (generateToken(url), isValid(url, token), resetToken(url, token), and the TOKEN_URI request parameter used by withForm). The change only bounds that existing URL-keyed storage and makes validation plus reset atomic so a token cannot be accepted twice under concurrency.

Can you fix the formatting on this?

@jamesfredley

Copy link
Copy Markdown
Contributor Author

Updated the summary formatting to follow the repository PR template and expanded the URL-scope rationale in the body.

Short version: this PR preserves the existing URL-keyed contract (generateToken(url), isValid(url, token), resetToken(url, token), and TOKEN_URI) rather than changing token scope. Keeping that contract limits replay to the action URL that generated the token, avoids a compatibility change in this hardening PR, and still fixes the concrete security issues here: unbounded token storage and non-atomic consume.

Verification: ./gradlew --no-daemon :grails-test-suite-web:test --tests "org.grails.web.servlet.mvc.SynchronizerTokensHolderTests" :grails-test-suite-uber:test --tests "org.grails.web.metaclass.WithFormMethodTests" passed.

@jamesfredley

Copy link
Copy Markdown
Contributor Author

Maintenance pass

Merged the latest 8.0.x (a large base gap - clean merge, no conflicts) and re-verified.

  • The two Copilot eviction comments are already resolved: both the URL-count eviction (while (currentTokens.size() > DEFAULT_MAX_TOKEN_URLS)) and the per-URL token eviction loop-trim an already-oversized session down to the bound in a single generateToken() call, and are covered by tests.
  • :grails-test-suite-web:test --tests SynchronizerTokensHolderTests and :grails-test-suite-uber:test --tests WithFormMethodTests both pass after the merge.

On @jdaugherty's URL-scope question: this PR keeps the existing URL-keyed holder contract (it only bounds that storage and makes validate+reset atomic) rather than changing token scope. Note for reviewers: the exactly-once guarantee is per in-memory holder - a clustered deployment without session affinity/replication would still need sticky sessions for it to hold, which is already true of the existing session-scoped synchronizer-token mechanism; distributed locking is out of scope for this hardening PR.

@testlens-app

testlens-app Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 1ffe64e
▶️ Tests: 19964 executed
⚪️ Checks: 61/61 completed


Learn more about TestLens at testlens.app.

@borinquenkid borinquenkid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did an exhaustive review of the diff plus an independent adversarial security pass (separate reviewer, focused on the concurrency/atomicity claims and CSRF threat model).

Findings:

  • The core fix — isValidAndResetToken() as a single synchronized check-and-remove on SynchronizerTokensHolder — correctly closes the concurrent double-submit race. The old synchronized on Controller#isTokenValid/resetToken was on a per-request trait instance and never actually serialized concurrent requests; moving the lock to the session-shared holder is the right fix. Verified with a two-thread race test (testConcurrentTokenConsumeAllowsOneSuccess) that exactly one submission wins.
  • Bounded LRU storage (100 URL buckets x 100 tokens/URL) is per-session only, can't be used to evict another user's tokens, and both Copilot's original single-removal eviction findings are now loop-trimmed and covered by tests (including the "already oversized on upgrade" case).
  • Malformed tokens fail closed without mutating holder state.
  • Public API (generateToken, isValid, resetToken(url[, token]), store) and session serialization compatibility are preserved — grepped every caller across the monorepo (FormTagLib, Spring Security UI plugin, all test suites), nothing breaks.
  • Docs updated for the new single-use/bounded-storage behavior.
  • CI is fully green across the matrix, and both review threads are resolved.

One low-severity, fail-safe race was independently identified: Controller#consumeToken's empty-check-then-session-detach isn't in the same critical section as the token consume, so a concurrent same-session form render could rarely have its freshly-generated token orphaned when the holder gets detached from the session. This can only cause a legitimate token to be wrongly rejected (self-DoS on the user's own form) — it cannot cause an invalid/reused/attacker-supplied token to validate, so it doesn't violate the CSRF property this PR is hardening. This matches what @jamesfredley already flagged as a known, pre-existing, out-of-scope edge case in the 2026-07-16 comment. Not a blocker; could be a good small follow-up (e.g. fold the isEmpty()+removeAttribute into the same holder-level synchronized call, or just stop pruning the empty holder from the session since a LinkedHashMap with no entries is cheap).

Approving.

@borinquenkid
borinquenkid merged commit e929338 into 8.0.x Aug 6, 2026
109 of 110 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Apache Grails Aug 6, 2026
@borinquenkid
borinquenkid deleted the fix/synchronizer-token-hardening branch August 6, 2026 18:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants