Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes escaping port number in absolute urls #1028

Merged
merged 2 commits into from Dec 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 25 additions & 10 deletions src/utils/matching/matchRequestUrl.test.ts
Expand Up @@ -64,6 +64,31 @@ describe('matchRequestUrl', () => {
})

describe('coercePath', () => {
test('escapes the colon in protocol', () => {
expect(coercePath('https://example.com')).toEqual('https\\://example.com')
expect(coercePath('https://example.com/:userId')).toEqual(
'https\\://example.com/:userId',
)
expect(coercePath('http://localhost:3000')).toEqual(
'http\\://localhost\\:3000',
)
})

test('escapes the colon before the port number', () => {
expect(coercePath('localhost:8080')).toEqual('localhost\\:8080')
expect(coercePath('http://127.0.0.1:8080')).toEqual(
'http\\://127.0.0.1\\:8080',
)
expect(coercePath('https://example.com:1234')).toEqual(
'https\\://example.com\\:1234',
)

expect(coercePath('localhost:8080/:5678')).toEqual('localhost\\:8080/:5678')
expect(coercePath('https://example.com:8080/:5678')).toEqual(
'https\\://example.com\\:8080/:5678',
)
})

test('replaces wildcard with an unnnamed capturing group', () => {
expect(coercePath('*')).toEqual('(.*)')
expect(coercePath('**')).toEqual('(.*)')
Expand All @@ -86,14 +111,4 @@ describe('coercePath', () => {
'/foo/:first/bar/:second*/(.*)',
)
})

test('escapes the semicolon in protocol', () => {
expect(coercePath('https://example.com')).toEqual('https\\://example.com')
expect(coercePath('https://example.com/:userId')).toEqual(
'https\\://example.com/:userId',
)
expect(coercePath('http://localhost:3000')).toEqual(
'http\\://localhost:3000',
)
})
})
7 changes: 6 additions & 1 deletion src/utils/matching/matchRequestUrl.ts
Expand Up @@ -36,12 +36,17 @@ export function coercePath(path: string): string {
: `${parameterName}${expression}`
},
)
/**
* Escape the port so that "path-to-regexp" can match
* absolute URLs including port numbers.
*/
.replace(/([^\/])(:)(?=\d+)/, '$1\\$2')
/**
* Escape the protocol so that "path-to-regexp" could match
* absolute URL.
* @see https://github.com/pillarjs/path-to-regexp/issues/259
*/
.replace(/^([^\/]+)(:)(?=\/\/)/g, '$1\\$2')
.replace(/^([^\/]+)(:)(?=\/\/)/, '$1\\$2')
)
}

Expand Down