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 1 commit
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { Router, cors } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
import type { Context } from 'aws-lambda/handler'; | ||
|
||
const app = new Router(); | ||
|
||
// Basic CORS with default configuration | ||
// - origin: '*' | ||
// - allowMethods: ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'] | ||
// - allowHeaders: ['Authorization', 'Content-Type', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token'] | ||
// - exposeHeaders: [] | ||
// - credentials: false | ||
app.use(cors()); | ||
|
||
app.get('/api/users', async () => { | ||
return { users: ['user1', 'user2'] }; | ||
}); | ||
|
||
app.post('/api/users', async (_: unknown, { request }: { request: Request }) => { | ||
const body = await request.json(); | ||
return { created: true, user: body }; | ||
}); | ||
|
||
export const handler = async (event: unknown, context: Context) => { | ||
return app.resolve(event, context); | ||
}; |
27 changes: 27 additions & 0 deletions
27
examples/snippets/event-handler/rest/cors_custom_config.ts
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,27 @@ | ||
import { Router, cors } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
import type { Context } from 'aws-lambda/handler'; | ||
|
||
const app = new Router(); | ||
|
||
// Custom CORS configuration | ||
app.use(cors({ | ||
origin: 'https://myapp.com', | ||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], | ||
allowHeaders: ['Content-Type', 'Authorization', 'X-API-Key'], | ||
exposeHeaders: ['X-Total-Count', 'X-Request-ID'], | ||
credentials: true, | ||
maxAge: 3600, // 1 hour | ||
})); | ||
|
||
app.get('/api/data', async () => { | ||
return { data: 'protected endpoint' }; | ||
}); | ||
|
||
app.post('/api/data', async (_: unknown, { request }: { request: Request }) => { | ||
const body = await request.json(); | ||
return { created: true, data: body }; | ||
}); | ||
|
||
export const handler = async (event: unknown, context: Context) => { | ||
return app.resolve(event, context); | ||
}; |
40 changes: 40 additions & 0 deletions
40
examples/snippets/event-handler/rest/cors_dynamic_origin.ts
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,40 @@ | ||
import { Router, cors } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
// When building the package, this import will work correctly | ||
// import type { RequestContext } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
import type { Context } from 'aws-lambda/handler'; | ||
|
||
const app = new Router(); | ||
|
||
// Dynamic origin configuration with function | ||
app.use(cors({ | ||
origin: (origin?: string) => { | ||
// Allow requests from trusted domains | ||
const allowedOrigins = [ | ||
'https://app.mycompany.com', | ||
'https://admin.mycompany.com', | ||
'https://staging.mycompany.com', | ||
]; | ||
|
||
// Log the origin for debugging | ||
console.log('CORS request from:', origin); | ||
|
||
// Return boolean: true allows the origin, false denies it | ||
return origin ? allowedOrigins.includes(origin) : false; | ||
}, | ||
credentials: true, | ||
allowHeaders: ['Content-Type', 'Authorization'], | ||
})); | ||
|
||
// Route-specific CORS for public API | ||
app.get('/public/health', [cors({ origin: '*' })], async () => { | ||
return { status: 'healthy', timestamp: new Date().toISOString() }; | ||
}); | ||
|
||
// Protected endpoint using global CORS | ||
app.get('/api/user/profile', async () => { | ||
return { user: 'john_doe', email: '[email protected]' }; | ||
}); | ||
|
||
export const handler = async (event: unknown, context: Context) => { | ||
return app.resolve(event, context); | ||
}; |
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,219 @@ | ||
import type { Middleware, RequestContext, HandlerResponse } from '../../types/rest.js'; | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
import { HttpErrorCodes, HttpVerbs } from '../constants.js'; | ||
|
||
/** | ||
* Configuration options for CORS middleware | ||
*/ | ||
export interface CorsOptions { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
/** | ||
* The Access-Control-Allow-Origin header value. | ||
* Can be a string, array of strings, or a function that returns a string or boolean. | ||
* @default '*' | ||
*/ | ||
origin?: string | string[] | ((origin: string | undefined, reqCtx: RequestContext) => string | boolean); | ||
|
||
/** | ||
* The Access-Control-Allow-Methods header value. | ||
* @default ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'] | ||
*/ | ||
allowMethods?: string[]; | ||
|
||
/** | ||
* The Access-Control-Allow-Headers header value. | ||
* @default ['Authorization', 'Content-Type', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token'] | ||
*/ | ||
allowHeaders?: string[]; | ||
|
||
/** | ||
* The Access-Control-Expose-Headers header value. | ||
* @default [] | ||
*/ | ||
exposeHeaders?: string[]; | ||
|
||
/** | ||
* The Access-Control-Allow-Credentials header value. | ||
* @default false | ||
*/ | ||
credentials?: boolean; | ||
|
||
/** | ||
* The Access-Control-Max-Age header value in seconds. | ||
* Only applicable for preflight requests. | ||
*/ | ||
maxAge?: number; | ||
} | ||
|
||
/** | ||
* Resolved CORS configuration with all defaults applied | ||
*/ | ||
interface ResolvedCorsConfig { | ||
dcabib marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
origin: CorsOptions['origin']; | ||
allowMethods: string[]; | ||
allowHeaders: string[]; | ||
exposeHeaders: string[]; | ||
credentials: boolean; | ||
maxAge?: number; | ||
} | ||
|
||
/** | ||
* Default CORS configuration matching Python implementation | ||
*/ | ||
const DEFAULT_CORS_OPTIONS: Required<Omit<CorsOptions, 'maxAge'>> = { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
origin: '*', | ||
allowMethods: ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT'], | ||
allowHeaders: ['Authorization', 'Content-Type', 'X-Amz-Date', 'X-Api-Key', 'X-Amz-Security-Token'], | ||
exposeHeaders: [], | ||
credentials: false, | ||
}; | ||
|
||
/** | ||
* Resolves and validates the CORS configuration | ||
*/ | ||
function resolveConfiguration(userOptions: CorsOptions): ResolvedCorsConfig { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const config: ResolvedCorsConfig = { | ||
origin: userOptions.origin ?? DEFAULT_CORS_OPTIONS.origin, | ||
allowMethods: userOptions.allowMethods ?? DEFAULT_CORS_OPTIONS.allowMethods, | ||
allowHeaders: userOptions.allowHeaders ?? DEFAULT_CORS_OPTIONS.allowHeaders, | ||
exposeHeaders: userOptions.exposeHeaders ?? DEFAULT_CORS_OPTIONS.exposeHeaders, | ||
credentials: userOptions.credentials ?? DEFAULT_CORS_OPTIONS.credentials, | ||
maxAge: userOptions.maxAge, | ||
}; | ||
|
||
return config; | ||
} | ||
|
||
/** | ||
* Resolves the origin value based on the configuration | ||
*/ | ||
function resolveOrigin( | ||
originConfig: CorsOptions['origin'], | ||
requestOrigin: string | null | undefined, | ||
reqCtx: RequestContext | ||
): string { | ||
const origin = requestOrigin || undefined; | ||
|
||
if (typeof originConfig === 'function') { | ||
const result = originConfig(origin, reqCtx); | ||
if (typeof result === 'boolean') { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
return result ? (origin || '*') : ''; | ||
} | ||
return result; | ||
} | ||
|
||
if (Array.isArray(originConfig)) { | ||
return origin && originConfig.includes(origin) ? origin : ''; | ||
} | ||
|
||
if (typeof originConfig === 'string') { | ||
return originConfig; | ||
} | ||
|
||
return DEFAULT_CORS_OPTIONS.origin as string; | ||
dcabib marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
/** | ||
* Handles preflight OPTIONS requests | ||
*/ | ||
function handlePreflight(config: ResolvedCorsConfig, reqCtx: RequestContext): Response { | ||
const { request } = reqCtx; | ||
const requestOrigin = request.headers.get('Origin'); | ||
const resolvedOrigin = resolveOrigin(config.origin, requestOrigin, reqCtx); | ||
|
||
const headers = new Headers(); | ||
dcabib marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
if (resolvedOrigin) { | ||
headers.set('Access-Control-Allow-Origin', resolvedOrigin); | ||
} | ||
|
||
if (config.allowMethods.length > 0) { | ||
headers.set('Access-Control-Allow-Methods', config.allowMethods.join(', ')); | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
if (config.allowHeaders.length > 0) { | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
headers.set('Access-Control-Allow-Headers', config.allowHeaders.join(', ')); | ||
} | ||
|
||
if (config.credentials) { | ||
headers.set('Access-Control-Allow-Credentials', 'true'); | ||
} | ||
|
||
if (config.maxAge !== undefined) { | ||
headers.set('Access-Control-Max-Age', config.maxAge.toString()); | ||
} | ||
|
||
return new Response(null, { | ||
status: HttpErrorCodes.NO_CONTENT, // 204 | ||
headers, | ||
}); | ||
} | ||
|
||
/** | ||
* Adds CORS headers to regular requests | ||
*/ | ||
function addCorsHeaders(config: ResolvedCorsConfig, reqCtx: RequestContext): void { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const { request, res } = reqCtx; | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const requestOrigin = request.headers.get('Origin'); | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const resolvedOrigin = resolveOrigin(config.origin, requestOrigin, reqCtx); | ||
|
||
if (resolvedOrigin) { | ||
res.headers.set('Access-Control-Allow-Origin', resolvedOrigin); | ||
} | ||
|
||
if (config.exposeHeaders.length > 0) { | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
res.headers.set('Access-Control-Expose-Headers', config.exposeHeaders.join(', ')); | ||
} | ||
|
||
if (config.credentials) { | ||
res.headers.set('Access-Control-Allow-Credentials', 'true'); | ||
} | ||
} | ||
|
||
/** | ||
* Creates a CORS middleware that adds appropriate CORS headers to responses | ||
* and handles OPTIONS preflight requests. | ||
* | ||
* @param options - CORS configuration options | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
* @returns A middleware function that handles CORS | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
* | ||
* @example | ||
* ```typescript | ||
* import { cors } from '@aws-lambda-powertools/event-handler/rest'; | ||
* | ||
* // 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); | ||
* } | ||
* })); | ||
* ``` | ||
*/ | ||
export const cors = (options: CorsOptions = {}): Middleware => { | ||
const config = resolveConfiguration(options); | ||
|
||
return async (_params: Record<string, string>, reqCtx: RequestContext, next: () => Promise<HandlerResponse | void>) => { | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
const { request } = reqCtx; | ||
const method = request.method.toUpperCase(); | ||
svozza marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
// Handle preflight OPTIONS request | ||
if (method === HttpVerbs.OPTIONS) { | ||
return handlePreflight(config, reqCtx); | ||
sdangol marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} | ||
|
||
// Continue to next middleware/handler first | ||
await next(); | ||
svozza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Add CORS headers to the response after handler | ||
addCorsHeaders(config, reqCtx); | ||
svozza marked this conversation as resolved.
Outdated
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,2 @@ | ||
export { cors } from './cors.js'; | ||
export type { CorsOptions } from './cors.js'; | ||
dcabib marked this conversation as resolved.
Outdated
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
Oops, something went wrong.
Oops, something went wrong.
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.