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 'isRequestOriginAllowed' returns mixed results when regex is used #152

Merged
merged 1 commit into from
Feb 23, 2022
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
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ function isRequestOriginAllowed (reqOrigin, allowedOrigin) {
} else if (typeof allowedOrigin === 'string') {
return reqOrigin === allowedOrigin
} else if (allowedOrigin instanceof RegExp) {
allowedOrigin.lastIndex = 0
return allowedOrigin.test(reqOrigin)
} else {
return !!allowedOrigin
Expand Down
35 changes: 20 additions & 15 deletions test/cors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -631,29 +631,34 @@ test('Allow only request from multiple specific origin', t => {
})

test('Allow only request from a specific origin using regex', t => {
t.plan(4)
t.plan(8)

const fastify = Fastify()
fastify.register(cors, { origin: /^(example|other)\.com/ })
fastify.register(cors, { origin: /(example|other)\.com/gi })

fastify.get('/', (req, reply) => {
reply.send('ok')
})

fastify.inject({
method: 'GET',
url: '/',
headers: { origin: 'example.com' }
}, (err, res) => {
t.error(err)
delete res.headers.date
t.equal(res.statusCode, 200)
t.equal(res.payload, 'ok')
t.match(res.headers, {
'access-control-allow-origin': 'example.com',
vary: 'Origin'
// .test was previously used, which caused 2 consecutive requests to return
// different results with global (e.g. /g) regexes. Therefore, check this
// twice to check consistency
for (let i = 0; i < 2; i++) {
fastify.inject({
method: 'GET',
url: '/',
headers: { origin: 'https://www.example.com/' }
}, (err, res) => {
t.error(err)
delete res.headers.date
t.equal(res.statusCode, 200)
t.equal(res.payload, 'ok')
t.match(res.headers, {
'access-control-allow-origin': 'https://www.example.com/',
vary: 'Origin'
})
})
})
}
})

test('Disable preflight', t => {
Expand Down