Skip to content

fix(core): let middleware exclusions cover prefix-excluded routes - #18209

Merged
kamilmysliwiec merged 3 commits into
nestjs:masterfrom
thekhegay:fix/middleware-exclude-prefix-excluded
Oct 21, 2026
Merged

kamilmysliwiec merged 3 commits into
nestjs:masterfrom
thekhegay:fix/middleware-exclude-prefix-excluded

Conversation

@thekhegay

Copy link
Copy Markdown
Contributor

PR Checklist

PR Type

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

My app keeps health endpoints outside of api prefix and runs auth middleware on everything else:

app.setGlobalPrefix('api', { exclude: ['health', 'health/ready'] });

consumer
  .apply(AuthMiddleware)
  .exclude('health', 'health/(.*)')
  .forRoutes('*path');

On 11.1 with Fastify this worked, only becuse wildcard middleware never ran on routes excluded from prefix (#17377 fixed that side)

With same setup on 12.2 GET /health/ready gets 401 from auth middleware, and Express has same hole on every version. Listing health/ready literally in exclude() works

exclude() resolves each entry with extractPathFrom(), which drops prefix only when entry itself is excluded from it - health/(.*) is not, so it becomes /api/health/{*path} while router serves health/ready at /health/ready. Same with health/{*path} and health/:check

enableCsrfProtection({ exclude }) resolves entries same way, so webhooks/*path does not cover webhooks/stripe excluded from prefix and cross-site POST there gets 403

What is the new behavior?

Exclusion also covers routes excluded from prefix that it matches, at paths where router serves them

New extractExclusionsFrom() in RouteInfoPathExtractor builds on extractExcludedRoutesCoveredBy() from fffdaf9, so exclude() follows same rule forRoutes() got there. CSRF resolveExclusions() uses it too, its docblock already says it resolves "like MiddlewareConsumer.exclude() does"

Only static excluded routes count, plus controller root that reports/{*path} takes out of prefix (exclude('reports') now skips /reports). health/(.*) still does not cover /health itself, as after 7b01d0e

Method of excluded route is kept, so { path: 'webhooks/:provider', method: GET } does not cover POST-only webhooks/stripe

New unit specs for extractExclusionsFrom() and both callers plus e2e in middleware-global-prefix-exclude.spec.ts (express and fastify) and csrf-protection.spec.ts fail on master and pass with fix

Does this PR introduce a breaking change?

  • Yes
  • No

Middleware is now skipped on prefix-excluded routes that exlusion pattern already matches by name, like #17950 did for HEAD. Literal exclusions and routes under prefix are unchanged

Other information

@micalevisk
micalevisk self-requested a review October 20, 2026 20:17

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

Thanks for the thorough write-up. The approach follows the rule fffdaf9 set for forRoutes(), keeps the method of the excluded route, and keeps the parent-route behaviour from 7b01d0e. I checked that the new unit and e2e specs fail on master and pass on this branch, on both Express and Fastify.

One blocking issue, below and inline.

Blocking: the coverage check is case-insensitive, so exclusions stop being exact

extractExcludedRoutesCoveredBy() compiles the exclusion with the path-to-regexp defaults, which ignore case. That is fine for forRoutes(), where a looser match only runs the middleware more often. An exclusion does the opposite: it skips the middleware or the CSRF check. So the coverage test has to be as strict as the match the same exclusion gets under the prefix.

Repro, same result on Express and Fastify:

app.setGlobalPrefix('api', { exclude: ['webhooks/stripe'] });
app.enableCsrfProtection({
  exclude: [{ path: 'WEBHOOKS/*path', method: RequestMethod.POST }],
});

// cross-site POST /webhooks/stripe     -> master: 403, this PR: 201
// cross-site POST /api/webhooks/github -> 403 on both, the exclusion is case-sensitive

The CSRF docs promise "Matching is case-sensitive", and compileExclusion() enforces it for every other path. Middleware has the same gap on a case-sensitive router: on Fastify, exclude('HEALTH/:check') with health/ready excluded from the prefix now skips the middleware on GET /health/ready, while it still runs on GET /api/health/1.

Suggested fix: let the callers pass the case sensitivity down to the coverage check, and keep the current default for forRoutes():

// route-info-path-extractor.ts
public extractExcludedRoutesCoveredBy(
  { path, method, version }: RouteInfo,
  { caseSensitive = false }: { caseSensitive?: boolean } = {},
): RouteInfo[] {
  // ...
  routeRegex = pathToRegexp(
    LegacyRouteConverter.tryConvert(addLeadingSlash(path), { logs: false }),
    { sensitive: caseSensitive },
  ).regexp;
  • MiddlewareBuilder passes the router's setting, read the way filterMiddleware() reads it: getRouteMatchingOptions?.()?.caseSensitive ?? true.
  • CrossOriginProtection.resolveExclusions() always passes true.

Please add a mis-cased exclusion to the unit specs of both callers so this stays pinned.

Non-blocking

  • Docs follow-up. content/security/csrf.md says the global prefix "is added, unless the route is excluded from it", which no longer describes the resolution fully. The "Excluding routes" section of content/middlewares.md says nothing about the global prefix. A short note in both, in nestjs/docs.nestjs.com, would help. It can be a separate PR.

Co-authored-by: Micael Levi L. Cavalcante <micalevisk@gmail.com>
@thekhegay
thekhegay force-pushed the fix/middleware-exclude-prefix-excluded branch from b48732a to 1141385 Compare October 21, 2026 06:30
@thekhegay

Copy link
Copy Markdown
Contributor Author

good catch, thanks. pushed 1141385 with your sketch (and you as co-author): middleware passes router's caseSensitive (?? true like filterMiddleware()), CSRF always passes true
mis-cased exclusion is in unit specs of both callers now, both fail without fix
docs note for csrf.md and middlewares.md I'll send as sepparate PR in docs repo

extractExclusionsFrom() defaulted to case-insensitive matching, so a caller that left the option out would cover more routes than the router serves.
@kamilmysliwiec
kamilmysliwiec merged commit aa18d39 into nestjs:master Oct 21, 2026
4 checks passed
@thekhegay
thekhegay deleted the fix/middleware-exclude-prefix-excluded branch October 21, 2026 09:17
ttt43ttt pushed a commit to NoDevelopers/ts-monorepo that referenced this pull request Nov 22, 2026
| datasource | package                  | from   | to     |
| ---------- | ------------------------ | ------ | ------ |
| npm        | @nestjs/common           | 12.2.0 | 12.3.1 |
| npm        | @nestjs/core             | 12.2.0 | 12.3.1 |
| npm        | @nestjs/platform-express | 12.2.0 | 12.3.1 |


## [v12.3.1](nestjs/nest@v12.3.0...v12.3.1)



## [v12.3.0](https://github.com/nestjs/nest/releases/tag/v12.3.0)

#### v12.3.0 (2026-10-27)

##### Features

- `platform-node`
  - [#18063](nestjs/nest#18063) feat(node): add a native node http platform adapter ([@kamilmysliwiec](https://github.com/kamilmysliwiec))

##### Bug fixes

- `common`
  - [#18289](nestjs/nest#18289) fix(common): report the detected file type in file type errors ([@DenisCDev](https://github.com/DenisCDev))
  - [#18246](nestjs/nest#18246) fix(common): avoid throwing for arrow prototype constructors ([@fengxueweilai](https://github.com/fengxueweilai))
  - [#18220](nestjs/nest#18220) fix(common): abort the response when a streamable file fails midway ([@thekhegay](https://github.com/thekhegay))
- `core`
  - [#18276](nestjs/nest#18276) fix(core): run middleware once for routes that differ only in version ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18262](nestjs/nest#18262) fix(core): tolerate sse request sockets without tuning methods ([@SnowingFox](https://github.com/SnowingFox))
  - [#18252](nestjs/nest#18252) fix(core): read the url protocol from the server ([@thekhegay](https://github.com/thekhegay))
  - [#18254](nestjs/nest#18254) fix(core): name the array and index of undefined module entries ([@thekhegay](https://github.com/thekhegay))
  - [#18235](nestjs/nest#18235) fix(core): discover classes by each of their discovery decorators ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
  - [#18216](nestjs/nest#18216) fix(core): read the abort on error option of the app being called ([@thekhegay](https://github.com/thekhegay))
  - [#18209](nestjs/nest#18209) fix(core): let middleware exclusions cover prefix-excluded routes ([@thekhegay](https://github.com/thekhegay))
  - [#18210](nestjs/nest#18210) fix(core): honor abortOnError passed to select() ([@Cayan](https://github.com/Cayan))
  - [#18215](nestjs/nest#18215) fix(core): subscribe to handler observables from other rxjs copies ([@koreahghg](https://github.com/koreahghg))
  - [#18201](nestjs/nest#18201) fix(core): read a quoted media type version in the middleware exclusions ([@hktitof](https://github.com/hktitof))
  - [#18200](nestjs/nest#18200) fix(core): resolve request-scoped forward refs for concurrent requests ([@maxymlyskov](https://github.com/maxymlyskov))
- `common`, `microservices`, `platform-ws`
  - [#18285](nestjs/nest#18285) fix(ws,microservices): load packages where bundlers can see them ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `common`, `microservices`, `websockets`
  - [#18272](nestjs/nest#18272) fix(common): keep one route param per argument in an overriding method ([@maxymlyskov](https://github.com/maxymlyskov))
- `platform-express`
  - [#18264](nestjs/nest#18264) fix(express): map unsupported multipart content types to 415 ([@seren-wib](https://github.com/seren-wib))
  - [#18234](nestjs/nest#18234) fix(express): end a head response for an empty streamable file ([@spokodev](https://github.com/spokodev))
  - [#18232](nestjs/nest#18232) fix(express): leave 5xx http-errors errors unmapped so they are logged ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18214](nestjs/nest#18214) fix(platform-express): map http-errors exceptions to HttpException in Express adapter ([@okxint](https://github.com/okxint))
  - [#18199](nestjs/nest#18199) fix(express): send the standard body for an exception wrapping an error ([@KAPUIST](https://github.com/KAPUIST))
- `platform-fastify`
  - [#18253](nestjs/nest#18253) fix(fastify): send object error bodies with a json content type ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18240](nestjs/nest#18240) fix(fastify): leave 5xx fastify errors unmapped so they are logged ([@thekhegay](https://github.com/thekhegay))
  - [#18239](nestjs/nest#18239) fix(fastify): map 4xx http-errors errors to http exceptions ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18226](nestjs/nest#18226) fix(fastify): listen on a file descriptor ([@thekhegay](https://github.com/thekhegay))
  - [#18217](nestjs/nest#18217) fix(fastify): run cors before nest middleware ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `core`, `platform-express`, `platform-fastify`, `platform-socket.io`, `platform-ws`, `websockets`
  - [#18251](nestjs/nest#18251) fix(core,express,fastify,ws,socket.io): load adapters with an older core ([@thekhegay](https://github.com/thekhegay))
- `microservices`
  - [#18250](nestjs/nest#18250) fix(microservices): re-arm the redis retries on a new listen ([@hktitof](https://github.com/hktitof))
  - [#18255](nestjs/nest#18255) fix(microservices): report a nats connection that gave up reconnecting ([@thekhegay](https://github.com/thekhegay))
  - [#18249](nestjs/nest#18249) fix(microservices): do not emit a trailing null to kafka requesters ([@thekhegay](https://github.com/thekhegay))
  - [#18256](nestjs/nest#18256) fix(microservices): let a retriable exception keep travelling ([@hktitof](https://github.com/hktitof))
  - [#18238](nestjs/nest#18238) fix(microservices): retry the tcp server again after close and listen ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
  - [#18223](nestjs/nest#18223) fix(microservices): clear the tcp retry timer when a new listen starts ([@hktitof](https://github.com/hktitof))
  - [#18221](nestjs/nest#18221) fix(microservices): honor mqtt topic filter boundaries ([@fabric0de](https://github.com/fabric0de))
  - [#18229](nestjs/nest#18229) fix(microservices): let only the exact message handler answer a request ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18211](nestjs/nest#18211) fix(microservices): fail the request when its last reply cannot be sent ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18206](nestjs/nest#18206) fix(microservices): reset the tcp retry attempts on each listen ([@hktitof](https://github.com/hktitof))
  - [#18204](nestjs/nest#18204) fix(microservices): count every failed rmq connection attempt ([@maxymlyskov](https://github.com/maxymlyskov))
  - [#18197](nestjs/nest#18197) fix(microservices): send the record headers of nats as message headers ([@hktitof](https://github.com/hktitof))

##### Dependencies

- `platform-express`
  - [#18268](nestjs/nest#18268) fix(deps): update dependency multer to v2.5.0 \[security] ([@renovate\[bot\]](https://github.com/apps/renovate))
- `common`
  - [#18257](nestjs/nest#18257) fix(deps): update dependency file-type to v22.2.0 ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- `platform-fastify`
  - [#18219](nestjs/nest#18219) fix(deps): update dependency [@fastify/middie](https://github.com/fastify/middie) to v9.3.6 ([@renovate\[bot\]](https://github.com/apps/renovate))

##### Committers: 16

- Abdellatif Anaflous ([@hktitof](https://github.com/hktitof))
- Daniel Pinto ([@Cayan](https://github.com/Cayan))
- Denis Scarabelli ([@DenisCDev](https://github.com/DenisCDev))
- Junpei Zhang ([@pei711](https://github.com/pei711))
- Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec))
- Luke Son ([@KAPUIST](https://github.com/KAPUIST))
- Maksym Lyskov ([@maxymlyskov](https://github.com/maxymlyskov))
- Om Bhandwaldar ([@OmBhandwaldar](https://github.com/OmBhandwaldar))
- Roman Khegay ([@thekhegay](https://github.com/thekhegay))
- Spoko Dev ([@spokodev](https://github.com/spokodev))
- [@fengxueweilai](https://github.com/fengxueweilai)
- [@okxint](https://github.com/okxint)
- snowingfox ([@SnowingFox](https://github.com/SnowingFox))
- yooseong ([@seren-wib](https://github.com/seren-wib))
- 김정현 (Kim JungHyeon) ([@fabric0de](https://github.com/fabric0de))
- 한국 ([@koreahghg](https://github.com/koreahghg))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants