如何使用Cognito事件/触发器在无服务器官能线中调用Lambda进行本地测试

发布于 2025-02-07 04:27:18 字数 2140 浏览 3 评论 0原文

我正在尝试为自定义auth Flow编写三个Cognito AuthChallenge lambdas。我想使用nodejs本地开发和测试Lambdas(也在CICD管道中的JEST测试中)。

例如,这是一个简化的处理程序代码,它具有verifyauthchallengersponsetriggerevent从aws-lambda软件包中键入键入:

import {
    VerifyAuthChallengeResponseTriggerEvent,
    VerifyAuthChallengeResponseTriggerHandler
} from "aws-lambda/trigger/cognito-user-pool-trigger/verify-auth-challenge-response";

export const verifyChallengeHandler: VerifyAuthChallengeResponseTriggerHandler =
    async (event: VerifyAuthChallengeResponseTriggerEvent):
        Promise<VerifyAuthChallengeResponseTriggerEvent> => {

        event.response.answerCorrect = event.request.privateChallengeParameters["code"] == event.request.challengeAnswer;

        return event;
    };

我到处发现,只发现与http event一起使用API​​ Gateway的示例,因此,当我本地尝试使用API​​ Gateway在本地尝试使用<<代码>函数在无服务器配置中,它也有效:

events: [
    {
        http: {
            method: "post",
            path: "auth-verify",
            cors: {
                origin: '*',
                headers:[
                    "Content-Type",
                    "X-Amz-Date",
                    "X-Amz-Security-Token",
                    "Authorization",
                    "X-Api-Key",
                    "X-Requested-With",
                    "Accept",
                ],
                allowCredentials: true,
            },
        },
    },
],

但是,我必须重写处理程序代码,以便与其他事件类型一起使用。这不是很好,因为它将是部署代码的测试代码不同。

import { ValidatedEventAPIGatewayProxyEvent } from '@libs/apiGateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';


const verifyChallengeHandler: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async(event) => {
   ... 

是否有一种配置无服务器的方法,可以称呼什么命令可以在本地调用lambdas,以及在带有正确事件的嘲笑测试中,而无需更改代码?我也可以创建一个自定义的事件模拟(但是如何指定它们?)。 IE。在function下使用config作为这样的东西:

events: [
    {
        cognitoUserPool: {
            pool: <some_pool_name>,
            trigger: 'VerifyAuthChallengeResponse' as const,
            existing: false,
        },
    },

I'm trying to write a trio of Cognito AuthChallenge lambdas for custom auth flow. I wanted to use serverless-offline to develop and test the lambdas locally with nodejs (also in jest tests in cicd pipeline).

For example, here is a simplified handler code with VerifyAuthChallengeResponseTriggerEvent type from aws-lambda package:

import {
    VerifyAuthChallengeResponseTriggerEvent,
    VerifyAuthChallengeResponseTriggerHandler
} from "aws-lambda/trigger/cognito-user-pool-trigger/verify-auth-challenge-response";

export const verifyChallengeHandler: VerifyAuthChallengeResponseTriggerHandler =
    async (event: VerifyAuthChallengeResponseTriggerEvent):
        Promise<VerifyAuthChallengeResponseTriggerEvent> => {

        event.response.answerCorrect = event.request.privateChallengeParameters["code"] == event.request.challengeAnswer;

        return event;
    };

I found everywhere only examples of using API Gateway with http event, so when I tried it locally with following config under the functions in serverless config, it also worked:

events: [
    {
        http: {
            method: "post",
            path: "auth-verify",
            cors: {
                origin: '*',
                headers:[
                    "Content-Type",
                    "X-Amz-Date",
                    "X-Amz-Security-Token",
                    "Authorization",
                    "X-Api-Key",
                    "X-Requested-With",
                    "Accept",
                ],
                allowCredentials: true,
            },
        },
    },
],

However, I'd have to rewrite the handler code, so that it works with different event type. That is not great as it would be different code for testing from the code to be deployed.

import { ValidatedEventAPIGatewayProxyEvent } from '@libs/apiGateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';


const verifyChallengeHandler: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async(event) => {
   ... 

Is there a way to configure serverless and what command to call that I can invoke the lambdas locally and also in jest tests with correct events and without changing the code? I'm also fine with creating a custom mock of events (but how to specify them?).
Ie. to use config under functions as something like this:

events: [
    {
        cognitoUserPool: {
            pool: <some_pool_name>,
            trigger: 'VerifyAuthChallengeResponse' as const,
            existing: false,
        },
    },

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寂寞笑我太脆弱 2025-02-14 04:27:18

好吧,似乎我找到了答案,这并不是那么困难,但是只是要完成这个问题,我会在这里发布。它基于此答案 aws lambda:aws lambda:with cli 我从以下方式开始启动本地lambda代码:

npm start

然后用模拟event.json文件数据作为CLI中的事件调用lambda:

aws lambda invoke /dev/null \
  --endpoint-url http://localhost:3002 \
  --function-name lambda-handler-dev-lambdaHandler \
  --invocation-type Event \
  --payload file:///home/...<path to my project>/src/functions/lambda-handler/mock-event.json

这很不错,因为一个终端等待更改并在任何代码更改后重新加载它们,并且还显示日志lambda的输出,而我仅使用另一个终端来调用lambda。我喜欢流动的清晰度和速度。

我也从无服务器中找到了其他方式(在我的无服务器项目模板的读数文件中,我很盲目看不到它,是吗?),然后在一个终端中执行了所有内容(一个日志和响应)有点旋转并调用lambda。另一方面,与AWS lambda CLI不同,它只给了我一些基本的响应,它也打印出了很好而完整的响应对象。它可以被调用为:

npx sls invoke local -f lambda-handler-dev-lambdaHandler --path src/functions/lambda-handler/mock-event.json

到目前为止,对于本地发展而言。关于测试,我正在在__测试中创建通常的嘲笑测试__文件夹,您可以在其中创建模拟对象并调用处理程序方法:

const event = {foo: bar};
const main = require("../src/functions/lambda-handler/handler").main;
const response = await main(...event-params...);

Well, seems like I found the answer, which wasn't finally that difficult, but just to complete this question, I'll post it here. It's based on this answer aws lambda: invoke with payload from cli where I start local lambda code with:

npm start

and then invoke lambda with mock-event.json file data as event in CLI like this:

aws lambda invoke /dev/null \
  --endpoint-url http://localhost:3002 \
  --function-name lambda-handler-dev-lambdaHandler \
  --invocation-type Event \
  --payload file:///home/...<path to my project>/src/functions/lambda-handler/mock-event.json

This was pretty nice, as one terminal waits for changes and reloads them after any code change and it also shows the log output of the lambda, while I use the other terminal just to invoke lambda. I like the clarity and speed of the flow.

I found also other way from Serverless (in the README file of my serverless project template, I was blind not to see it before, yeah?), and that executed everything in one terminal (logs and responses in one), but it took a bit of time to spin up and invoke the lambda. On the other side, unlike from the aws lambda cli which gave me only some basic response back, it also printed nice and complete response object. It can be invoked as:

npx sls invoke local -f lambda-handler-dev-lambdaHandler --path src/functions/lambda-handler/mock-event.json

That's so far for a local development. Regarding the testing, I'm creating the usual jest test in __tests__ folder where you create mock objects and call the handler method:

const event = {foo: bar};
const main = require("../src/functions/lambda-handler/handler").main;
const response = await main(...event-params...);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文