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

Add new 'ACKEE_AUTO_FQDN_ORIGIN' method of adding CORS Headers #271

Merged
merged 1 commit into from
Feb 26, 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
4 changes: 4 additions & 0 deletions app.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
"description": "Tracked domains which will be used on Ackee (CORS headers)",
"required": true
},
"ACKEE_AUTO_FQDN_ORIGIN": {
"description": "Automatically add CORS headers for domains with fully qualified domain names as titles",
"required": false
},
"ACKEE_TTL": {
"description": "Specifies how long an Ackee TTL token is valid (Default: 3600000)",
"required": false
Expand Down
6 changes: 6 additions & 0 deletions docs/Options.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,10 @@ Setting a wildcard (`*`) is also supported, but not recommended. It's neither a

```
ACKEE_ALLOW_ORIGIN="*"
```

As opposed to manually configuring CORS domains, you can also automatically add CORS Headers for domains in the domain list that have fully qualified domain names as a title. To achieve this, set:

```
ACKEE_AUTO_FQDN_ORIGIN="true"
```
3 changes: 2 additions & 1 deletion netlify.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@
ACKEE_MONGODB = "ACKEE_MONGODB"
ACKEE_USERNAME = "ACKEE_USERNAME"
ACKEE_PASSWORD = "ACKEE_PASSWORD"
ACKEE_ALLOW_ORIGIN = "ACKEE_ALLOW_ORIGIN"
ACKEE_ALLOW_ORIGIN = "ACKEE_ALLOW_ORIGIN"
ACKEE_AUTO_FQDN_ORIGIN = "ACKEE_AUTO_FQDN_ORIGIN"
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"graphql-scalars": "^1.10.0",
"graphql-tools": "^7.0.5",
"is-url": "^1.2.4",
"is-valid-domain": "^0.0.20",
"micro": "^9.3.4",
"microrouter": "^3.1.3",
"mongoose": "^5.12.14",
Expand Down
6 changes: 3 additions & 3 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ const catchError = (fn) => async (req, res) => {
}
}

const attachCorsHeaders = (fn) => (req, res) => {
const matchingOrigin = findMatchingOrigin(req, config.allowOrigin)
const attachCorsHeaders = (fn) => async (req, res) => {
const matchingOrigin = await findMatchingOrigin(req, config.allowOrigin, config.autoOrigin)

if (matchingOrigin != null) {
res.setHeader('Access-Control-Allow-Origin', matchingOrigin)
Expand All @@ -79,7 +79,7 @@ const attachCorsHeaders = (fn) => (req, res) => {
res.setHeader('Access-Control-Allow-Credentials', 'true')
}

return fn(req, res)
return await fn(req, res)
}

const notFound = (req) => {
Expand Down
18 changes: 15 additions & 3 deletions src/serverless.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const { ApolloServer } = require('apollo-server-lambda')

const config = require('./utils/config')
const connect = require('./utils/connect')
const domainFqNames = require('./utils/domainFqNames')
const createApolloServer = require('./utils/createApolloServer')
const { createServerlessContext } = require('./utils/createContext')

Expand All @@ -17,14 +18,25 @@ const apolloServer = createApolloServer(ApolloServer, {
context: createServerlessContext,
})

const origin = (() => {
const origin = ((req, callback) => {
if (config.autoOrigin) {
domainFqNames().then((d) => callback(req, d))
.catch(() => callback(req, false))
return
}

if (config.allowOrigin === '*') {
return true
callback(req, true)
return
}

if (config.allowOrigin != null) {
return config.allowOrigin.split(',')
callback(req, config.allowOrigin.split(','))
return
}

callback(req, false)
return
})()

exports.handler = apolloServer.createHandler({
Expand Down
1 change: 1 addition & 0 deletions src/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ module.exports = new Proxy({}, {
port: process.env.ACKEE_PORT || process.env.PORT || 3000,
dbUrl: process.env.ACKEE_MONGODB || process.env.MONGODB_URI,
allowOrigin: process.env.ACKEE_ALLOW_ORIGIN,
autoOrigin: process.env.ACKEE_AUTO_FQDN_ORIGIN === 'true',
username: process.env.ACKEE_USERNAME,
password: process.env.ACKEE_PASSWORD,
isDemoMode: process.env.ACKEE_DEMO === 'true',
Expand Down
14 changes: 14 additions & 0 deletions src/utils/domainFqNames.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict'

const isValidDomain = require('is-valid-domain')
const debouncePromise = require('debounce-promise')

const domains = require('../database/domains')

// A zero timeout is enough to ensure that this task
// runs only once on every API call. It's a task that would
// otherwise execute multiple times.
module.exports = debouncePromise(async () => {
const titles = (await domains.all()).map((d) => d.title)
return titles.filter((n) => isValidDomain(n, { subdomain: true, wildcard: false, allowUnicode: true }))
}, 0)
12 changes: 8 additions & 4 deletions src/utils/findMatchingOrigin.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
'use strict'

module.exports = (req, allowedOrigins) => {
if (allowedOrigins === '*') return '*'
const domainFqNames = require('./domainFqNames')

if (allowedOrigins != null) {
const origins = allowedOrigins.split(',')
module.exports = async (req, allowedOrigins, autoOrigin) => {
const allowedDomains = autoOrigin ? (await domainFqNames()).join(',') : allowedOrigins

if (allowedDomains === '*') return '*'

if (allowedDomains != null) {
const origins = allowedDomains.split(',')
return origins.find((origin) => origin.includes(req.headers.origin) || origin.includes(req.headers.host))
}
}
64 changes: 64 additions & 0 deletions test/serverWithAutoCors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict'

const test = require('ava')
const listen = require('test-listen')
const fetch = require('node-fetch')
const mockedEnv = require('mocked-env')

const server = require('../src/server')

const Domain = require('../src/models/Domain')
const { connectToDatabase, disconnectFromDatabase } = require('./resolvers/_utils')

const base = listen(server)

test.before(connectToDatabase)
test.after.always(disconnectFromDatabase)
test.beforeEach(async (t) => {
t.context.domain1 = await Domain.create({ title: 'fqdn.example.com' })
t.context.domain2 = await Domain.create({ title: 'not-an-fqdn' })
})
test.afterEach.always(async (t) => {
await Domain.findOneAndDelete({
id: t.context.domain1.id,
})
await Domain.findOneAndDelete({
id: t.context.domain2.id,
})
})

test('return cors headers for domain with fully qualifed domain name', async (t) => {
const url = new URL('/api', await base)
const origin = 'fqdn.example.com' // fake an origin for the test!

const restore = mockedEnv({
ACKEE_AUTO_FQDN_ORIGIN: 'true',
})

const { headers } = await fetch(url.href, { headers: { Host: origin } })

t.is(headers.get('Access-Control-Allow-Origin'), origin)
t.is(headers.get('Access-Control-Allow-Methods'), 'GET, POST, PATCH, OPTIONS')
t.is(headers.get('Access-Control-Allow-Headers'), 'Content-Type, Authorization, Time-Zone')
t.is(headers.get('Access-Control-Allow-Credentials'), 'true')

restore()
})

test('do not return cors headers for domain that is not an fqdn', async (t) => {
const url = new URL('/api', await base)
const origin = 'not-an-fqdn' // fake an origin for the test!

const restore = mockedEnv({
ACKEE_AUTO_FQDN_ORIGIN: 'true',
})

const { headers } = await fetch(url.href, { headers: { Host: origin } })

t.is(headers.get('Access-Control-Allow-Origin'), null)
t.is(headers.get('Access-Control-Allow-Methods'), null)
t.is(headers.get('Access-Control-Allow-Headers'), null)
t.is(headers.get('Access-Control-Allow-Credentials'), null)

restore()
})
12 changes: 12 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4774,6 +4774,13 @@ is-url@^1.2.4:
resolved "https://registry.yarnpkg.com/is-url/-/is-url-1.2.4.tgz#04a4df46d28c4cff3d73d01ff06abeb318a1aa52"
integrity sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==

is-valid-domain@^0.0.20:
version "0.0.20"
resolved "https://registry.yarnpkg.com/is-valid-domain/-/is-valid-domain-0.0.20.tgz#8bb1317f2a5c0d00ca86d11eee6798587c43b5ac"
integrity sha512-Yd9oD7sgCycVvH8CHy5U4fLXibPwxVw2+diudYbT8ZfAiQDtW1H9WvPRR4+rtN9qOll+r+KAfO4SjO28OPpitA==
dependencies:
punycode "^1.4.1"

is-windows@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d"
Expand Down Expand Up @@ -6447,6 +6454,11 @@ pump@^3.0.0:
end-of-stream "^1.1.0"
once "^1.3.1"

punycode@^1.4.1:
version "1.4.1"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e"
integrity sha1-wNWmOycYgArY4esPpSachN1BhF4=

punycode@^2.1.0, punycode@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec"
Expand Down