Giter VIP home page Giter VIP logo

serverless-http-invoker's Introduction

Hi there 👋

My name is Scott Willeke ❤️ I love spending time with family and being outside. I also love to build things - especially out of code and especially with others.

More about me at https://scott.willeke.com/about

My GitHub Stats

Scott Willeke's GitHub Stats

github-snake

Scott Willeke's GitHub streak stats

Scott Willeke's Top Langs

serverless-http-invoker's People

Contributors

activescott avatar dependabot[bot] avatar dhessler avatar greenkeeper[bot] avatar ilkkaanttonen avatar wahler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

serverless-http-invoker's Issues

incorporate remaining serverless Plugin Approved/Certified Criteria

https://serverless.com/plugins/criteria/

Documentation Requirements

  • Description - A summary of the plugin and its intended purpose.
  • Table of Contents - A summary of each section of the Readme.
  • Usage Requirements - Provides details as to the minimum requirements in order to make use of the plugin and MAY include:
    • Required node and npm versions
    • Required runtime version
    • Minimum version of the Serverless Framework required
    • Any dependency on any other plugin
    • Warning describing any effects on standard deployment process or effect on existing services deployed
  • Installation Instructions - Provides instructions on how to install the plugin, and SHOULD include:
    • Basic instructions to install the Serverless Framework
    • Link to the Serverless Framework Getting Started Section
    • Instructions for installing the plugin
  • Quick Start Instructions - Details a minimum required configuration for a basic version of the plugin to work and SHOULD contain a simple, inline example demonstrating usage of the plugin.
  • Feature Details - A reference section that describes each feature and its available options in detail:
    • Each feature is described in its sub-section in detail
    • Each feature includes relevant config or code snippet
    • A complete yaml reference providing an example of all possible configuration options for the plugin.
  • Examples - Links to examples in the examples folder.
  • Licence - A description of the plugin’s license.

Misc

Example Requirements

  • Examples must be kept within an “examples” folder in the repo
  • Examples MUST have links to them from the root Readme
  • Each example MUST have its own Readme providing instructions as to how to use the example and describing what it is demonstrating
  • Multiple examples should be provided if there are multiple use cases that need to be covered
  • All examples should be easily replicated by an end user
  • All example code and configuration should be commented in a way that fully explains the plugin features being used

Testing Requirements

  • MUST have 80% unit test coverage
  • Coverage MUST include each feature it supports
  • An integration test MUST exist that runs each example in the examples directory.

CI

  • Continuous Integration/Continuous Delivery, meeting the following requirements, should be in place:
    • Master branch is a protected branch that cannot be pushed to directly
    • All changes must be submitted via pull request
    • Pull requests are only merged after at least ONE approving review
    • A CI/CD process must be configured to execute all unit tests after every merged pull request
    • Unit test coverage must not drop below 90%
    • Prior to every release, integration tests on examples should pass
    • CI/CD setup should push a new npm release triggered via Github tags to allow Serverless Inc to release new npm versions without needing access to npm

When lambda function throws an exception, invoker should catch it and return an appropriate HTTP response

When the lambda function being invoked throws an exception, invoker isn't catching it and just allows the exception to be thrown into the test itself. Instead, it should catch the exception and marshal the error across as an HTTP Error Response. API Gateway returns 502 (bad gateway) and sets the response body to {"message": "Internal server error"}.

Wouldn't hurt for test purposes to add more error detail to the http response for test debugging

Response only contains the body of the lambda callback

Based on the examples I expected a successful invocation response to contain fields "statusCode" and "body", but it looks like it only contains the contents of the body. On line 92 only the response from invokeWithLambdaWrapper (which uses lambda-wrapper) is returned and it looks like to be only the contents of the lambda-callback. In case of errors the response is built to contain statusCode and body.

Should the line 92 wrap the response like "return { statusCode: 200, body: response }" or would a more complex solution with status code sniffing (that the api-gateway would do if the message contains http statuscode in the beginning in brackets) be done?

mergeResourceArrays probably should be mergeArrays

It looks like serverless has changed some of the method names causing invoker to crash on line 43 when it initializes. It tries to call a function "sls.service.mergeResourceArrays()" but it looks like there's only a method "sls.service.mergeArrays()" in the serverless implementation. Would this be the correct method to call at that stage?

Problem with execution simplest function

Hi, I've got a problem with testing of simplest function

module.exports.main = (event, context, callback) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            generated: true,
            pdf: 'PDF'
        }),
    };
    callback(null, response)
};

serverless.yml

service: test

provider:
  name: aws
  stage: dev
  runtime: nodejs8.10
  profile: ${self:custom.myProfile.${self:custom.myStage}}
  region: ${self:custom.myRegion.${self:custom.myStage}}

custom:
  myStage: ${opt:stage, self:provider.stage}
  myProfile:
    dev: default
    prod: default
  myRegion:
    dev: eu-central-1
    prod: eu-central-1

functions:
  test:
    handler: src/test.main
    name: test
    memorySize: 128
    events:
      - http:
          path: test
          method: get
          cors: true

When I manually trigger this function sls invoke local -f test I got following result:

Serverless: INVOKING INVOKE
{
    "statusCode": 200,
    "body": "{\"generated\":true,\"pdf\":\"PDF\"}"
}

However when executing from test

const ServerlessInvoker = require('serverless-http-invoker')
const expect = require('chai').expect

describe('PDF Generator tests', () => {
    let sls = new ServerlessInvoker()
    it('should work', function () {
        let response = sls.invoke('GET test')
        response.then( r => {
            console.log(r)
            // return expect(r).to.eventually.have.deep.property('body', {message: 'postit:boo'})
        })
    });
});

I get


  console.log src/__test__/handler.test.js:25
    { statusCode: 502,
      body:
       { message: 'Internal server error',
         test_debug_error_message: 'Error: Invalid input. Expected either lambda module (with exposed handler) or AWS Lambda configuration (with provided \'lambdaFunction\' name)',
         test_debug_error_stack: 'Error: Invalid input. Expected either lambda module (with exposed handler) or AWS Lambda configuration (with provided \'lambdaFunction\' name)\n    at new Wrapped (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/lambda-wrapper/index.js:17:15)\n    at wrap (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/lambda-wrapper/index.js:105:32)\n    at Promise.try (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/serverless-http-invoker/index.js:149:20)\n    at tryCatcher (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/util.js:16:23)\n    at Function.Promise.attempt.Promise.try (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/method.js:39:29)\n    at ServerlessInvoker.invokeWithLambdaWrapper (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/serverless-http-invoker/index.js:147:23)\n    at loadServerlessEnvironment.then (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/serverless-http-invoker/index.js:80:23)\n    at tryCatcher (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/util.js:16:23)\n    at Promise._settlePromiseFromHandler (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/promise.js:512:31)\n    at Promise._settlePromise (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/promise.js:569:18)\n    at Promise._settlePromiseCtx (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/promise.js:606:10)\n    at Async.Object.<anonymous>.Async._drainQueue (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/async.js:138:12)\n    at Async.Object.<anonymous>.Async._drainQueues (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/async.js:143:10)\n    at Immediate.Async.drainQueues (/home/pawel/serverless/Hireflow/assessmentReport/node_modules/bluebird/js/release/async.js:17:14)\n    at runCallback (timers.js:810:20)\n    at tryOnImmediate (timers.js:768:5)\n    at processImmediate [as _immediateCallback] (timers.js:745:5)' } }

Any idea what is going on?

maybe this "Serverless: INVOKING INVOKE" from sls is a problem?

new Serverless() not getting assigned correctly to this.serverless, Promise not resolving properly

Expected behavior:

Code of function initializeServerless working properly and setting this.serverless to the generated sls

  async initializeServerless() {
    process.env.SLS_DEBUG = "*"

    const slsService = await ServerlessInvoker.loadServerlessYaml(
      path.join(this.servicePath, "serverless.yml")
    )
    const config = {
      serviceDir: path.dirname(this.servicePath),
      configurationFilename: "serverless.yml",
      configuration: slsService,
      commands: [],
      options: {},
    }
    const sls = new Serverless(config) // creates the new Serverless
    
    return sls.init().then(() => {
      sls.service.load().then(() => {
        sls.service.setFunctionNames({})
        sls.service.mergeArrays()
        sls.service.validate()
        **this.serverless = sls** // should set this.serverless to the created Serverless
      })
    })
  }

Actual behavior:

The initializeServerless function does not seem to set this.serverless = sls in time so that this.loadServerlessEvents throws an error as this.serverless is still null.
(TypeError: Cannot read properties of null (reading 'service') at ServerlessInvoker.loadServerlessEvents)

  async invoke(httpRequest, event, context) {
    // Read the serverless.yml file
    return this.initializeServerless()
      .then(() => **this.loadServerlessEvents()**) // error thrown by this function
      .then((httpEvents) => {
        // find the event that matches the specified httpRequest
        let httpEvent = httpEvents.find((e) => e.test(httpRequest))
        if (!httpEvent) {
          throw new Error(
            `Serverless http event not found for HTTP request "${httpRequest}" in service path "${this.servicePath}".`
          )
        }
async loadServerlessEvents() {
    let funcs = **this.serverless.service** // is null
      .getAllFunctions()
      .map((fname) => {
        let funcObj = this.serverless.service.getFunction(fname)
        let events = this.serverless.service.getAllEventsInFunction(fname)
        let f = {
          name: fname,
          handler: funcObj.handler,
          events: events.filter(
            (e) => Object.keys(e).includes("http") && e.http !== null
          ),
        }

Setting this.serverless = sls earlier or solved the problem for me:

    const sls = new Serverless(config)
   
    return sls.init().then(() => {
      **this.serverless = sls** // e.g. here
      sls.service.load().then(() => {
        sls.service.setFunctionNames({})
        sls.service.mergeArrays()
        sls.service.validate()
      })

Steps to reproduce the problem:

Create test class with a serverlessInvoker instance

private readonly serverlessInvoker = new ServerlessInvoker();

and exectue the invoke function

const response = await this.serverlessInvoker.invoke(
      'POST xyz',
      {}
    );

a serverless.yml

service: service

frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs18.x
  region: eu-central-1

resources:
  # externalize Resources to separated file to get support by IDE for cloudformation
  - ${file(serverless-resources.yml)}

serverless-resources.yml

Resources:
  OnlyApiRequestValidation:
    Type: "AWS::ApiGateway::RequestValidator"

Environment:

serverless-http-invoker 3.0.6
serverless 3.31.0
node 18
macOS 13.1.1

[Security] Workflow build.yml is using vulnerable action actions/checkout

The workflow build.yml is referencing action actions/checkout using references v1. However this reference is missing the commit a6747255bd19d7a757dbdda8c654a9f84db19839 which may contain fix to the some vulnerability.
The vulnerability fix that is missing by actions version could be related to:
(1) CVE fix
(2) upgrade of vulnerable dependency
(3) fix to secret leak and others.
Please consider to update the reference to the action.

Support for node v6

Hello, I am testing my serverless app in a docker container emulating the aws runtime, thus running node 6.10.

I am getting the following error:

TypeError: URL is not a constructor
 at Function.parseQueryStringParameters (node_modules/serverless-http-invoker/index.js:125:19)
 at initializeServerless.then.then.httpEvents (node_modules/serverless-http-invoker/index.js:72:52)

This is happening because serverless-http-invoker is using node v8 syntax here:

const { URL } = require('url')

Would it be possible to change this or the packaging system to support node v6?
Thanks!

An in-range update of serverless is breaking the build 🚨

The devDependency serverless was updated from 1.61.3 to 1.62.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

serverless is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for 1.62.0 (2020-01-29)

Features

  • Support redrivePolicy configuration on SNS events (#7239) (4f27378)
  • Ensure deterministic WebSockets deployment id (so deployments are skipped when no changes are detected) (#7248) (9f0131f)
  • azure-nodejs-typescript template (#7252) (0549d85)

Bug Fixes

  • Variables: When resolving SSM parameter, ensure to retrieve status code from AWS error correctly (bc5bbbe), closes #7237
  • Do not overwrite go.mod on make in Go template (#7245) (1793cf8)

Comparison since last release

Commits

The new version differs by 9 commits.

  • ff93121 chore: Release v1.62.0
  • fcd74db chore: Bump dependencies
  • 9f0131f fix: Ensure deterministic WebSockets deployment id (#7248)
  • 304f0ec refactor(Variables): Clear ineffective promise functions usage
  • bc5bbbe fix(Variables): Ensure to retrieve status code correctly
  • 31987ce refactor(Variables): Reflect if/else logic in async handling
  • 0549d85 feat: azure-nodejs-typescript template. (#7252)
  • 4f27378 feat: Support RedrivePolicy configuration on SNS events (#7239)
  • 1793cf8 fix: Do not overwrite go.mod on make in Go template (#7245)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

self:service not populated

Have a variable in serverless.yml like ${self:service}-${opt:stage, self:provider.stage}-pluginApiAuth not getting the self:service variable populated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.