From 129e98f9a8516061f49def53feb8acc2d9fea14b Mon Sep 17 00:00:00 2001 From: Alessandro Magionami Date: Wed, 5 Aug 2020 10:09:20 +0200 Subject: [PATCH] test: test for array and regex origin options (#77) (#81) --- test/index.test.js | 69 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/test/index.test.js b/test/index.test.js index 4c85ece..7c6253c 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -477,7 +477,7 @@ test('Should not add cors headers other than `vary` when origin is false', t => }) }) -test('Allow only request from a specifc origin', t => { +test('Allow only request from a specific origin', t => { t.plan(4) const fastify = Fastify() @@ -503,6 +503,73 @@ test('Allow only request from a specifc origin', t => { }) }) +test('Allow only request from multiple specific origin', t => { + t.plan(8) + + const fastify = Fastify() + fastify.register(cors, { origin: ['other.io', 'example.com'] }) + + fastify.get('/', (req, reply) => { + reply.send('ok') + }) + + fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'other.io' } + }, (err, res) => { + t.error(err) + delete res.headers.date + t.strictEqual(res.statusCode, 200) + t.strictEqual(res.payload, 'ok') + t.match(res.headers, { + 'access-control-allow-origin': 'other.io', + vary: 'Origin' + }) + }) + + fastify.inject({ + method: 'GET', + url: '/', + headers: { origin: 'foo.com' } + }, (err, res) => { + t.error(err) + delete res.headers.date + t.strictEqual(res.statusCode, 200) + t.strictEqual(res.payload, 'ok') + t.match(res.headers, { + 'access-control-allow-origin': false, + vary: 'Origin' + }) + }) +}) + +test('Allow only request from a specific origin using regex', t => { + t.plan(4) + + const fastify = Fastify() + fastify.register(cors, { origin: new RegExp(/^(example|other)\.com/) }) + + 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.strictEqual(res.statusCode, 200) + t.strictEqual(res.payload, 'ok') + t.match(res.headers, { + 'access-control-allow-origin': 'example.com', + vary: 'Origin' + }) + }) +}) + test('Disable preflight', t => { t.plan(7)