1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00

fix: adds cors caching (#2522)

* This PR adds a configurable maxAge header to the CORS middleware. This
allows the preflight request to be cached so that we can reduce the
request load on our end for the frontend clients starting to utilise the
frontend api.
This commit is contained in:
Fredrik Strand Oseberg 2022-11-24 16:14:47 +01:00 committed by GitHub
parent d63f5d9a4b
commit 5d52216d53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 27 additions and 6 deletions

View File

@ -2,6 +2,7 @@
exports[`should create default config 1`] = `
{
"accessControlMaxAge": 172800,
"additionalCspAllowedDomains": {
"defaultSrc": [],
"fontSrc": [],

View File

@ -80,7 +80,7 @@ export default async function getApp(
`${baseUriPath}/api/frontend*`,
conditionalMiddleware(
() => config.flagResolver.isEnabled('embedProxy'),
corsOriginMiddleware(services),
corsOriginMiddleware(services, config),
),
);

View File

@ -450,6 +450,10 @@ export function createConfig(options: IUnleashOptions): IUnleashConfig {
DEFAULT_STRATEGY_SEGMENTS_LIMIT,
);
const accessControlMaxAge = options.accessControlMaxAge
? options.accessControlMaxAge
: parseEnvVarNumber(process.env.ACCESS_CONTROL_MAX_AGE, 172800);
const clientFeatureCaching = loadClientCachingOptions(options);
return {
@ -481,6 +485,7 @@ export function createConfig(options: IUnleashOptions): IUnleashConfig {
segmentValuesLimit,
strategySegmentsLimit,
clientFeatureCaching,
accessControlMaxAge,
};
}

View File

@ -1,6 +1,6 @@
import { RequestHandler } from 'express';
import cors from 'cors';
import { IUnleashServices } from '../types';
import { IUnleashConfig, IUnleashServices } from '../types';
export const allowRequestOrigin = (
requestOrigin: string,
@ -13,9 +13,10 @@ export const allowRequestOrigin = (
// Check the request's Origin header against a list of allowed origins.
// The list may include '*', which `cors` does not support natively.
export const corsOriginMiddleware = ({
settingService,
}: Pick<IUnleashServices, 'settingService'>): RequestHandler => {
export const corsOriginMiddleware = (
{ settingService }: Pick<IUnleashServices, 'settingService'>,
config: IUnleashConfig,
): RequestHandler => {
return cors(async (req, callback) => {
try {
const { frontendApiOrigins = [] } =
@ -25,6 +26,7 @@ export const corsOriginMiddleware = ({
req.header('Origin'),
frontendApiOrigins,
),
maxAge: config.accessControlMaxAge,
});
} catch (error) {
callback(error);

View File

@ -54,7 +54,7 @@ export default class ProxyController extends Controller {
// Support CORS requests for the frontend endpoints.
// Preflight requests are handled in `app.ts`.
this.app.use(corsOriginMiddleware(services));
this.app.use(corsOriginMiddleware(services, config));
this.route({
method: 'get',

View File

@ -117,6 +117,7 @@ export interface IUnleashOptions {
inlineSegmentConstraints?: boolean;
clientFeatureCaching?: Partial<IClientCachingOption>;
flagResolver?: IFlagResolver;
accessControlMaxAge?: number;
}
export interface IEmailOption {
@ -202,4 +203,5 @@ export interface IUnleashConfig {
segmentValuesLimit: number;
strategySegmentsLimit: number;
clientFeatureCaching: IClientCachingOption;
accessControlMaxAge: number;
}

View File

@ -981,3 +981,13 @@ test('should return all features when specified', async () => {
});
});
});
test.only('should return maxAge header on options call', async () => {
await app.request
.options('/api/frontend')
.set('Origin', 'https://example.com')
.expect(204)
.expect((res) => {
expect(res.headers['access-control-max-age']).toBe('172800');
});
});

View File

@ -130,6 +130,7 @@ unleash.start(unleashOptions);
- `maxAge` - the time to cache features, set to 600 milliseconds by default - Overridable with (`CLIENT_FEATURE_CACHING_MAXAGE`) ) (accepts milliseconds)
- **frontendApi** - Configuration options for the [Unleash front-end API](../front-end-api.md).
- `refreshIntervalInMs` - how often (in milliseconds) front-end clients should refresh their data from the cache. Overridable with the `FRONTEND_API_REFRESH_INTERVAL_MS` environment variable.
- **accessControlMaxAge** - You can configure the max-age of the Access-Control-Max-Age header. Defaults to 172800 seconds. Overridable with the `ACCESS_CONTROL_MAX_AGE` environment variable.
You can also set the environment variable `ENABLED_ENVIRONMENTS` to a comma delimited string of environment names to override environments.