Skip to content

Commit

Permalink
fix: ensure regular expressions are properly escaped (#378)
Browse files Browse the repository at this point in the history
* fix: front slashes only get escaped now if they aren't already

* chore: updated test description

* chore: cleaned up logic

* fix: ensure regexes are properly escaped

* chore: style changes

---------

Co-authored-by: Nick Taylor <nick@iamdeveloper.com>
  • Loading branch information
eduardoboucas and nickytonline committed Apr 28, 2023
1 parent 9d798de commit 214c3fb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
18 changes: 17 additions & 1 deletion node/declaration.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { test, expect } from 'vitest'

import { FunctionConfig } from './config.js'
import { Declaration, mergeDeclarations } from './declaration.js'
import { Declaration, mergeDeclarations, parsePattern } from './declaration.js'

const deployConfigDeclarations: Declaration[] = []

Expand Down Expand Up @@ -191,3 +191,19 @@ test('netlify.toml-defined excludedPath are respected', () => {

expect(declarations).toEqual(expectedDeclarations)
})

test('Does not escape front slashes in a regex pattern if they are already escaped', () => {
const regexPattern = '^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/([^/.]{1,}))\\/shows(?:\\/(.*))(.json)?[\\/#\\?]?$'
const expected = '^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/([^/.]{1,}))\\/shows(?:\\/(.*))(.json)?[\\/#\\?]?$'
const actual = parsePattern(regexPattern)

expect(actual).toEqual(expected)
})

test('Escapes front slashes in a regex pattern', () => {
const regexPattern = '^(?:/(_next/data/[^/]{1,}))?(?:/([^/.]{1,}))/shows(?:/(.*))(.json)?[/#\\?]?$'
const expected = '^(?:\\/(_next\\/data\\/[^/]{1,}))?(?:\\/([^/.]{1,}))\\/shows(?:\\/(.*))(.json)?[/#\\?]?$'
const actual = parsePattern(regexPattern)

expect(actual).toEqual(expected)
})
7 changes: 3 additions & 4 deletions node/declaration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,8 @@ const createDeclarationsFromFunctionConfigs = (
// Validates and normalizes a pattern so that it's a valid regular expression
// in Go, which is the engine used by our edge nodes.
export const parsePattern = (pattern: string) => {
// Escaping forward slashes with back slashes.
const normalizedPattern = pattern.replace(/\//g, '\\/')
const regex = regexpAST.transform(`/${normalizedPattern}/`, {
const regexp = new RegExp(pattern)
const newRegexp = regexpAST.transform(regexp, {
Assertion(path) {
// Lookaheads are not supported. If we find one, throw an error.
if (path.node.kind === 'Lookahead') {
Expand All @@ -155,5 +154,5 @@ export const parsePattern = (pattern: string) => {
})

// Strip leading and forward slashes.
return regex.toString().slice(1, -1)
return newRegexp.toString().slice(1, -1)
}

0 comments on commit 214c3fb

Please sign in to comment.