Skip to content

fix(core): reject URL patterns with several placeholders in one segment - #3303

Merged
ascorbic merged 8 commits into
mainfrom
fix/url-pattern-redos
Sep 27, 2026
Merged

ascorbic merged 8 commits into
mainfrom
fix/url-pattern-redos

Conversation

@ascorbic

Copy link
Copy Markdown
Member

What does this PR do?

Fixes a ReDoS in public URL routing. compileUrlPattern turns every collection url_pattern placeholder into ([^/]+), and resolveEmDashPath matches anonymous request paths against the result. When a pattern puts several placeholders in one path segment (/{a}{b}{c}{d}{e}x), the regex can split that segment in a huge number of ways. Before this change, one 200-character path took ~8 s to match. Anyone with schema access can set such a pattern through the normal collection create/update APIs.

Putting a literal between the placeholders doesn't help, because [^/]+ also matches the literal. For example, /{a}-{b}-{c}x takes 170 ms on a 1,000-character path and grows polynomially. This PR therefore uses a stricter rule: at most one placeholder per path segment. Each group can then only backtrack inside its own segment against a fixed-length literal, so matching is linear. An adversarial review pass measured 0.1–1.4 ms on 20k–60k-character paths.

Where the rule is enforced:

  • compileUrlPattern throws URL patterns allow only one placeholder per path segment.
  • The zod create/update bodies (REST and the MCP schema_update_collection tool) now show that message instead of a generic "Invalid URL pattern".
  • SchemaRegistry.createCollection / createSeedCollection reject such patterns with SchemaError INVALID_URL_PATTERN. updateCollection rejects them only when the pattern changes.
  • validateSeed rejects them, so a seed fails before anything is written.
  • The admin collection editor shows the error under the URL Pattern field and disables Save.

Existing stored patterns: resolveEmDashPath now skips a stored pattern that fails to compile and console.warns once per cache build, rather than throwing on every request. Before this change, any stored pattern that failed to compile (for example, one with a stray brace) broke routing for every collection. Outbound link generation (menus, sitemaps, redirects, hreflang) only substitutes values into the pattern, so it keeps working. API updates that send an unchanged stored pattern back still succeed, which keeps REST/MCP round-trips and seed re-applies with onConflict: "update" working on legacy sites.

Compatibility trade-off to review: patterns like /{slug}-{id} and /{year}{month}/{slug} could be saved before and are now rejected. On sites that already have one, resolveEmDashPath stops matching it. I found no such pattern anywhere in the repo's seeds, templates, docs, or the WordPress importer. If compact date forms turn out to matter, a follow-up could give the date tokens fixed-width regexes (\d{4}, \d{2}), which would make {year}{month} safe without a separate segment.

Out of scope, filed separately: seed-file redirect patterns skip validatePattern, and /[a][b][c][d][e]x takes ~41 s against a 200-character path in the redirect cache. It's the same bug class in a different subsystem.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change): full packages/core suite (7369 passed) and ContentTypeEditor admin tests
  • pnpm format has been run (on touched files)
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added and reviewed the user-facing changeset (if this PR changes a published package)
  • New features link to an approved Discussion: n/a, bug fix
  • I have included screenshots below if this PR changes the UI

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 5.5 (Claude Code)

Screenshots / test output

The collection editor with /blog/{year}{slug} entered. The inline error appears and Save is disabled:

Posts collection editor with URL Pattern set to /blog/{year}{slug}, a red message below reading "Each placeholder needs its own path segment, e.g. /{year}/{slug}", and a disabled Save button

The same state in Arabic (RTL). The message shows in English until the catalogs are extracted on merge:

The same Posts collection editor in the Arabic RTL layout, showing the red path-segment message aligned under the URL Pattern field and a disabled Save button

Regression test before the fix (stored /{a}{b}{c}{d}{e}x, 200-character path through resolveEmDashPath):

× resolves a path against a stored ambiguous pattern without backtracking 8213ms
AssertionError: expected 8173.405208 to be less than 1000

Two `([^/]+)` groups in one path segment can split it many ways, so
`resolveEmDashPath` backtracked catastrophically on crafted anonymous
paths (~8 s for `/{a}{b}{c}{d}{e}x` against a 200-char path). A literal
separator does not help: `[^/]+` also matches the literal, so
`/{a}-{b}-{c}x` is still polynomial. Requiring a `/` between
placeholders pins each group to its own segment and keeps matching linear.

- compileUrlPattern throws for multiple placeholders in a segment
- zod create/update bodies surface the specific message
- SchemaRegistry validates on create, seed create, and on update when the
  pattern changes (unchanged stored patterns survive round-trips)
- validateSeed rejects such patterns before any seed writes
- resolveEmDashPath skips invalid stored patterns with a warning per
  cache build instead of throwing on every request
- admin editor flags the pattern inline and disables save
@changeset-bot

changeset-bot Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2bf64fe

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
emdash Patch
@emdash-cms/admin Patch
@emdash-cms/cloudflare Patch
@emdash-cms/plugin-test Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
create-emdash Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

🚀 Deploying Preview to Cloudflare 🚀

Preview URL: https://fix-url-pattern-redos.try.emdashcms.com, https://fix-url-pattern-redos-emdash-playground.emdash-cms.workers.dev (commit 2bf64fe)

This URL reflects your latest Preview deployment

Preview Deployments by commit

Status Deployment URL Commit Updated (UTC) See this deployment's details
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://3eed3c0c.try.emdashcms.com, https://3eed3c0c-emdash-playground.emdash-cms.workers.dev 2bf64fe 2026-09-27T14:24:49.651Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://7048f6db.try.emdashcms.com, https://7048f6db-emdash-playground.emdash-cms.workers.dev 0ec2744 2026-09-27T13:29:57.526Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://34409168.try.emdashcms.com, https://34409168-emdash-playground.emdash-cms.workers.dev 2a4f8e2 2026-09-26T13:19:13.371Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://c8fb970f.try.emdashcms.com, https://c8fb970f-emdash-playground.emdash-cms.workers.dev 8b07329 2026-09-23T07:38:18.411Z Visit the dashboard ↗

@pkg-pr-new

pkg-pr-new Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@3303

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@3303

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@3303

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@3303

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@3303

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@3303

emdash

npm i https://pkg.pr.new/emdash@3303

create-emdash

npm i https://pkg.pr.new/create-emdash@3303

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@3303

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@3303

@emdash-cms/plugin-test

npm i https://pkg.pr.new/@emdash-cms/plugin-test@3303

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@3303

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@3303

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@3303

@emdash-cms/registry-loader

npm i https://pkg.pr.new/@emdash-cms/registry-loader@3303

@emdash-cms/registry-moderation

npm i https://pkg.pr.new/@emdash-cms/registry-moderation@3303

@emdash-cms/registry-verification

npm i https://pkg.pr.new/@emdash-cms/registry-verification@3303

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@3303

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@3303

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@3303

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@3303

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@3303

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@3303

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@3303

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@3303

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@3303

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@3303

commit: 2bf64fe

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
docs 0ec2744 Sep 27 2026, 01:29 PM

@emdashbot emdashbot Bot 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.

The core ReDoS fix is solid: compileUrlPattern now rejects two or more placeholders in the same path segment, resolveEmDashPath skips invalid stored patterns with a warning, and seeds/admin/REST/MCP schemas reject ambiguous patterns on write. Tests cover the DoS, the new validation rule, and seed rejection.

The main issue is that the changeset/docs promise an unchanged-invalid-pattern round-trip for API updates, but the implementation doesn't deliver it. The updateCollectionBody Zod schema validates urlPattern before the handler runs, so the registry's new unchanged-pattern bypass is unreachable from the REST route and the MCP tool. The admin component also always sends urlPattern on save, so it can't benefit from any such round-trip either. The registry bypass is essentially dead code in production.

Also note that validateSeed runs before applySeed writes anything, so the seed path won't exercise the registry bypass for invalid patterns either.

I recommend either (a) updating the changeset/docs to match the actual behavior (API callers must omit urlPattern, not echo the invalid one) and removing/simplifying the unreachable registry bypass, or (b) moving the unchanged-pattern tolerance into the REST/MCP layers so the documented round-trip actually works. If (b), add integration tests for a REST or MCP update that echoes an existing invalid pattern.

Comment thread packages/core/src/schema/registry.ts Outdated
Comment on lines +776 to +777
// A stored pattern that fails validation must survive round-trips of unrelated edits.
if (input.urlPattern !== existingRow.url_pattern) this.validateUrlPattern(input.urlPattern);

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.

[needs fixing] This bypass is meant to let an existing invalid urlPattern survive round-trip updates, but it is unreachable from the production API/MCP paths. Both the REST route (packages/core/src/astro/routes/api/schema/collections/[slug]/index.ts:52) and the MCP tool (packages/core/src/mcp/server.ts:2062-2069) parse the request with updateCollectionBody first, and urlPatternValue.superRefine rejects ambiguous patterns unconditionally before handleSchemaCollectionUpdate is called. Seeds don't reach this either because validateSeed rejects the pattern before applySeed invokes the registry. Either move this unchanged-pattern tolerance into the API/MCP layer so it is actually exercised, or remove it and update the changeset/docs to say callers must omit urlPattern for unrelated edits.


Collection URL patterns now allow at most one placeholder per path segment. `/{year}/{month}/{slug}.html` and `/p-{id}/{slug}` are still valid, but `/{year}{month}/{slug}` and `/{slug}-{id}` are rejected when a collection is created or its pattern is changed through the admin, the REST API, the MCP `schema_update_collection` tool, or a seed. Seed files with such a pattern fail validation before anything is applied. The admin's collection editor shows the problem next to the URL Pattern field.

If a collection already has a pattern that breaks this rule, it keeps working for generating links in menus, sitemaps and redirects, but `resolveEmDashPath()` no longer matches it, and the site logs a warning naming the collection. API updates that send the stored pattern back unchanged still succeed. Give each placeholder its own segment (for example, change `/{slug}-{id}` to `/{id}/{slug}`) to route those entries again. The admin won't save changes to that collection until the pattern is fixed.

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.

[needs fixing] The sentence "API updates that send the stored pattern back unchanged still succeed" does not match the actual flow. Because updateCollectionBody validates urlPattern before the registry bypass can compare it to the stored value, a REST or MCP update that echoes the existing invalid pattern is rejected with a 400. The admin editor also always sends the pattern, so it cannot round-trip an invalid one. Update this changeset (and the matching docs, if any) to reflect the actual behavior: the stored pattern is preserved only when the caller omits urlPattern or the registry is called directly.

expect(await registry.getCollection("pages")).toBeNull();
});

it("keeps an unchanged stored pattern when other collection settings are updated", async () => {

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.

[suggestion] This test only covers direct registry.updateCollection calls, which is the one path that exercises the unchanged-pattern bypass. Consider adding REST/MCP integration tests that echo an existing invalid urlPattern so the intended round-trip behavior is actually verified where users will hit it. That will also prevent the changeset/docs drift seen here.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Sep 23, 2026
github-actions Bot pushed a commit that referenced this pull request Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Overlapping PRs

This PR modifies files that are also changed by other open PRs:

This may cause merge conflicts or duplicated work. A maintainer will coordinate.

The redirect middleware now only issues redirects to single-slash
site-relative paths. Rows whose destination has a scheme, a `//` or `/\`
prefix, or control characters (browsers strip tab/CR/LF, so `/\t/host`
resolves as `//host`) are logged and skipped. Seeds, plugins with direct
DB access, and manual DB edits could previously store an open redirect.

compilePattern now escapes every regex metacharacter in literal text,
including parentheses. Before, a literal `(...)` survived as live regex
syntax: `/(.*.*.*x)/[p]` backtracked catastrophically on ordinary paths,
and an unbalanced `(` threw during cache compilation, which disabled every
redirect on the site. The rewrite also collects param names in source
order, fixing swapped captures for `/[category]/[...rest]`.

The redirect cache skips stored pattern rows that fail validatePattern,
and seed validation now runs validatePattern, validateDestinationParams
and the site-relative destination check, matching the redirects API.
@github-actions github-actions Bot added size/XL review/needs-rereview New commits since the last review and removed size/L needs-rebase labels Sep 26, 2026
@ascorbic
ascorbic merged commit d8ea3fc into main Sep 27, 2026
41 checks passed
@ascorbic
ascorbic deleted the fix/url-pattern-redos branch September 27, 2026 16:14
@emdashbot emdashbot Bot mentioned this pull request Sep 27, 2026
danielmlr added a commit to danielmlr/emdash that referenced this pull request Sep 27, 2026
The catalog extraction after emdash-cms#1939 and emdash-cms#3303 added five admin strings:
the dashboard's core update notice and the error for a URL pattern with
two placeholders in one path segment. German admins would have seen them
in English on every site that has an update waiting.

The changeset now names the update notice, the invitation emails and
the unpublish term switch (depublizieren to zurückziehen).
ascorbic pushed a commit that referenced this pull request Sep 28, 2026
* i18n(de): translate the taxonomy picker, link picker and plugin draft review

The German admin catalog had fallen 72 entries behind after the taxonomy
sidebar, link search, content validation messages and the plugin
editor-draft and release verification work landed. German-speaking
editors saw English in the taxonomy picker and when deleting a taxonomy,
the publish confirmation, the URL and language settings, the link and
code block language pickers, save validation errors and the
save-conflict message, the plugin consent dialog's editor-content warning
and release verification, the review dialog for plugin-proposed changes,
and the registry's install errors.

Validation messages quote the field label, because a label can be plural
or German and the quoted form keeps the verb agreeing either way. The
code block's "Set language" button now reads "Sprache festlegen" instead
of "Sprache speichern": it opens the language choice and saves nothing.

* i18n(de): complete the German admin and settle its terminology

Upstream added about 550 admin strings since the last German pass, in
site transfer, content relations, bulk term assignment, the bylines
directory, block types and CLI device sign-in. German-speaking editors
saw them in English.

A review of the 2,400 older entries against their source found
mistranslations (a passkey name read as a user name, Integer and Number
both shown as "Zahl"), calques and one-off terms. The catalog now uses
one term per concept: Plugin, Sammlung, veröffentlichen, löschen for
delete and entfernen for remove, Beziehung for content relations.
Progress messages use the passive, buttons the infinitive, and quotes
German quotation marks.

* i18n(de): translate the core update notice and the URL pattern error

The catalog extraction after #1939 and #3303 added five admin strings:
the dashboard's core update notice and the error for a URL pattern with
two placeholders in one path segment. German admins would have seen them
in English on every site that has an update waiting.

The changeset now names the update notice, the invitation emails and
the unpublish term switch (depublizieren to zurückziehen).
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.

1 participant