Skip to content

Reduce per-request work, and rework hidden HTTP method and multipart handling - #16149

Merged
codeconsole merged 82 commits into
apache:8.0.xfrom
codeconsole:perf/request-path-8.0.x
Sep 9, 2026
Merged

codeconsole merged 82 commits into
apache:8.0.xfrom
codeconsole:perf/request-path-8.0.x

Conversation

@codeconsole

@codeconsole codeconsole commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

One PR covering the Grails 8 request path: per-request cost, hidden HTTP method handling, and multipart. This supersedes #16150, #16152 and #16183, which are merged in here with their history intact rather than squashed — they were interdependent enough that reviewing them separately meant tracking a merge order, which is not a reasonable thing to ask of a reviewer.

⚠️ This changes a default for every application on upgrade. See The hidden HTTP method filter is now off by default below, and in particular the authorization consequence, which is the one change here that fails silently. If the team would rather ship the property and defer the default flip to 9.0, that is a one-line change — say so and I will make it.

What is in here

1. Per-request work (was #16149)

Reduces allocation and repeated lookups across the request path: cached per-context collaborators, shared stateless interceptors, UrlPathHelper.defaultInstance instead of per-request instances, and a GrailsApplicationAttributes cached per servlet context rather than rebuilt per request. Benchmarks are in grails-benchmarks.

2. URL mapping names from the match (was #16150)

UrlMappingInfo resolves controller and action names from the match rather than re-reading request parameters.

3. Oversized uploads reach the application's error handling (was #16152, closes #16145)

Reading any parameter of a multipart/form-data request makes the container parse the body, and a body past the configured limit fails that parse inside the filter chain, where no HandlerExceptionResolver can see it. Worse, once part parsing has failed every later parameter read on that request fails too — including the reads the error handling itself performs.

Framework parameter reads now go through one tolerant helper, so the failure is left for checkMultipart to raise during dispatch where Spring routes it to the exception resolvers.

Container Before After
Tomcat 11 500, raw container HTML 413, handled by the application
Jetty 12 400, indistinguishable from a malformed request 413, handled by the application
Undertow 2.4 413, empty body unchanged — the limit is applied before any filter or servlet runs

4. request is always the outermost request (was #16149)

Grails used to substitute the resolved MultipartHttpServletRequest for the request it exposes, which discarded wrappers contributed by other filters. Multipart capability is now discovered by unwrapping, with an attribute for the case where the wrapper sits above the request Grails bound. GrailsWebRequest.getCurrentRequest() is deprecated and returns getRequest().

5. The hidden HTTP method filter is now off by default (was #16183)

Grails registered a servlet filter rewriting POST into PUT/PATCH/DELETE from a _method parameter or an X-HTTP-Method-Override header, ahead of the dispatcher and ahead of the Spring Security chain, with no way to turn it off.

Reading a request parameter before the dispatcher is not free: the container resolves the dispatcher's MultipartConfigElement at filter time, so reading _method on a multipart POST parses the whole body — writing its temporary files — before the request has been routed or authenticated. The filter is order -170; the security chain is -100. Spring Boot disabled its equivalent in 2.2 for the same reason.

The override is not lost. It moves into the dispatcher, resolved after multipart handling and after the filter chain, and published as a request attribute so allowedMethods and URL mapping resolution agree on the method. Restore the old behaviour with grails.web.hiddenmethod.filter.enabled: true.

Two supporting changes:

  • POST /$controller/$id → update is generated by a resources mapping. RestfulController has declared update: ['PUT', 'POST'] since #9926 — raised because AngularJS $resource and the clients modelled on it POST to the member URL to save an existing object — but no route was ever generated, so the permission has been unreachable. It is also what lets a form submit without a _method parameter.
  • <g:form method="PUT"> stops emitting _method, submitting a plain POST to the same URL. method="DELETE" still emits it, because delete and update share a URL. In the new default _method appears in exactly one place: a delete form.

The consequence to review before upgrading. Servlet filters and the Spring Security chain now see a form delete as a bare POST /books/1. A rule matching DELETE /books/** will no longer fire, and since the URL is unchanged, update and delete are not distinguishable by path either. This is the only change here that fails silently.

6. A startup failure new in 8.0

Boot's WebMvcAutoConfiguration registers its filter under the same hiddenHttpMethodFilter bean name, so spring.mvc.hiddenmethod.filter.enabled=true failed startup with a BeanDefinitionOverrideException. Grails' registration moved to its own auto-configuration ordered after Boot's, detecting Boot's filter rather than assuming it from a property — and contributing its own when Boot cannot, which is the case under @EnableWebMvc.

Review notes

  • Every commit from the superseded PRs is preserved; nothing was squashed or dropped.
  • Review feedback already addressed: @jdaugherty and @codeconsole on GrailsWebRequest, @sbglasius on CachedBean remembering a lookup miss, @matrei on the filter-mode flag being derived from only one of the two properties.

Documentation

grails-doc upgrade guide sections 52–54, and the REST guide's Linking to Resources page.

The request Grails exposed to controllers, tag libraries and GSPs was replaced
with the resolved MultipartHttpServletRequest for file uploads. That discarded
every request wrapper contributed after multipart resolution - the hidden HTTP
method filter, Spring Security, and any application filter - and required a
mutable pointer on GrailsWebRequest plus propagation code to maintain it.

The request is now always the outermost request, and multipart capabilities are
discovered from its wrapper chain via WebUtils.resolveMultipartRequest. When the
DispatcherServlet resolves a request Grails had already bound, the wrapper sits
above that request and cannot be reached by unwrapping, so it is also published
as a request attribute.

- Add WebUtils.resolveMultipartRequest and isMultipartContentType
- Add the MultipartRequest read surface to HttpServletRequestExtension so
  request.getFile(..) and friends keep working, failing loudly rather than
  returning null when the request is not a resolved multipart request
- Populate GrailsParameterMap through discovery rather than an instanceof check
- Replace GrailsWebRequest.setMultipartRequest and the multipart branch in
  getCurrentRequest with multipartRequestResolved, which only invalidates the
  cached params (apachegh-13837)
- Return the processed request from GrailsDispatcherServlet.checkMultipart, so
  the dispatch runs against it as Spring MVC expects
- Delete the unreachable multipart resolution in DefaultUrlMappingInfo, along
  with the undocumented grails.web.disable.multipart setting
- Make the SpringSecurityUtils multipart branch functional again; it read an
  attribute only the deleted DefaultUrlMappingInfo code ever wrote

request instanceof MultipartHttpServletRequest and casts to that type no longer
work; documented in the 8.0 upgrade guide.
isMultipartContentType had no production caller - only the test written for it.
Condense the six per-method javadoc blocks on the file upload accessors into one.
…ntext

GrailsWebRequest built a GrailsApplicationAttributes on every request, through a
reflective Constructor.newInstance. That object holds no request state - it caches
the beans its own comment calls "used very often" (template engine, GrailsApplication,
GroovyPagesUriService, MessageSource, plugin manager) - so building one per request
paid for the reflection and then discarded all five caches immediately.

It is now created on first use and cached in the servlet context, and rebuilt only
if the ApplicationContext it resolved against is no longer current, so a replaced or
restarted context (as happens between tests) is never served a stale instance. Its
lazily populated fields become volatile now that one instance is shared across
request threads.

Also stop allocating a UrlPathHelper per request or per call. Spring exposes
UrlPathHelper.defaultInstance and none of the four Grails instances were configured,
so they can share it.
…ceptors

UrlMappingsHandlerMapping.getHandlerExecutionChain re-implemented the loop from
AbstractHandlerMapping, so Grails-mapped requests silently missed whatever Spring
added to that method later. Currently that is the API version deprecation
interceptor, which means the Deprecation, Sunset and Link headers configured by
spring.mvc.apiversion.* were never emitted for a Grails-mapped request.

It now calls super and inserts the WebRequestInterceptors at the front, which
keeps the "OSIV must run first" ordering that motivated the override. The two
Grails interceptors are stateless, so they become shared instances instead of two
allocations per request, and the @CompileDynamic MappedInterceptor cast helper
goes away with the copied loop.

Also:
- Keep UrlMappingsHandlerMapping's own UrlPathHelper. UrlPathHelper.defaultInstance
  is read-only and that field is protected, so pointing it at the shared instance
  would break any subclass configuring it. It is a singleton bean, so there was no
  per-request allocation to save there anyway.
- Restore the previous LocaleContext in GrailsWebRequestFilter rather than clearing
  it, so a LocaleContext set by a filter outside Grails survives, matching Spring's
  own RequestContextFilter.
GrailsParameterMap's constructor defensively copied request.getParameterMap() into
a LinkedHashMap before walking it. updateNestedKeys only ever reads that map -
every put it makes goes into wrappedMap or a nested map it created - so the copy
was only ever needed to merge uploaded files in.

The servlet map (immutable per the servlet contract) is now walked directly, and
copied only when there are multipart files to merge, removing a map allocation and
a full entry copy per request for every non-upload request.
A URL mapping cache miss was the most expensive thing in the request path by three
orders of magnitude - 1964 ns for a URI only the default mapping serves, against
2.5 ns for a cache hit - because every miss ran a linear scan allocating a Matcher
for each of the ~56 compiled patterns in a mid-size application.

RegexUrlMapping now records each pattern's slash count at parse time and skips
patterns whose segment count rules them out. Every construct convertToRegex emits
is bounded to a single path segment except ".*", which comes only from a "**"
token, so a pattern without "**" can only match a URI with exactly its slash count
or one more, the extra one coming from the trailing "/??" every pattern ends with.
Patterns containing "**" are never skipped.

Candidates are skipped, never reordered, so the scan still returns the first
mapping that matches and declaration precedence is unchanged.

This replaces the patternByTokenCount map, which built exactly this index and was
never read by anything.

The holder computes the URI's slash count once per request rather than once per
mapping, and hoists the per-candidate LOG.isDebugEnabled() call out of the three
scan loops.
The adapter passed its callback to observe() as `{ -> i.before() } as BooleanSupplier`.
Groovy evaluates that coercion before entering observe(), so it ran even when the
ObservationRegistry is a no-op, and DefaultGroovyMethods.asType routes it through
CachedSAMClass.coerceToSAM to Proxy.newProxyInstance. Every matched interceptor
therefore cost a Closure, a Class[], a ConvertedClosure and a JDK dynamic proxy per
phase per request, with each callback dispatching reflectively through
ConversionHandler rather than calling the interceptor directly.

The phase is now a private enum that dispatches straight to before()/after(), so the
default path is a field read, a no-op check and an interface call. In the compiled
class groovy.lang.Reference references drop from 15 to 0 and the two closure classes
are gone. The observing path is structurally unchanged.

Also caches the logical interceptor name per class rather than recomputing it per
interceptor per phase per request, and reverses the matched-interceptor list in place
rather than copying it - the reversed list is stored back under the request attribute
and read by afterCompletion, so the ordering remains observable and unchanged.

Adds coverage for the observation path, which previously had none, including the
null-registry branch, the no-op registry branch, and error recording.
The controller AST transformer emitted the ALLOWED_METHODS_HANDLED request-attribute
guard twice into the same generated wrapper - once from convertToMethodAction and
again from wrapMethodBodyWithExceptionHandling - producing two byte-identical blocks
where the second could never do anything, because the first had already set the
attribute. It also emitted the guard, and its finally-block cleanup, for controllers
that declare no allowedMethods at all.

An action on a controller with no allowedMethods was paying four dynamic request
property gets, two getAttribute, a setAttribute, a removeAttribute and a compareEqual
per request for a guard that could never fire. Each request property get goes through
an indy callsite and RequestContextHolder, so this was not free.

The duplicate emission is removed, and the bookkeeping is now generated only for
controllers that declare a non-empty allowedMethods map. Gating it per action rather
than per controller looks equivalent but is not: the marker means "an action has
already begun handling this request" (apachegh-11444), so an unrestricted action must still
set it, or a restricted action it invokes programmatically starts rejecting the
request. Controllers that use allowedMethods generate byte-identical code to before.

Adds coverage for the command-object path, which had none.
…okup

Binding a command object resolved the DataBindingSourceRegistry, the MimeTypeResolver
and the GrailsWebDataBinder from the bean factory on every request, each with a
containsBean followed by a getBean, and did so twice because bindObjectToInstance
runs createDataBindingSource again. Holders.findApplication() is itself a getBean
rather than a field read, and was called twice more per bind.

These now resolve once per ApplicationContext, held in a single-entry volatile cache.
A map keyed by ApplicationContext would retain every context ever seen, since the
cached beans reference the context, so a single entry replaced whenever a different
context appears is both cheaper and the correct invalidation signal for dev restarts
and test contexts.

Separately, getBindingIncludeList used getDeclaredField to look up the AST-injected
whitelist field and cached the result after the call. For any class the transformer
did not touch - inner-class command objects, precompiled classes, plain POJOs - that
call threw, control jumped past the caching, and the exception was reconstructed on
every subsequent bind. It now uses ReflectionUtils.findField, which returns null, and
caches the negative result too, while still requiring the field to be declared on the
class itself so an untransformed subclass does not inherit its parent's whitelist.
…ing paths

Four lookups repeated per request, all resolving to values that are stable:

- Every redirect read the controller's static namespace field reflectively, through
  a hierarchy walk plus makeAccessible plus Field.get. The in-code comment already
  noted this was avoidable. Now cached per controller Class; a reloaded class is a
  different Class object, so a stale namespace cannot be served.
- Every redirect allocated a ResponseRedirector and called three setters on it. That
  object holds only configuration and takes the request, response and arguments per
  call, so one is now built lazily and reused. Each of its setters clears the cached
  instance, so a configuration change after the first redirect is still honoured.
- Every template render resolved CompositeViewResolver from the bean factory. It is
  now held in a field, matching how this trait already caches the plugin manager,
  mime utility and layout selector.
- The domain map constructor resolved the GrailsApplication and PersistentEntity,
  discarded them, then resolved both again to autowire the instance. They are now
  resolved once and passed down.

The redirector is held in an AtomicReference rather than a volatile field: Groovy's
trait field remapping drops the volatile modifier, and unlike the other cached values
this object is constructed here after its setters run, so it needs safe publication.
GrailsWebRequest.getCurrentRequest() returned the resolved MultipartHttpServletRequest
in place of the request Grails was bound to. That substitution is gone, so the method
is now literally `return getRequest();`.

The two can never disagree. getRequest() is final on Spring's ServletRequestAttributes
and fixed at construction, and nothing wraps or replaces the request for the lifetime of
a GrailsWebRequest: includes and forwards wrap only the response and dispatch the same
request object, layout decoration swaps the response and re-renders against the original
request, and async builds a new GrailsWebRequest around the request it is given. The two
places that do cope with a later request wrapper avoid this method entirely - multipart
through WebUtils.resolveMultipartRequest, and Spring Security by binding a fresh
DelegatingGrailsWebRequest.

All 65 framework call sites now use getRequest(). The method is deprecated rather than
deleted so plugins keep compiling; removing it is a separate decision.

- Move the "always the outermost request" note to the class javadoc, where it outlives
  the deprecated method
- Keep getCurrentRequest in DelegatingGrailsWebRequest's @DeleGate exclusions. Delegating
  it would hand back the request from earlier in the filter chain, which is what that
  filter exists to prevent. Both reasons the exclusion list exists are now written down
- Cover that filter with a spec; it had none
- Stop JsonViewTemplateResolverSpec mocking GrailsWebRequest and stubbing
  getCurrentRequest(). It relied on the deprecated method being the only stubbable
  request accessor and produced an object whose two accessors disagreed; it now drives a
  real GrailsWebRequest over a MockHttpServletRequest
Covers controller action invocation (with and without allowedMethods, and a
command-object action), the interceptor chain with a no-op and an observing
registry, and collectControllerMappings - the uncached wrapper that runs on every
request even when the URL mapping cache hits.

The existing benchmarks measured GrailsWebRequest construction (12 ns) and
multipart resolution (1.7 ns), neither of which is where request time goes.
getRequest() is final on ServletRequestAttributes, so getCurrentRequest() was the
only stubbable request accessor on GrailsWebRequest. Tests that mocked it will see
framework code take a different path now that it calls getRequest() directly.
@codecov

codecov Bot commented Aug 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.20536% with 129 lines in your changes missing coverage. Please review.
✅ Project coverage is 54.9148%. Comparing base (60515a5) to head (82b8648).
⚠️ Report is 83 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...rails/web/json/PathCapturingJSONWriterWrapper.java 0.0000% 30 Missing ⚠️
...ails/compiler/web/ControllerActionTransformer.java 14.7059% 27 Missing and 2 partials ⚠️
...g/grails/web/mapping/DefaultUrlMappingsHolder.java 60.0000% 5 Missing and 5 partials ⚠️
...y/org/grails/web/servlet/mvc/GrailsWebRequest.java 83.7209% 7 Missing ⚠️
...b/controllers/api/ControllersDomainBindingApi.java 75.0000% 3 Missing and 2 partials ⚠️
.../GrailsInterceptorHandlerInterceptorAdapter.groovy 80.9524% 0 Missing and 4 partials ⚠️
...roovy/grails/web/databinding/DataBindingUtils.java 91.6667% 3 Missing and 1 partial ⚠️
...sting/AbstractGrailsMockHttpServletResponse.groovy 0.0000% 3 Missing ⚠️
...eb/servlet/DefaultGrailsApplicationAttributes.java 80.0000% 3 Missing ⚠️
.../src/main/groovy/org/grails/web/util/WebUtils.java 85.7143% 2 Missing and 1 partial ⚠️
... and 25 more
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16149        +/-   ##
==================================================
+ Coverage     54.7242%   54.9148%   +0.1906%     
- Complexity      20532      20692       +160     
==================================================
  Files            2104       2108         +4     
  Lines          101149     101295       +146     
  Branches        17966      17986        +20     
==================================================
+ Hits            55353      55626       +273     
+ Misses          37775      37656       -119     
+ Partials         8021       8013         -8     
Files with missing lines Coverage Δ
...s/web/async/AsyncWebRequestPromiseDecorator.groovy 75.6098% <100.0000%> (ø)
.../src/main/groovy/grails/artefact/Controller.groovy 0.0000% <ø> (ø)
...act/controller/support/AllowedMethodsHelper.groovy 70.0000% <100.0000%> (ø)
...efact/controller/support/ResponseRedirector.groovy 0.0000% <ø> (ø)
...GrailsHiddenHttpMethodFilterAutoConfiguration.java 100.0000% <100.0000%> (ø)
...core/src/main/groovy/grails/config/Settings.groovy 100.0000% <ø> (ø)
.../web/gsp/io/GrailsConventionGroovyPageLocator.java 45.7143% <100.0000%> (ø)
...ovy/org/grails/gsp/jsp/GroovyPagesPageContext.java 64.1975% <100.0000%> (ø)
...roovy/org/grails/gsp/jsp/PageContextFactory.groovy 100.0000% <100.0000%> (ø)
...vy/org/grails/plugins/web/taglib/FormTagLib.groovy 76.4620% <ø> (ø)
... and 52 more

... and 5 files with indirect coverage changes

🚀 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.

The filter sets the locale from the request unconditionally, but restored the
previous LocaleContext only on the outermost dispatch. An include or forward
therefore left the enclosing request with the locale it had installed, and replaced
any TimeZoneAwareLocaleContext with a plain SimpleLocaleContext for the remainder
of that request.

The restore now happens on every invocation, matching the unconditional set. Only
the GrailsWebRequest handling stays branched, since an include restores the previous
web request rather than clearing it.

This filter had no test coverage; adds one, including a case that fails without the
change.
…8.0.x

Upstream landed the mass-assignment hardening (apache#15947) and the clearMissing
work (apache#15950), both of which rewrote the DataBindingUtils methods this branch
had touched in "Cache the data binding collaborators and the databinding
whitelist lookup". The conflict is resolved in favour of upstream everywhere
the two overlap, so that the deny-by-default binding behaviour is exactly the
one upstream shipped.

Superseded by upstream and dropped from this branch:

* The whitelist include-list caching in getBindingIncludeList. Upstream's
  rewrite already caches the negative result behind a NO_BINDING_INCLUDE_LIST
  sentinel and resolves the runtime bindable names only on a cache miss, and it
  keys the cache on whether deny-by-default is enabled, which this branch's
  single cache could not express. The method is taken from upstream verbatim.

* The resolveBindingIncludeList helper. Upstream's getField / getPairedField /
  getStaticListFieldValue replace it and fix the same defect: the lookup no
  longer lets getDeclaredField throw for a class the AST transform never
  enhanced, so nothing is owed here any more. The helper also honoured only a
  whitelist declared on the class itself, whereas upstream deliberately walks
  the superclass chain, so DataBindingUtilsSpec now asserts that an inherited
  whitelist applies. Its test of the private include-list cache is dropped: the
  negative result is still covered through the public binding API, and upstream
  now keeps two caches rather than the one the test reached into.

Kept from this branch:

* The ContextBoundBeans cache of the data binding collaborators, which upstream
  does not touch.

* Resolving the GrailsApplication once per bind and passing it down. It now
  travels through a private bindObjectToDomainInstance overload which runs
  upstream's include normalisation, so the include.isEmpty() /
  NO_BINDABLE_PROPERTIES handling and the clearMissing && explicitInclude
  gating apply on every path, including bindToCollection.
…er tests

Holders keeps its application discovery strategies in a static list and consults them in
registration order, and tests share a JVM fork. The spec registered its own strategy but did
not clear the list first, so a strategy left behind by an earlier test - holding an application
context that had since been closed - was asked first and threw IllegalStateException before the
spec's strategy was reached.

Clearing in setup as well as cleanup makes the spec independent of whatever ran before it.
@codeconsole
codeconsole requested review from jamesfredley, jdaugherty and matrei and removed request for jdaugherty and matrei August 15, 2026 21:53

@matrei matrei 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.

Review Round 2 — Mergeable

Current head: 533f7e2cfb (branch codeconsole/perf/request-path-8.0.x).

The three findings from the previous round are addressed, and the new work adds a
real security fix and end-to-end coverage. I would merge.

Previous P1/P2 findings — all resolved

P1a — Command-object and request-body binding read the effective method

Both call sites now go through HiddenHttpMethod.effectiveMethod(request):

  • grails-controllers/src/main/groovy/grails/artefact/Controller.groovy:416
  • grails-web-databinding/src/main/groovy/org/grails/web/databinding/bindingsource/AbstractRequestBodyDataBindingSourceCreator.groovy:51

AbstractRequestBodyDataBindingSourceCreatorSpec now asserts a POST naming
DELETE leaves the body unbound while a plain POST still binds
(AbstractRequestBodyDataBindingSourceCreatorSpec.groovy:122-143). The
command-object branch is only reachable with a GORM-backed domain, so it is
covered by the rule and the upgrade note rather than by a test.

P1b — Dispatcher override across forwards/includes

The fix picks the opposite of what the previous comment suggested — instead of
clearing the attribute for internal dispatches, it now honours the published
override wherever it applies and refuses only to derive a fresh one from
inherited parameters
(UrlMappingsHandlerMapping.groovy:91-109). This aligns dispatcher mode with the
servlet filter, whose request wrapper reports the overridden method for the
whole request. It is a defensible choice and is documented in the method's
Javadoc. Both readers agree during an internal dispatch:

  • an override the dispatcher resolved survives an internal dispatch
    (HiddenHttpMethodHandlerMappingSpec.groovy:97-114) drives a forward and an
    include and asserts both the mapping and HiddenHttpMethod.effectiveMethod
    return PUT.
  • the parameter does not select a route for an internal dispatch still holds
    when no override was published (.groovy:81-95).

P2 — Multipart branch in SpringSecurityUtils.isAjax()

Now reads through the tolerant helper:
SpringSecurityUtils.groovy:313 → WebUtils.readParameter(multipart, 'ajax'),
whose readTolerantly swallows RuntimeException on multipart requests and
returns the fallback (WebUtils.java:646-666). The isAjax-specific test with a
throwing multipart wrapper the previous comment asked for is not present, but
the behaviour is exercised by WebUtilsSpec (the parameter reads yield their fallback when a multipart body cannot be parsed).

New work in this round — worth calling out

  • Security parity fix (ReflectionUtils.matchAllUrlMappings, a39a350) —
    Spring Security's URL matching now resolves _method before matching so
    authorization applies to the action the dispatcher will actually run. This
    closes a real gap: on this branch a POST /book/1 with _method=DELETE was
    authorized against update and then executed as delete. Covered by two new
    cases in ReflectionUtilsSpec.groovy:224-263. The framework invariant that
    either the filter rewrites the method or dispatcher-mode resolves it
    (UrlMappingsGrailsPlugin.groovy:130 + GrailsHiddenHttpMethodFilterAutoConfiguration)
    keeps this safe — reading _method here cannot select a route the dispatcher
    will not execute.

  • ALLOWED_METHODS_HANDLED now written by every action
    (ControllerActionTransformer.java:530-580)
    — Fixes a 405 mid-request when
    an unrestricted controller forwards into a restricted action in another
    controller. The compile-time optimisation of skipping the attribute for an
    unrestricted controller was unsafe: the reader is in whichever controller is
    entered second. Existing coverage exercises intra-controller forwarding
    (ControllerActionTransformerAllowedMethodsSpec); a cross-controller forward
    from an unrestricted controller to a restricted one is not directly asserted,
    but the change is a uniform simplification and the behaviour rests on the
    attribute contract.

  • GrailsWebRequest.setMultipartRequest restored as a deprecated shim
    (GrailsWebRequest.java:186-192)
    — Backwards-compat for external callers,
    bridges to MULTIPART_HTTP_SERVLET_REQUEST_ATTRIBUTE publication.

  • WebUtils.readTolerantly distinguishes expected vs unexpected multipart
    failures (WebUtils.java:646-666)
    — MultipartException at DEBUG,
    everything else at WARN. Improves observability without changing behaviour.

  • End-to-end RequestPathSpec — Drives the whole chain (filter chain,
    multipart resolution, dispatcher override, mapping, allowedMethods, params,
    command binding, response) in one round trip for six cases. This is the test
    the earlier rounds kept asking for.

Minor observations (non-blocking)

  • RequestPathController defines forwarding and forwarded actions
    (RequestPathController.groovy:55-61) that no spec exercises. Either add a
    forward-through-override case to RequestPathSpec or drop the two actions.
    A functional test asserting the forward case would strengthen coverage of the
    P1b design decision (that a forward inherits the resolved override) in a
    running container.
  • No isAjax-specific spec covers a multipart wrapper that throws from
    getParameter(). The tolerance is covered by WebUtilsSpec, so this is
    optional.
  • The ALLOWED_METHODS_HANDLED cross-controller forward scenario (unrestricted
    → restricted, in different controllers) is described in the commit message
    but not asserted by a test. The uniform rule the commit installs makes this
    hard to regress accidentally.

Verdict

Mergeable. The security bypass fix in particular is worth landing; the
end-to-end spec closes the long-standing "test the whole path together" ask; the
design of the effective-method rule now agrees across every reader.

@matrei
matrei self-requested a review September 7, 2026 09:36
Review approved the branch with three observations. Two are worth a test.

RequestPathController carried a forwarding action and the action it forwarded to,
and no spec drove either. Rather than drop them, they now assert the design
decision made in the previous round: an override the dispatcher resolved is
honoured for an internal dispatch, instead of being cleared for one. The forward
goes to the member URL rather than naming an action, so the mappings route it and
the response reports which method they matched on - delete for a POST naming
DELETE, update for the same POST without it. That is the servlet filter's
behaviour, whose wrapper reports the overridden method for the whole request, and
it was previously asserted only against a mock.

The second case is a forward from a controller restricting nothing into an action
of another controller that restricts to DELETE. It is admitted, because the first
action recorded that it had begun handling the request. That is the contract
restored earlier this round, and the cross-controller shape is the one it exists
for, since a controller cannot see from itself whether some later one will read
the record.

The third observation asked for an isAjax test with a multipart wrapper that
throws. Written, and then removed: it passes against the direct read it was meant
to catch, so the branch is not reached under the unit test harness and the test
asserts nothing. Review marked it optional and noted the tolerance is covered by
WebUtilsSpec, which is where it stays. A test that cannot fail is worse than none.
Three things review pointed at, none of which had a reason to be there.

ControllersAutoConfigurationSpec kept a hiddenMethodContextRunner helper with no
callers - a fixture for tests that ended up written another way.

FormTagLib.setConfiguration carried @GrailsCompileStatic, where the rest of that
file uses plain @CompileStatic and 8.0.x annotates the method not at all. It
arrived with the trait field cache this branch added and then removed, the same
way the explicit getGrailsLinkGenerator() call did. The method now differs from
8.0.x by nothing, so the annotation and its import go with it.

The upgrade note called the move from getCurrentRequest() to getRequest() a
rename. It is not: getRequest() has always been on Spring's
ServletRequestAttributes. What changed is that getCurrentRequest() no longer
returns anything different from it, so the note says that instead.
@codeconsole

Copy link
Copy Markdown
Contributor Author

Thanks. Inline comments answered on their threads; the three review observations are in c8bbcb8.

Unexercised forward actions — kept and put to work rather than dropped, since they cover the P1b decision in a running container. The forward now targets the member URL instead of naming an action, so the mappings route it: delete for a POST naming DELETE, update for the same POST without it.

Cross-controller ALLOWED_METHODS_HANDLED — added. A new RequestPathForwarderController restricts nothing and forwards into the DELETE-only delete; it is admitted because the first action recorded that it began handling.

isAjax multipart test — written, then removed. It passed against the direct multipart?.getParameter('ajax') read it was meant to catch, so the branch is not reached under that harness and it asserted nothing. WebUtilsSpec keeps the coverage.

RequestPathSpec is nine cases now.

@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 a -1 on merging this until the getCurrentRequest() deprecation is removed. This API has been there since the inception of Grails and I disagree with the removal. I'm ok leaving the renames.

The API has been there since the inception of Grails, and review is against
retiring it. Only the annotation goes; the method is unchanged, and so is
everything else this branch did around it.

It still returns what getRequest() returns, because the multipart substitution
that used to make the two differ is gone. Framework code still calls getRequest()
directly - the renames stay - and that is now a matter of the framework picking
one of two accessors that answer identically, not of steering anyone off this
one.

The spec asserted the annotation was present. It asserts the behaviour instead:
the two accessors hand back the same object. Upgrade note 54.5 says the same, in
place of telling readers to move off the method.
@codeconsole

Copy link
Copy Markdown
Contributor Author

Done in 5fa7a5e - the @Deprecated is off getCurrentRequest() and nothing else changed. The renames stay, as you said.

The method still returns what getRequest() returns, since the multipart substitution that used to make the two differ is gone; that is now just two accessors answering identically rather than one being steered away from. The spec asserted the annotation was present, so it asserts the behaviour instead, and upgrade note 54.5 says the two are the same object rather than telling readers to move off it.

setMultipartRequest(..) keeps its deprecation - that is the shim you asked for in the earlier round, where the method had been removed outright.

@codeconsole
codeconsole merged commit 4351078 into apache:8.0.x Sep 9, 2026
19 of 22 checks passed
@testlens-app

testlens-app Bot commented Sep 9, 2026

Copy link
Copy Markdown

🚨 TestLens detected 2 failed tests 🚨

Here is what you can do:

  1. Inspect the test failures carefully.
  2. If you are convinced that some of the tests are flaky, you can mute them below.
  3. Finally, trigger a rerun by checking the rerun checkbox.

Test Summary

SiteMesh 2 Compatibility / SiteMesh 2 Functional Tests (Java 21, indy=false) > :grails-test-examples-app1:integrationTest

Test Runs Flakiness
AsyncPromiseSpec > async service processes string input ❌ 1% 🟡
AsyncPromiseSpec > conditional async uses sync mode when requested ❌ 1% 🟡

🏷️ Commit: 82b8648
▶️ Tests: 66066 executed
🟡 Checks: 67/88 completed

Test Failures

AsyncPromiseSpec > async service processes string input (:grails-test-examples-app1:integrationTest in SiteMesh 2 Compatibility / SiteMesh 2 Functional Tests (Java 21, indy=false))
java.net.http.HttpTimeoutException: request timed out
	at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:953)
	at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:133)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.send(HttpClientSupport.groovy:1133)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.send(HttpClientSupport.groovy:1122)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.http(HttpClientSupport.groovy:203)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.http(HttpClientSupport.groovy:169)
	at functionaltests.async.AsyncPromiseSpec.async service processes string input(AsyncPromiseSpec.groovy:139)
AsyncPromiseSpec > conditional async uses sync mode when requested (:grails-test-examples-app1:integrationTest in SiteMesh 2 Compatibility / SiteMesh 2 Functional Tests (Java 21, indy=false))
java.net.http.HttpTimeoutException: request timed out
	at java.net.http/jdk.internal.net.http.HttpClientImpl.send(HttpClientImpl.java:953)
	at java.net.http/jdk.internal.net.http.HttpClientFacade.send(HttpClientFacade.java:133)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.send(HttpClientSupport.groovy:1133)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.send(HttpClientSupport.groovy:1122)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.http(HttpClientSupport.groovy:203)
	at org.apache.grails.testing.http.client.HttpClientSupport$Trait$Helper.http(HttpClientSupport.groovy:169)
	at functionaltests.async.AsyncPromiseSpec.conditional async uses sync mode when requested(AsyncPromiseSpec.groovy:280)

Rerun Controls

Note

Checks are currently running using the configuration below.

Select tests to mute in this pull request:

🔲 AsyncPromiseSpec > async service processes string input
🔲 AsyncPromiseSpec > conditional async uses sync mode when requested

Reuse successful test results:

🔲 ♻️ Only rerun the tests that failed or were muted before

Click the checkbox to trigger a rerun:

🔲 Rerun jobs


Learn more about TestLens at testlens.app/docs.

matrei added a commit to gsartori/grails-core that referenced this pull request Sep 17, 2026
Resolves the conflicts with apache#16149 and moves what that PR added over to
the Spring Boot multipart properties:

- ControllersAutoConfiguration: keep the Environment-aware dispatcherServlet
  bean from apache#16149, drop the Grails MultipartConfigElement bean.
- Upgrade guide §53.1 and its Undertow note now name
  spring.servlet.multipart.* and Boot's 1MB / 10MB defaults, and link to the
  new §4.2 migration section.
- THREAT_MODEL.md keeps the P10 XXE property next to the reworded P9.
- The oversized-upload specs in the app1, app4, jetty and undertow example
  apps relied on the old 128000-byte default. Those apps now configure
  spring.servlet.multipart limits so the 200000-byte payload still trips
  the limit, and the spec labels say so.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
antobinary added a commit to antobinary/bigbluebutton that referenced this pull request Sep 23, 2026
Apache Grails published 8.0.0-RC1 on 2026-09-23. Like M6 before it, the
artifacts are in the ASF staging group only while the release vote runs,
so the TEMP staging-repository entries in build.gradle stay for now and
the comments are retargeted at RC1. Spring Boot stays at 4.1.1 (RC1's BOM
manages the same version); Groovy follows the BOM to 5.1.3 and the
cloud.wondrify asset-pipeline plugin to its 5.2.0-RC1 release, which is
already on Maven Central.

The RC1 Grails Gradle plugin is built against Gradle 9.7
(apache/grails-core#16114): on the 9.6.0 wrapper `gradlew assemble` dies
with NoSuchMethodError on
GroovyCompileOptions.getConfigurationScriptFile() returning a
RegularFileProperty. Move the wrapper to 9.7.1, the current release.

RC1 hands multipart handling to Spring Boot's auto-configuration
(apache/grails-core#16040): the grails.controllers.upload.maxFileSize /
maxRequestSize keys are gone, and an application that still sets them
aborts at startup with a migration message. Move bbb-web's limits to
spring.servlet.multipart.max-file-size / max-request-size with the same
values. Without an explicit setting, Boot's defaults (1 MB per file,
10 MB per request) would silently cap presentation and caption uploads;
BigBlueButton's own per-presentation cap (maxFileSizeUpload, enforced by
ParamsProcessorUtil) is unchanged.

Also in RC1 (apache/grails-core#16149) the _method override moved from a
servlet filter into the dispatcher and is off by default, so the disabled
hiddenHttpMethodFilter registration in resources.groovy is now redundant.
It still compiles and stays inert, so it is left alone here.

Verified with a package build in the grails-8 build image, deployed to a
4.0 dev container: startup in 4.4 s without warnings, checksummed
create/getMeetingInfo/end round-trip, a 5.3 MB presentation upload
through the client (above Boot's default per-file limit), and the api,
learningdashboard, presentation and parameters Playwright suites. Every
remaining failure in those suites reproduces with the same signature on
the pre-upgrade Grails 7.0.12 package (screenshot drift, the @flaky
external-video tests, a test needing maskTagThreshold > 0, and the
predefined breakout groups tests).
antobinary added a commit to bigbluebutton/bigbluebutton that referenced this pull request Oct 26, 2026
e9d0534 registered a disabled HiddenHttpMethodFilter in
resources.groovy. On Grails 7 that was the way to turn the filter off:
Grails registered it unconditionally, and a bean with the same name
replaced it. Since #25466 bbb-web runs on Grails 8, whose auto
configuration registers the filter only when
grails.web.hiddenmethod.filter.enabled or
spring.mvc.hiddenmethod.filter.enabled is true, and both default to
false (apache/grails-core#16149). The bean now disables a filter that is
never registered.

The registration and its two imports go, and application.properties
sets grails.web.hiddenmethod.filter.enabled=false, so the filter stays
off by configuration rather than by a framework default. Grails 8 still
resolves a _method parameter on POST requests to PUT, PATCH or DELETE
in the dispatcher; bbb-web maps none of those methods, so such a
request falls through to the index action like any other unmapped one.

This must not be merged into a line that is still on Grails 7, where
the bean is what keeps the filter off.

Part of #26002.
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.

[Grails 8] Oversized multipart uploads cannot be handled by Grails application code

5 participants