generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 175
feat(event-handler): add CORS middleware support #4477
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2a9fd4c
feat(event-handler): add CORS middleware for REST API
dani-abib c06500b
fix: address all review feedback
dani-abib eb99adf
Addressed the remaining feedbacks
sdangol 1456e7b
Merge branch 'main' into feat/cors-middleware
sdangol dde1477
Removed unused variable
sdangol 180ae68
added the headers check middleware
sdangol f2fa687
optimized tests
sdangol bec305c
Fixed test formats
sdangol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import type { | ||
CorsOptions, | ||
Middleware, | ||
} from '../../types/rest.js'; | ||
import { | ||
DEFAULT_CORS_OPTIONS, | ||
HttpErrorCodes, | ||
HttpVerbs, | ||
} from '../constants.js'; | ||
|
||
/** | ||
* Resolves the origin value based on the configuration | ||
*/ | ||
const resolveOrigin = ( | ||
originConfig: NonNullable<CorsOptions['origin']>, | ||
requestOrigin: string | null, | ||
): string => { | ||
if (Array.isArray(originConfig)) { | ||
return requestOrigin && originConfig.includes(requestOrigin) ? requestOrigin : ''; | ||
} | ||
return originConfig; | ||
}; | ||
|
||
/** | ||
* Creates a CORS middleware that adds appropriate CORS headers to responses | ||
* and handles OPTIONS preflight requests. | ||
* | ||
* @example | ||
* ```typescript | ||
* import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
* import { cors } from '@aws-lambda-powertools/event-handler/experimental-rest/middleware'; | ||
* | ||
* const app = new Router(); | ||
* | ||
* // Use default configuration | ||
* app.use(cors()); | ||
* | ||
* // Custom configuration | ||
* app.use(cors({ | ||
* origin: 'https://example.com', | ||
* allowMethods: ['GET', 'POST'], | ||
* credentials: true, | ||
* })); | ||
* | ||
* // Dynamic origin with function | ||
* app.use(cors({ | ||
* origin: (origin, reqCtx) => { | ||
* const allowedOrigins = ['https://app.com', 'https://admin.app.com']; | ||
* return origin && allowedOrigins.includes(origin); | ||
* } | ||
* })); | ||
* ``` | ||
* | ||
* @param options.origin - The origin to allow requests from | ||
* @param options.allowMethods - The HTTP methods to allow | ||
* @param options.allowHeaders - The headers to allow | ||
* @param options.exposeHeaders - The headers to expose | ||
* @param options.credentials - Whether to allow credentials | ||
* @param options.maxAge - The maximum age for the preflight response | ||
*/ | ||
export const cors = (options?: CorsOptions): Middleware => { | ||
const config = { | ||
...DEFAULT_CORS_OPTIONS, | ||
...options | ||
}; | ||
|
||
return async (_params, reqCtx, next) => { | ||
const requestOrigin = reqCtx.request.headers.get('Origin'); | ||
const resolvedOrigin = resolveOrigin(config.origin, requestOrigin); | ||
|
||
reqCtx.res.headers.set('access-control-allow-origin', resolvedOrigin); | ||
if (resolvedOrigin !== '*') { | ||
reqCtx.res.headers.set('Vary', 'Origin'); | ||
} | ||
config.allowMethods.forEach(method => { | ||
reqCtx.res.headers.append('access-control-allow-methods', method); | ||
}); | ||
config.allowHeaders.forEach(header => { | ||
reqCtx.res.headers.append('access-control-allow-headers', header); | ||
}); | ||
config.exposeHeaders.forEach(header => { | ||
reqCtx.res.headers.append('access-control-expose-headers', header); | ||
}); | ||
reqCtx.res.headers.set('access-control-allow-credentials', config.credentials.toString()); | ||
if (config.maxAge !== undefined) { | ||
reqCtx.res.headers.set('access-control-max-age', config.maxAge.toString()); | ||
} | ||
|
||
// Handle preflight OPTIONS request | ||
if (reqCtx.request.method === HttpVerbs.OPTIONS && reqCtx.request.headers.has('Access-Control-Request-Method')) { | ||
return new Response(null, { | ||
status: HttpErrorCodes.NO_CONTENT, | ||
headers: reqCtx.res.headers, | ||
}); | ||
} | ||
await next(); | ||
svozza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export { compress } from './compress.js'; | ||
export { cors } from './cors.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
96 changes: 96 additions & 0 deletions
96
packages/event-handler/tests/unit/rest/middleware/cors.test.ts
dcabib marked this conversation as resolved.
Show resolved
Hide resolved
sdangol marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import { beforeEach, describe, expect, it } from 'vitest'; | ||
import context from '@aws-lambda-powertools/testing-utils/context'; | ||
import { cors } from '../../../../src/rest/middleware/cors.js'; | ||
import { createTestEvent, createHeaderCheckMiddleware } from '../helpers.js'; | ||
import { Router } from '../../../../src/rest/Router.js'; | ||
import { DEFAULT_CORS_OPTIONS } from 'src/rest/constants.js'; | ||
|
||
describe('CORS Middleware', () => { | ||
const getRequestEvent = createTestEvent('/test', 'GET'); | ||
const optionsRequestEvent = createTestEvent('/test', 'OPTIONS'); | ||
let app: Router; | ||
|
||
const customCorsOptions = { | ||
origin: 'https://example.com', | ||
allowMethods: ['GET', 'POST'], | ||
allowHeaders: ['Authorization', 'Content-Type'], | ||
credentials: true, | ||
exposeHeaders: ['Authorization', 'X-Custom-Header'], | ||
maxAge: 86400, | ||
}; | ||
|
||
const expectedDefaultHeaders = { | ||
"access-control-allow-credentials": "false", | ||
"access-control-allow-headers": "Authorization, Content-Type, X-Amz-Date, X-Api-Key, X-Amz-Security-Token", | ||
"access-control-allow-methods": "DELETE, GET, HEAD, PATCH, POST, PUT", | ||
"access-control-allow-origin": "*", | ||
}; | ||
|
||
beforeEach(() => { | ||
app = new Router(); | ||
app.use(cors()); | ||
}); | ||
|
||
it('uses default configuration when no options are provided', async () => { | ||
const corsHeaders: { [key: string]: string } = {}; | ||
app.get('/test', [createHeaderCheckMiddleware(corsHeaders)], async () => ({ success: true })); | ||
|
||
const result = await app.resolve(getRequestEvent, context); | ||
|
||
expect(result.headers?.['access-control-allow-origin']).toEqual(DEFAULT_CORS_OPTIONS.origin); | ||
expect(result.multiValueHeaders?.['access-control-allow-methods']).toEqual(DEFAULT_CORS_OPTIONS.allowMethods); | ||
expect(result.multiValueHeaders?.['access-control-allow-headers']).toEqual(DEFAULT_CORS_OPTIONS.allowHeaders); | ||
expect(result.headers?.['access-control-allow-credentials']).toEqual(DEFAULT_CORS_OPTIONS.credentials.toString()); | ||
expect(corsHeaders).toMatchObject(expectedDefaultHeaders); | ||
}); | ||
|
||
it('merges user options with defaults', async () => { | ||
const corsHeaders: { [key: string]: string } = {}; | ||
const customApp = new Router(); | ||
customApp.get('/test', [cors(customCorsOptions), createHeaderCheckMiddleware(corsHeaders)], async () => ({ success: true })); | ||
|
||
const result = await customApp.resolve(getRequestEvent, context); | ||
|
||
expect(result.headers?.['access-control-allow-origin']).toEqual('https://example.com'); | ||
expect(result.multiValueHeaders?.['access-control-allow-methods']).toEqual(['GET', 'POST']); | ||
expect(result.multiValueHeaders?.['access-control-allow-headers']).toEqual(['Authorization', 'Content-Type']); | ||
expect(result.headers?.['access-control-allow-credentials']).toEqual('true'); | ||
expect(result.multiValueHeaders?.['access-control-expose-headers']).toEqual(['Authorization', 'X-Custom-Header']); | ||
expect(result.headers?.['access-control-max-age']).toEqual('86400'); | ||
expect(corsHeaders).toMatchObject({ | ||
"access-control-allow-credentials": "true", | ||
"access-control-allow-headers": "Authorization, Content-Type", | ||
"access-control-allow-methods": "GET, POST", | ||
"access-control-allow-origin": "https://example.com", | ||
}); | ||
}); | ||
|
||
it.each([ | ||
['matching', 'https://app.com', 'https://app.com'], | ||
['non-matching', 'https://non-matching.com', ''] | ||
])('handles array origin with %s request', async (_, origin, expected) => { | ||
const customApp = new Router(); | ||
customApp.get('/test', [cors({ origin: ['https://app.com', 'https://admin.app.com'] })], async () => ({ success: true })); | ||
|
||
const result = await customApp.resolve(createTestEvent('/test', 'GET', { 'Origin': origin }), context); | ||
|
||
expect(result.headers?.['access-control-allow-origin']).toEqual(expected); | ||
}); | ||
|
||
it('handles OPTIONS preflight requests', async () => { | ||
app.options('/test', async () => ({ foo: 'bar' })); | ||
|
||
const result = await app.resolve(createTestEvent('/test', 'OPTIONS', { 'Access-Control-Request-Method': 'GET' }), context); | ||
|
||
expect(result.statusCode).toBe(204); | ||
}); | ||
|
||
it('calls the next middleware if the Access-Control-Request-Method is not present', async () => { | ||
const corsHeaders: { [key: string]: string } = {}; | ||
app.options('/test', [createHeaderCheckMiddleware(corsHeaders)], async () => ({ success: true })); | ||
|
||
await app.resolve(optionsRequestEvent, context); | ||
|
||
expect(corsHeaders).toMatchObject(expectedDefaultHeaders); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.