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

fix(entity-link): more robust url regex #933

Merged
merged 5 commits into from
Nov 21, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect } from 'vitest'
import { expect, vi } from 'vitest'
import type { SpyInstance } from 'vitest'
import composables from '..'

const { useExternalLinkCreator } = composables
Expand All @@ -22,6 +23,12 @@ const routeParams = [
]

describe('parse-route-parameters', () => {
let consoleMock: SpyInstance

beforeEach(() => {
consoleMock = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})

it('builds valid url with multiple parameters', () => {
const url = useExternalLinkCreator(routeParams)

Expand All @@ -39,5 +46,53 @@ describe('parse-route-parameters', () => {

// Console error should be thrown, and method will return empty string
expect(url).toBe('')
expect(consoleMock).toHaveBeenCalledOnce()
expect(consoleMock).toHaveBeenLastCalledWith('Failed to build valid URL:', new Error('Invalid url'))
})

it('fails if there are trailing slashes', () => {
const url = useExternalLinkCreator([routeParams[0], routeParams[1], '//'])

// Console error should be thrown, and method will return empty string
expect(url).toBe('')
expect(consoleMock).toHaveBeenLastCalledWith('Failed to build valid URL:', new Error('Invalid url'))
})

it('fails if the base URL uses http protocol', () => {
vi.spyOn(global as any, 'window', 'get').mockImplementationOnce(() => ({
location: {
origin: 'http://cloud.konghq.tech/',
},
}))

const url = useExternalLinkCreator([routeParams[0], routeParams[1]])

expect(url).toBe('')
expect(consoleMock).toHaveBeenLastCalledWith('Failed to build valid URL:', new Error('Invalid url'))
})

it('allows http only for localhost', () => {
vi.spyOn(global as any, 'window', 'get').mockImplementationOnce(() => ({
location: {
origin: 'http://localhost:3000/',
},
}))

const url = useExternalLinkCreator([routeParams[0], routeParams[1]])

expect(url).toBe(`http://localhost:3000/${routeParams[0]}/${routeParams[1]}`)
})

it('does not allow port number following an external domain', () => {
vi.spyOn(global as any, 'window', 'get').mockImplementationOnce(() => ({
location: {
origin: 'http://cloud.konghq.tech:3000/',
},
}))

const url = useExternalLinkCreator([routeParams[0]])

expect(url).toBe('')
expect(consoleMock).toHaveBeenLastCalledWith('Failed to build valid URL:', new Error('Invalid url'))
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ export default function useExternalLinkCreator(routeParams: string[]): string {
const fullUrl = `${baseUrl}${path}`
const hasEmptyParams = routeParams.some(item => item.trim() === '')

/* Test validity of generated URL */
const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g // eslint-disable-line no-useless-escape
// Test validity of generated URL; only allows `http` protocal if domain is `localhost`
/* eslint-disable-next-line no-useless-escape */
const validUrlRegex = /^(https:\/\/(www\.)?([a-zA-Z0-9-]+\.){1,}[a-zA-Z]{2,}(:[0-9]+)?(\/[^\/]+)*)$|^(https|http):\/\/localhost(:[0-9]+)?(\/[^\/]+)*$/
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to add a unit test for this composable to test happy and bad paths?

Copy link
Contributor Author

@mihai-peteu mihai-peteu Nov 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call - pushed a commit with a few more passing + failing cases


/* eslint-disable no-new */
if (!urlRegex.test(fullUrl) && !hasEmptyParams && new URL(fullUrl)) {
if (validUrlRegex.test(fullUrl) && !hasEmptyParams && new URL(fullUrl)) {
return `${baseUrl}${path}`
} else {
throw new Error('Invalid url')
Expand Down