Repository navigation
fix(core): harden redirect rules written outside the admin API - #3326
Conversation
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 detectedLatest commit: d9bbcbf The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
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 |
There was a problem hiding this comment.
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:
- 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
isSiteRelativeDestinationalso 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. RedirectRepository.matchPathstill callscompilePatternwithout first validating the source and never checksisSiteRelativeDestinationon 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-405The destination check now rejects backslash prefixes (
/\\evil.example) and all C0/DEL control characters (tab, NUL, DEL, etc.) viaisSiteRelativeDestination, 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-479matchPathis now the only remaining redirect-matching path that compiles a stored pattern without first validating it and that returns a resolved destination without checkingisSiteRelativeDestination. 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 samevalidatePattern+isSiteRelativeDestinationhardening here, or removing the method if it is genuinely dead code.
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
🚀 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 deploymentPreview Deployments by commit
|
# Conflicts: # packages/core/src/seed/validate.ts
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
docs | d9bbcbf | Sep 26 2026, 07:44 PM |
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
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.
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
urlPathschema requires a leading single/, but_emdash_redirectsrows can also come from seeds, direct DB access or manual edits. At request time the middleware only refused//and/\prefixes, so a storedhttps://evil.exampledestination was an open redirect. The newisSiteRelativeDestination(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.exampleresolves 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 tonext().2. Seed redirects get the same pattern validation as the API.
seed/validate.tsnow runsvalidatePatternandvalidateDestinationParamsfor pattern sources, asapi/handlers/redirects.tsdoes.isPatterndetection is already consistent:RedirectRepository.createderivesis_patternfrom the source when the seed doesn't pass it. Seed destinations also have to passisSiteRelativeDestination, so a seed can't store a row the middleware would then skip on every request.3.
compilePatterntreated 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 passvalidatePatternand 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]throwsUnterminated groupincompileRedirects. The cache never installs, the middleware's catch callsnext(), and every redirect on the site stops working whilefindAllEnabledruns again on each logged-out request.compilePatternnow walks the placeholder matches and escapes the literal text between them, including()[], the same waycompileUrlPatterninschema/url-pattern.tsbuilds 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/breturned{ rest: "tech", category: "a/b" }, with the captures swapped.4. The cache skips malformed stored patterns.
compileRedirectsskips pattern rows that failvalidatePatternand 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:
urlPathschema and seedisValidRedirectPathhave required a leading single/since the first commit, so no official write path has ever accepted an absolute URL.urlPattern. An absolute pattern would also make the source absolute, and that can never match a request pathname.cli/commands/import/wordpress.ts) writes_redirects.jsonand never touches_emdash_redirects.redirects.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.tsalready promised.Not changed here
urlPathschema still accepts/\xand/\t/xas destinations. They're safe now because the middleware skips them, but the API doesn't warn when you save one. TighteningurlPathwould reject input the API currently accepts, so it should be its own change.redirects/loops.tscompilePatternsstill compiles stored patterns without checkingvalidatePattern. With thecompilePatternfix, the worst left there is a slow match over short inputs on authenticated admin loop checks.isSafeRedirectinapi/redirect.ts, used for the auth routes'?redirect=parameters, has the same tab/CR/LF bypass:?redirect=/%09/evil.exampleresolves toevil.example. I'm tracking it separately so this PR stays focused.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runAI-generated code disclosure
Screenshots / test output
Not applicable for screenshots.
The regression tests were written first, and each one failed against
mainfor 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/abcbefore 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) andpnpm typecheckall pass, and the core unit and integration suites pass: 7250 passed, 6 skipped.