joostfarla / serverless-cors-plugin Goto Github PK
View Code? Open in Web Editor NEWServerless CORS Plugin - Managing Cross-origin resource sharing (CORS) policies
License: ISC License
Serverless CORS Plugin - Managing Cross-origin resource sharing (CORS) policies
License: ISC License
Hey
GET and POST requests work correctly, but PUT requests fail consistently.
I tested this by creating a POST endpoint, validating that the response worked correctly, and then changing the method to a PUT and redeploying. The request immediately failed with an error.
It's my understanding that in order to add CORS to all endpoints you need to add cors
to each function's custom
property. Since the general use-case is that you want to either enable CORS on your entire API, or not at all, it would be nice if we could set this at a higher level that would be applied to all endpoints. We could allow setting the local cors
property to override the global setting for the rare case you need it to be different/disabled.
If this is currently possible, I apolgise, and would greatly appreciate being pointed at documentation for this. :)
For some reason, allowCredentials option is not working on s3.amazonaws.com. Looks like some trouble with OPTIONS part of request.
Anyway ,changing
if (populatedEndpoint.method === 'GET' && !_.isUndefined(policy.allowCredentials)) {
to
if ( !_.isUndefined(policy.allowCredentials)) {
solved the issue.
I'm posting this just in case someone may face similar problem in future.
I'm using temporary credentials from cognito to call API gateway:
var apigClient = apigClientFactory.newClient(
{
accessKey: AWS.config.credentials.accessKeyId,
secretKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken,
region: AWS.config.region
}
);
Is it possible to forward these credentials from API GW to Lambda?
I see the option "Invoke with caller credentials" in the console, but after using serverless-cors-plugin to update my API, this option is always disabled. So I guess there is a parameter for this?
When I manually check "Invoke with caller credentials" in the console after all CORS were correct, I think the function messes up the CORS settings because then I get "No 'Access-Control-Allow-Origin' header is present on the requested resource.".
I tried with "allowCredentials": true, but does not seem to work.
When using the cors plugin I always get the following error
Response to preflight request doesn't pass access control check: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
I'm using a very basic s-function config:
{
"functions": {
"eio": {
"custom": {
"excludePatterns": [],
"envVars": [],
"cors": {
"allow": {
"origin": "*"
}
}
},
"handler": "modules/falcor/eio/handler.handler",
"timeout": 6,
"memorySize": 1024,
"eventSourceArn": "",
"endpoints": [
{
"path": "falcor/eio",
"method": "GET",
"authorizationType": "none",
"apiKeyRequired": false,
"requestParameters": {},
"requestTemplates": {
"application/json": ""
},
"responses": {
"400": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {},
"responseModels": {},
"responseTemplates": {
"application/json": ""
}
}
}
}
]
}
}
}
and I have added the plugin to the s-project.json. Its clearly doing something because the OPTION method gets created in the API gateway which wouldn't happen witth adding the cors plugin.
I am running the latest versions of sls and CORS plugin. I have placed my response mappings into s_templates.json, and reference them in s_function as "responses": "$${defaultResponses}"
. So when I try to use CORS on an endpoint with such mapping, the plugin throws an error
serverless:lib.node_modules.serverless.lib.actions.EndpointDeploy TypeError: Cannot assign to read only property 'responseParameters' of $ at /Users/abc/Apps/my_project/node_modules/serverless-cors-plugin/src/index.js:51:39
It is probably due to the fact sls doesn't replace $$ variable with its corespondent value at this stage.
And if I replace $$ variable with proper mappings, it works, only OPTIONS method is missing.
Was seeing an error when trying to deploy - debugged it as a lodash error when trying to call _.pluck on line 141 of index.js in the _createPreflightEndpoints function.
Checking lodash documentation it seems they removed the _.pluck call in version 4.0.0 and your plugin calls for "lodash": "^4.0.0" which causes this error. I changed the lodash dependency to 3.10.1 and all works as expected.
I've just installed this plugin on a Serverless 0.5.6 project and it does create the OPTIONS endpoints, but my HTTP requests are failing with the following error message:
Fetch API cannot load .... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
However, if I go in to the AWS Console and use the "Enable CORS" feature then it all works as expected.
I also noticed that endpoint remove
doesn't remove the OPTIONS endpoints.
Hello all,
the CORS headers are working correctly for me as long as i do not use a custom authorizer function. Do you have any idea why? This is my (broken) s-function.json
...
"custom": {
"excludePatterns": [],
"cors": {
"allowOrigin": "*",
"allowHeaders": [
"Content-Type",
"X-Amz-Date",
"Authorization",
"X-Api-Key"
]
},
"optimize": {OPTIMIZE OPTIONS},
"endpoints": [
{
"path": "scrape/website",
"method": "GET",
"type": "AWS",
"authorizationType": "custom",
"authorizerFunction": "authorize",
"apiKeyRequired": false,
"requestParameters": {},
...
It breaks my integration.
Full Setup:
I did deploy the https://github.com/laardee/serverless-authentication-boilerplate boilerplate and want to use the custom authorize
function. I added it (as shown above). Then the fetch request from my frontent (adding the Authorization
header) throws the following error:
.../?url=https://github.com&selector=%7B%22V1%22:%22title%22%7D. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://dev.auto-scraper.com.s3-website.eu-central-1.amazonaws.com' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
When i do an OPTIONS request to the same URL with Postman, i get 200 OK and the Correct headers are shown...
Also looking at the AWS Console Everything seams normal...
Any ideas? What am i doing wrong?
The OPTIONS endpoints are not being deployed by default. I figured out by looking at the plugin source code that you need to add a --all
flag to the command to get the OPTIONS endpoints to deploy.
As discussed with @chadkouse in #1.
When providing authenticated requests with the withCredentials
option, CORS requires you to set a specific host in the Access-Control-Allow-Origin header. CORS doen not allow a wildcard (*) origin for authenticated requests.
We could implement an option which dynamically sets the Access-Control-Allow-Origin
header equal to the request's Origin
. This would enable to allow authenticated cross-origin requests coming from anywhere.
So - it looks like I can add the headers to the POST integration for my Lambda Proxy Integration - but I'm not sure how I should be doing this for the OPTIONS requests for endpoints. From what I can tell, I've configured things correctly, but I'm still getting {"message": "Internal server error"}
back from the OPTIONS endpoint specifically.
There are lot's of breaking changes in the new version of serverless released yesterday which is what is causing this.
Maybe the CORS-functionality in this plugin could be achieved with the new templates introduced in serverless 0.1.0?
https://github.com/serverless/serverless/releases
/User/X/.node/lib/node_modules/serverless/node_modules/bluebird/js/main/async.js:43
fn = function () { throw arg; };
^
TypeError: Cannot read property 'region' of undefined
at ServerlessCors.addPreflightRequests (/User/X/Code/chatter/node_modules/serverless-cors-plugin/src/index.js:68:29)
From previous event:
at /User/X/.node/lib/node_modules/serverless/lib/Serverless.js:177:25
at Array.reduce (native)
at Serverless._execute (/User/X/.node/lib/node_modules/serverless/lib/Serverless.js:176:26)
at Object.actions.(anonymous function) [as endpointDeploy] (/User/X/.node/lib/node_modules/serverless/lib/Serverless.js:378:20)
at /User/X/.node/lib/node_modules/serverless/lib/actions/DashDeploy.js:288:34
From previous event:
at DashDeploy._deploy (/User/X/.node/lib/node_modules/serverless/lib/actions/DashDeploy.js:283:10)
From previous event:
at DashDeploy.dashDeploy (/User/X/.node/lib/node_modules/serverless/lib/actions/DashDeploy.js:132:10)
From previous event:
at /User/X/.node/lib/node_modules/serverless/lib/Serverless.js:152:29
at Array.reduce (native)
at /User/X/.node/lib/node_modules/serverless/lib/Serverless.js:151:30
at processImmediate [as _immediateCallback] (timers.js:384:17)
From previous event:
at Serverless._execute (/User/X/.node/lib/node_modules/serverless/lib/Serverless.js:149:10)
at Serverless.actions.(anonymous function) (/User/X/.node/lib/node_modules/serverless/lib/Serverless.js:378:20)
at Serverless.command (/User/X/.node/lib/node_modules/serverless/lib/Serverless.js:347:38)
at Object.<anonymous> (/User/X/.node/lib/node_modules/serverless/bin/serverless:16:12)
at Module._compile (module.js:399:26)
at Object.Module._extensions..js (module.js:406:10)
at Module.load (module.js:345:32)
at Function.Module._load (module.js:302:12)
at Function.Module.runMain (module.js:431:10)
at startup (node.js:141:18)
at node.js:977:3
Is there any reason for not having OPTIONS created with Mock endpoint? Is it on the RoadMap or there is technical issue with that?
Really sorry about asking it, I remember some discussions in gitter, but totally forgot the outcome of them.
For some reason In get an error when deploying the options endpoints lately.
No idea why. The error is:
Serverless: OPTIONS - someEndpoint: Invalid model name specified: application/json;charset=UTF-8=Empty
When I run new version of sls and cors plugin, I get the following error
ALUAs-MBP:users g_alua$ sls endpoint deploy --all
/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:48
fn = function () { throw arg; };
^
ServerlessError: Missing required config.sPath
at new ServerlessError (/usr/local/lib/node_modules/serverless/lib/ServerlessError.js:17:11)
at new ServerlessEndpoint (/usr/local/lib/node_modules/serverless/lib/ServerlessEndpoint.js:24:142)
at /Users/g_alua/App/monei/node_modules/serverless-cors-plugin/src/index.js:98:29
at arrayEach (/Users/g_alua/App/monei/node_modules/lodash/lodash.js:474:11)
at Function.forEach (/Users/g_alua/App/monei/node_modules/lodash/lodash.js:7633:11)
at ServerlessCors.addPreflightRequests (/Users/g_alua/App/monei/node_modules/serverless-cors-plugin/src/index.js:78:9)
From previous event:
at /usr/local/lib/node_modules/serverless/lib/Serverless.js:156:29
at Array.reduce (native)
at /usr/local/lib/node_modules/serverless/lib/Serverless.js:155:30
at processImmediate [as _immediateCallback] (timers.js:383:17)
From previous event:
at Serverless._execute (/usr/local/lib/node_modules/serverless/lib/Serverless.js:153:10)
I checked sls source code and seems that now in Endpoint class they validate sPath.
((!config.component || !config.module || !config.function || !config.endpointPath || !config.endpointMethod) && !config.sPath)
When you setup CORS on a function or module that has a path or query string parameter, the Options method is added successfully with the header responses needed for CORS, but the path and query parameters are not added to the method request settings so whenever the API is exported as a Swagger (or other template) via the Stage settings, the template has syntax errors and does not resolve all references.
If the path and query parameters were passed down to the created options method request, even though they're not used, the Swagger templates and API exports would generate fully and not show syntax errors and warnings.
After including plugn in project I've got error:
Type Error ---------------------------------------------
S.getServerlessPath is not a function
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Get Support --------------------------------------------
Docs: docs.serverless.com
Bugs: github.com/serverless/serverless/issues
Please report this error. We think it might be a bug.
Your Environment Information -----------------------------
OS: win32
Node Version: 7.2.0
Serverless Version: 1.7.0
Looks like another plugin had same issue: serverless/serverless-client-s3#43
Hi,
Is there something significant that changed? I was using serverless v0.4.2 together with serverless-cors-plugin v0.2.1 and then a "serverless endpoint deploy --all" worked perfectly to include the preflight checks etc.. when run in the root of the project.
Now when using v0.4.2 with v0.3.1, the same command suddenly crashes with following error:
C:\DATA\serverless-4kgaw\nodejscomponent\resource\show>serverless endpoint deploy --all
C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\node_modules\bluebird\js\main\async.js:43
fn = function () { throw arg; };
^
ServerlessError: Missing required config.component, config.module, config.function, config.endpointMethod, config.endpointPath
at new ServerlessError (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\ServerlessError.js:17:11)
at new ServerlessEndpoint (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\ServerlessEndpoint.js:24:122)
at C:\DATA\serverless-4kgaw\node_modules\serverless-cors-plugin\src\index.js:98:29
at arrayEach (C:\DATA\serverless-4kgaw\node_modules\serverless-cors-plugin\node_modules\lodash\lodash.js:482:11)
at Function.forEach (C:\DATA\serverless-4kgaw\node_modules\serverless-cors-plugin\node_modules\lodash\lodash.js:7720:11)
at ServerlessCors.addPreflightRequests (C:\DATA\serverless-4kgaw\node_modules\serverless-cors-plugin\src\index.js:78:9)
From previous event:
at C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:157:29
at Array.reduce (native)
at C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:156:30
at processImmediate as _immediateCallback
From previous event:
at Serverless._execute (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:154:10)
at Serverless.actions.(anonymous function) (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:382:20)
at Serverless.command (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\lib\Serverless.js:351:38)
at Object. (C:\Users\myusername\AppData\Roaming\npm\node_modules\serverless\bin\serverless:16:12)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
I've got following code in s-module.json:
{
"name": "auth",
"profile": "aws-v0.3.1",
"custom": {
"cors": {
"allowOrigin": "*",
"allowHeaders": [
"Content-Type",
"X-Amz-Date",
"Authorization",
"X-Api-Key",
"x-amz-security-token",
"Access-Control-Allow-Origin"
]
}
},
"cloudFormation": {
"resources": {},
"lambdaIamPolicyDocumentStatements": []
}
}
Any ideas?
How do you just deploy the OPTIONS
method for one endpoint? I was hoping when I deployed my GET
method this plugin would detect that no OPTIONS
method was present for endpoint, and it would automatically create the OPTIONS
method.
I have added the following to s-project.json
"custom": {
"cors": {
"allowOrigin": "*",
"allowHeaders": [
"Content-Type",
"X-Amz-Date",
"Authorization",
"X-Api-Key"
],
"allowCredentials": true,
"maxAge": 3600
}
...
I have also tried adding to s-function.json
.
the OPTIONS
does not show up under serverless dash deploy
and it gives me an error when I try to run serverless endpoint deploy "discover/wx/{version}/latlng~OPTIONS"
saying method not found.
Lastly I added an OPTIONS
to my s-function.json
endpoints
. I was able to deploy the method, however looking at --debug
I don't see your plugin getting invoked and the integration request is not using a MOCK
any ideas whats going on here? serverless v0.5.1
. Thanks
I'm trying to send a custom header to my Serverless endpoint using AngularJS and JQuery, and whenever I do I get a 403 error during the OPTIONS preflight check.
My s-function.json
has:
"requestTemplates": "$${apiRequestTemplate}",
..
"custom": {
"cors": {
"allowOrigin": "*",
"allowHeaders": ["Content-Type", "X-Amz-Date", "X-Custom-Auth", "X-Api-Key"]
}
}
My s-templates.json
file has:
"apiRequestTemplate": {
"application/json": {
"auth": "$input.params('X-Custom-Auth')"
}
}
I've tested it with a simple JQuery request:
$.ajax({
url: "https://***.execute-api.us-east-1.amazonaws.com/dev/test",
type: 'GET',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Custom-Auth', 'MY_AUTH');
}
})
.done(function(data) {
console.log('JQUERY',data)
})
.fail(function(data) {
console.log('JQUERYFAIL',data)
});
})
If I comment out the beforeSend
block, the request completes successfully.
The current validation for header names (line ~100) is:
allowHeaders: Joi.array().min(1).items(Joi.string().regex(/^[a-zA-Z-]+$/))
We have a case where our header contains numbers. Amazon requires a special header when using signed (authenticated) requests: X-Amz-Content-Sha256
. http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html. The current validation regex fails on the #'s in the header name.
I think a more appropriate regex would be /^(\w|-)+$/
.
The OPTIONS endpoints that were created using the cors plugin are missing the status code in the integration request mapping template, which is resulting in this error:
Execution log for request test-request
Wed Jan 27 18:20:49 UTC 2016 : Starting execution for request: test-invoke-request
Wed Jan 27 18:20:49 UTC 2016 : API Key: test-invoke-api-key
Wed Jan 27 18:20:49 UTC 2016 : Method request path: {myParam=undefined}
Wed Jan 27 18:20:49 UTC 2016 : Method request query string: {}
Wed Jan 27 18:20:49 UTC 2016 : Method request headers: {}
Wed Jan 27 18:20:49 UTC 2016 : Method request body before transformations: null
Wed Jan 27 18:20:49 UTC 2016 : Execution failed due to configuration error: statusCode should be an integer which defined in request template
Wed Jan 27 18:20:49 UTC 2016 : Method completed with status: 500
To fix this, I had to manually modify the mapping template, change it from Input passthrough to mapping template, and add the following content to the template:
{"statusCode": 200}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.