Skip to content

Commit

Permalink
fix: 'isRequestOriginAllowed' returns mixed results when regex is used (
Browse files Browse the repository at this point in the history
#152)

The 'isRequestOriginAllowed' function returned random results for
global regexes, since the .test function was used, and the output
of this function depends on previous invocations of the function. By
resetting the 'lastIndex', every invocation of the function should now
return the same result.

This also updates the corresponding test to use a global regex, and do
the same validation twice, in order to check consistency

fixes #151

Co-authored-by: Tom Brouwer <brouwer@floodtags.com>
  • Loading branch information
Tom-Brouwer and Tom Brouwer authored Feb 23, 2022
1 parent 2d6c272 commit dc7ad95
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
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

0 comments on commit dc7ad95

Please sign in to comment.