Skip to content

fix(core): harden redirect rules written outside the admin API - #3326

Merged
ascorbic merged 3 commits into
mainfrom
fix/redirect-rule-hardening
Sep 26, 2026
Merged

ascorbic merged 3 commits into
mainfrom
fix/redirect-rule-hardening

Conversation

@ascorbic

Copy link
Copy Markdown
Member

What does this PR do?

Closes two redirect hardening gaps found in a security audit, plus two pattern-compiler bugs an adversarial review turned up along the way.

1. The middleware only redirects to site-relative paths. The admin API's urlPath schema requires a leading single /, but _emdash_redirects rows can also come from seeds, direct DB access or manual edits. At request time the middleware only refused // and /\ prefixes, so a stored https://evil.example destination was an open redirect. The new isSiteRelativeDestination (redirects/destination.ts) allows only paths that start with a single /, have no // or /\ prefix, and contain no C0 control characters or DEL. The control-character check matters because browsers strip tab, CR and LF from URLs, so /\t/evil.example resolves as //evil.example. The check runs after pattern interpolation, so captured path segments are covered too. Rejected rows are logged with their ID and fall through to next().

2. Seed redirects get the same pattern validation as the API. seed/validate.ts now runs validatePattern and validateDestinationParams for pattern sources, as api/handlers/redirects.ts does. isPattern detection is already consistent: RedirectRepository.create derives is_pattern from the source when the seed doesn't pass it. Seed destinations also have to pass isSiteRelativeDestination, so a seed can't store a row the middleware would then skip on every request.

3. compilePattern treated literal parentheses as regex syntax. This came out of the adversarial review. Literal text was escaped after the capture groups had been added, by splitting on /(\([^)]+\))/, so any literal (...) in a source stayed live regex. The results, all of which pass validatePattern and could be stored through the API as well as seeds:

  • /(.*.*.*.*.*.*.*.*x)/[p] backtracks catastrophically: 283 ms at 25 characters, and it didn't finish within 100 s at 40.
  • /a((b)/[p] throws Unterminated group in compileRedirects. The cache never installs, the middleware's catch calls next(), and every redirect on the site stops working while findAllEnabled runs again on each logged-out request.

compilePattern now walks the placeholder matches and escapes the literal text between them, including ()[], the same way compileUrlPattern in schema/url-pattern.ts builds its regex. As a side effect it collects param names in source order. The old code collected splats first, so /[category]/[...rest] against /tech/a/b returned { rest: "tech", category: "a/b" }, with the captures swapped.

4. The cache skips malformed stored patterns. compileRedirects skips pattern rows that fail validatePattern and logs a warning, so rows that older seeds already installed (for example /[a][b][c]…) are never compiled.

Compatibility

I checked whether any official path creates external destinations on purpose, and none does:

  • The API urlPath schema and seed isValidRedirectPath have required a leading single / since the first commit, so no official write path has ever accepted an absolute URL.
  • Slug-change auto-redirects build the source and destination from the same collection urlPattern. An absolute pattern would also make the source absolute, and that can never match a request pathname.
  • The WordPress importer (cli/commands/import/wordpress.ts) writes _redirects.json and never touches _emdash_redirects.
  • No template or demo seed defines redirects.
  • Plugin redirect writes go through createRedirectBody, the same schema as the API.

The only rows affected are ones that bypassed every validator, and they now fall through to normal routing with a warning. Sources with literal parentheses now match the literal path instead of acting as a regex, which is what the "no user-supplied regex" doc comment on patterns.ts already promised.

Not changed here

  • The API urlPath schema still accepts /\x and /\t/x as destinations. They're safe now because the middleware skips them, but the API doesn't warn when you save one. Tightening urlPath would reject input the API currently accepts, so it should be its own change.
  • redirects/loops.ts compilePatterns still compiles stored patterns without checking validatePattern. With the compilePattern fix, the worst left there is a slow match over short inputs on authenticated admin loop checks.
  • isSafeRedirect in api/redirect.ts, used for the auth routes' ?redirect= parameters, has the same tab/CR/LF bypass: ?redirect=/%09/evil.example resolves to evil.example. I'm tracking it separately so this PR stays focused.

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)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). n/a: no admin UI changes. The new messages are server-side logs and seed validation errors.
  • 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: n/a, no UI changes

AI-generated code disclosure

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

Screenshots / test output

Not applicable for screenshots.

The regression tests were written first, and each one failed against main for the reported reason:

  • tests/unit/astro/middleware-redirect.test.ts: stored exact rules with scheme, relative, //, /\, tab, LF, CRLF and DEL destinations; a pattern rule resolving to an external URL; a // produced by a captured segment; a malformed stored pattern (/[a][b][c] matched /abc before the fix). A query string and fragment in a destination still redirect.
  • tests/unit/redirects/patterns.test.ts: literal and unbalanced parentheses; captures from a [param] before a [...splat].
  • tests/unit/seed/validate.test.ts: malformed pattern sources, uncaptured destination params, off-site destinations.

pnpm build (root), pnpm lint:quick (0 diagnostics) and pnpm typecheck all pass, and the core unit and integration suites pass: 7250 passed, 6 skipped.

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.
@changeset-bot

changeset-bot Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d9bbcbf

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/cloudflare Patch
@emdash-cms/plugin-test Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/admin 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

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

This PR is the right change: it closes a real open-redirect hole for rows written outside the admin API, fixes two concrete ReDoS/DoS bugs in the pattern compiler, and makes seed validation consistent with the request-time hardening. The implementation is focused, adds good behavioral regression tests, and introduces no new logged-out queries.

I checked the diff, the changed source files, the redirect repository, the API schema, and the cache/loops call sites. The middleware path is correctly hardened: destinations are validated after interpolation, malformed pattern sources are skipped at compile time, and literal regex metacharacters are escaped in patterns. Seed validation mirrors the important API/handlers checks.

Two smaller gaps remain:

  1. The seed validation error message for an off-site destination no longer matches the cases it rejects. It mentions protocol-relative URLs, path traversal, and newlines, but isSiteRelativeDestination also rejects backslash prefixes (/\\evil.example) and every C0/DEL control character (tab, NUL, DEL, etc.). A seed author with a tab in the destination will be told the rule has a newline, which is misleading.
  2. RedirectRepository.matchPath still calls compilePattern without first validating the source and never checks isSiteRelativeDestination on the resolved destination. It appears unused in production code (only integration tests call it), but as a public repository method it is an inconsistent, unhardened path in the same subsystem.

Neither blocks the security fix, but addressing them keeps the redirect surface uniformly hardened and user-facing errors accurate.


Findings

  • [suggestion] packages/core/src/seed/validate.ts:403-405

    The destination check now rejects backslash prefixes (/\\evil.example) and all C0/DEL control characters (tab, NUL, DEL, etc.) via isSiteRelativeDestination, but the error message still says "no protocol-relative URLs, path traversal, or newlines". A seed author whose destination contains only a tab or a backslash prefix will be misled about why the rule was rejected.

    				} else if (!isValidRedirectPath(destination) || !isSiteRelativeDestination(destination)) {
    					errors.push(
    						`${prefix}.destination: must be a path starting with / (no protocol-relative URLs, backslash prefixes, path traversal, or control characters)`,
    					);
    				}
    
  • [suggestion] packages/core/src/database/repositories/redirect.ts:468-479

    matchPath is now the only remaining redirect-matching path that compiles a stored pattern without first validating it and that returns a resolved destination without checking isSiteRelativeDestination. It appears unused in production code (only integration tests call it), but as a public repository method it leaves an unhardened gap inconsistent with the middleware and cache. Consider either applying the same validatePattern + isSiteRelativeDestination hardening here, or removing the method if it is genuinely dead code.

@github-actions github-actions Bot added the review/awaiting-author Reviewed; waiting on the author to respond label Sep 23, 2026
@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@3326

@emdash-cms/auth

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

@emdash-cms/auth-atproto

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

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

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

emdash

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

create-emdash

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

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

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

@emdash-cms/plugin-cli

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

@emdash-cms/plugin-test

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

@emdash-cms/plugin-types

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

@emdash-cms/registry-client

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

@emdash-cms/registry-lexicons

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

@emdash-cms/registry-loader

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

@emdash-cms/registry-moderation

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

@emdash-cms/registry-verification

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

@emdash-cms/sandbox-workerd

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-field-kit

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: d9bbcbf

@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-redirect-rule-hardening.try.emdashcms.com, https://fix-redirect-rule-hardening-emdash-playground.emdash-cms.workers.dev (commit d9bbcbf)

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://46ef61bb.try.emdashcms.com, https://46ef61bb-emdash-playground.emdash-cms.workers.dev d9bbcbf 2026-09-26T19:47:20.851Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://bafde86a.try.emdashcms.com, https://bafde86a-emdash-playground.emdash-cms.workers.dev 4915a72 2026-09-26T13:07:32.885Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://8abf064a.try.emdashcms.com, https://8abf064a-emdash-playground.emdash-cms.workers.dev aec5ef4 2026-09-23T13:54:59.239Z Visit the dashboard ↗

# Conflicts:
#	packages/core/src/seed/validate.ts
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 26, 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 d9bbcbf Sep 26 2026, 07:44 PM

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

@ascorbic
ascorbic merged commit a3421ef into main Sep 26, 2026
41 checks passed
@ascorbic
ascorbic deleted the fix/redirect-rule-hardening branch September 26, 2026 21:27
@emdashbot emdashbot Bot mentioned this pull request Sep 26, 2026
linropx added a commit to linropx/emdash that referenced this pull request Sep 29, 2026
Resolve conflicts with emdash-cms#3326 (redirect rule hardening):
- cache.ts: keep upstream's validatePattern() guard, compile the
  normalised source (validate the author's raw source).
- middleware-redirect.test.ts: keep both new describe blocks.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/core cla: signed review/awaiting-author Reviewed; waiting on the author to respond size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants