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 cacheControl to control caching in CDN #252

Merged
merged 3 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ You can use it as is without passing any option or you can configure it as expla
* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: `'Content-Range,X-Content-Range'`) or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed.
* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. In seconds. Set to an integer to pass the header, otherwise it is omitted.
* `cacheControl`: Configures the **Cache-Control** header for CORS preflight responses. Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`, or set to a string to pass the header as `Cache-Control: ${cacheControl}` (fully define the header value), otherwise the header is omitted.
* `preflightContinue`: Pass the CORS preflight response to the route handler (default: `false`).
* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.
* `preflight`: if needed you can entirely disable preflight by passing `false` here (default: `true`).
Expand Down
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,17 @@ function handleCorsOptionsCallbackDelegator (optionsResolver, fastify, req, repl
})
}

/**
* @param {import('./types').FastifyCorsOptions} opts
*/
function normalizeCorsOptions (opts) {
const corsOptions = Object.assign({}, defaultOptions, opts)
if (Array.isArray(opts.origin) && opts.origin.indexOf('*') !== -1) {
corsOptions.origin = '*'
}
if (Number.isInteger(Number(corsOptions.cacheControl)) === true) {
corsOptions.cacheControl = `max-age=${corsOptions.cacheControl}`
}
return corsOptions
}

Expand Down Expand Up @@ -235,6 +241,10 @@ function addPreflightHeaders (req, reply, corsOptions) {
if (corsOptions.maxAge !== null) {
reply.header('Access-Control-Max-Age', String(corsOptions.maxAge))
}

if (corsOptions.cacheControl && (typeof corsOptions.cacheControl === 'string')) {
Copy link
Contributor

Choose a reason for hiding this comment

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

@jsumners

do we still need a type check?

Suggested change
if (corsOptions.cacheControl && (typeof corsOptions.cacheControl === 'string')) {
if (corsOptions.cacheControl) {

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, the normalization has cleared this behaviour

cc @brettwillis

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Eomm are you agreeing to apply the suggested change? Initially we had cacheControl only applied if the value was string or number. If we remove the type check then we could end up applying any non-number value.

We should either (1) keep the check, (2) coerce the "any truthy value" to string e.g. String(cacheControl) and apply it, or (3) patch normalisation to also set cacheControl to null if it is not a string (and not a number).

Copy link
Member

Choose a reason for hiding this comment

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

This is-string check needs to happen in order to not add an invalid header value (still possible, but the module has done as much as it really can). Test should be added to show this if they do not already exist.

Copy link
Member

Choose a reason for hiding this comment

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

Test should be added to show this if they do not already exist.

This, or just the normalizeCorsOptions do the full normalization :D

This check protects us if the user provides a function or and object.
Right now - it is just ignored. Let's add a test and it is fine too

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I discovered that this Number.isInteger(Number(corsOptions.cacheControl)) behaviour means that a boolean values are coerced to max-age=1 and max-age=0 respectively, which is probably not desired.

Should we add a check to exclude booleans e.g. Number.isInteger(Number(corsOptions.cacheControl)) && (typeof corsOptions.cacheControl !== 'boolean')?

Or only consider values that are strictly a number (don't coerce to number) e.g. Number.isInteger(corsOptions.cacheControl)?

Copy link
Member

Choose a reason for hiding this comment

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

Either accept a string or an integer. Do not accept anything else.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Either accept a string or an integer. Do not accept anything else.

Ok, done.

Also I moved the is-string check to the normalisation function, so there is one less conditional check being run per-request.

reply.header('Cache-Control', corsOptions.cacheControl)
}
}

function resolveOriginWrapper (fastify, origin) {
Expand Down
15 changes: 11 additions & 4 deletions test/cors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ test('Should add cors headers (custom values)', t => {
credentials: true,
exposedHeaders: ['foo', 'bar'],
allowedHeaders: ['baz', 'woo'],
maxAge: 123
maxAge: 123,
cacheControl: 321
})

fastify.get('/', (req, reply) => {
Expand All @@ -65,6 +66,7 @@ test('Should add cors headers (custom values)', t => {
'access-control-allow-methods': 'GET',
'access-control-allow-headers': 'baz, woo',
'access-control-max-age': '123',
'cache-control': 'max-age=321',
'content-length': '0'
})
})
Expand Down Expand Up @@ -96,14 +98,16 @@ test('Should support dynamic config (callback)', t => {
credentials: true,
exposedHeaders: ['foo', 'bar'],
allowedHeaders: ['baz', 'woo'],
maxAge: 123
maxAge: 123,
cacheControl: 456
}, {
origin: 'sample.com',
methods: 'GET',
credentials: true,
exposedHeaders: ['zoo', 'bar'],
allowedHeaders: ['baz', 'foo'],
maxAge: 321
maxAge: 321,
cacheControl: 'public, max-age=456'
}]

const fastify = Fastify()
Expand Down Expand Up @@ -164,6 +168,7 @@ test('Should support dynamic config (callback)', t => {
'access-control-allow-methods': 'GET',
'access-control-allow-headers': 'baz, foo',
'access-control-max-age': '321',
'cache-control': 'public, max-age=456',
'content-length': '0'
})
})
Expand Down Expand Up @@ -197,7 +202,8 @@ test('Should support dynamic config (Promise)', t => {
credentials: true,
exposedHeaders: ['zoo', 'bar'],
allowedHeaders: ['baz', 'foo'],
maxAge: 321
maxAge: 321,
cacheControl: 'public, max-age=456'
}]

const fastify = Fastify()
Expand Down Expand Up @@ -258,6 +264,7 @@ test('Should support dynamic config (Promise)', t => {
'access-control-allow-methods': 'GET',
'access-control-allow-headers': 'baz, foo',
'access-control-max-age': '321',
'cache-control': 'public, max-age=456',
'content-length': '0'
})
})
Expand Down
7 changes: 7 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ declare namespace fastifyCors {
* Set to an integer to pass the header, otherwise it is omitted.
*/
maxAge?: number;
/**
* Configures the Cache-Control header for CORS preflight responses.
* Set to an integer to pass the header as `Cache-Control: max-age=${cacheControl}`,
* or set to a string to pass the header as `Cache-Control: ${cacheControl}` (fully define
* the header value), otherwise the header is omitted.
*/
cacheControl?: number | string;
/**
* Pass the CORS preflight response to the route handler (default: false).
*/
Expand Down
33 changes: 28 additions & 5 deletions types/index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import fastify from 'fastify'
import fastify, { FastifyRequest } from 'fastify'
import { expectType } from 'tsd'
import fastifyCors, {
FastifyCorsOptions,
FastifyCorsOptionsDelegate,
FastifyCorsOptionsDelegatePromise,
FastifyPluginOptionsDelegate,
Expand All @@ -18,6 +19,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: 'authorization',
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -31,6 +33,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 'public, max-age=3500',
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -44,6 +47,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -57,6 +61,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -70,6 +75,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -83,6 +89,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -104,6 +111,7 @@ app.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
optionsSuccessStatus: 200,
preflight: false,
strictPreflight: false
Expand All @@ -120,6 +128,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: 'authorization',
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -133,6 +142,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -146,6 +156,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -159,6 +170,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -172,6 +184,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -185,6 +198,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -204,6 +218,7 @@ appHttp2.register(fastifyCors, {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -218,6 +233,7 @@ appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegate => (req, cb) => {
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -233,6 +249,7 @@ appHttp2.register(fastifyCors, (): FastifyCorsOptionsDelegatePromise => (req) =>
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand All @@ -248,6 +265,7 @@ const delegate: FastifyPluginOptionsDelegate<FastifyCorsOptionsDelegatePromise>
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 13000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
Expand Down Expand Up @@ -276,32 +294,37 @@ appHttp2.register(fastifyCors, {

appHttp2.register(fastifyCors, {
hook: 'preParsing',
delegator: () => {
return {
delegator: (req, cb) => {
if (req.url.startsWith('/some-value')) {
cb(new Error())
}
cb(null, {
origin: [/\*/, /something/],
allowedHeaders: ['authorization', 'content-type'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 12000,
preflightContinue: false,
optionsSuccessStatus: 200,
preflight: false,
strictPreflight: false
}
})
}
})

appHttp2.register(fastifyCors, {
hook: 'preParsing',
delegator: () => {
delegator: async (req: FastifyRequest): Promise<FastifyCorsOptions> => {
return {
origin: [/\*/, /something/],
allowedHeaders: ['authorization', 'content-type'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
credentials: true,
exposedHeaders: ['authorization'],
maxAge: 13000,
cacheControl: 'public, max-age=3500',
preflightContinue: false,
brettwillis marked this conversation as resolved.
Show resolved Hide resolved
optionsSuccessStatus: 200,
preflight: false,
Expand Down