Skip to content

fix(parser): LambdaFunctionUrl envelope assumes JSON string in body #3514

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 4 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 22 additions & 21 deletions packages/parser/src/envelopes/lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ZodSchema, z } from 'zod';
import { ParseError } from '../errors.js';
import { LambdaFunctionUrlSchema } from '../schemas/index.js';
import type { ParsedResult } from '../types/index.js';
import { Envelope, envelopeDiscriminator } from './envelope.js';
import { envelopeDiscriminator } from './envelope.js';

/**
* Lambda function URL envelope to extract data within body key
Expand All @@ -14,37 +14,38 @@ export const LambdaFunctionUrlEnvelope = {
*/
[envelopeDiscriminator]: 'object' as const,
parse<T extends ZodSchema>(data: unknown, schema: T): z.infer<T> {
const parsedEnvelope = LambdaFunctionUrlSchema.parse(data);

if (!parsedEnvelope.body) {
throw new Error('Body field of Lambda function URL event is undefined');
try {
return LambdaFunctionUrlSchema.extend({
body: schema,
}).parse(data).body;
} catch (error) {
throw new ParseError('Failed to parse Lambda function URL body', {
cause: error as Error,
});
}

return Envelope.parse(parsedEnvelope.body, schema);
},

safeParse<T extends ZodSchema>(data: unknown, schema: T): ParsedResult<unknown, z.infer<T>> {
const parsedEnvelope = LambdaFunctionUrlSchema.safeParse(data);

if (!parsedEnvelope.success) {
return {
success: false,
error: new ParseError('Failed to parse Lambda function URL envelope'),
originalEvent: data,
};
}
safeParse<T extends ZodSchema>(
data: unknown,
schema: T
): ParsedResult<unknown, z.infer<T>> {
const results = LambdaFunctionUrlSchema.extend({
body: schema,
}).safeParse(data);

const parsedBody = Envelope.safeParse(parsedEnvelope.data.body, schema);
if (!parsedBody.success) {
if (!results.success) {
return {
success: false,
error: new ParseError('Failed to parse Lambda function URL body', {
cause: parsedBody.error,
cause: results.error,
}),
originalEvent: data,
};
}

return parsedBody;
return {
success: true,
data: results.data.body,
};
},
};
49 changes: 49 additions & 0 deletions packages/parser/tests/events/lambda/base.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"version": "2.0",
"routeKey": "$default",
"rawPath": "/",
"rawQueryString": "parameter1=value1&parameter1=value2&parameter2=value",
"cookies": ["cookie1", "cookie2"],
"headers": {
"header1": "value1",
"header2": "value1,value2"
},
"queryStringParameters": {
"parameter1": "value1,value2",
"parameter2": "value"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "<urlid>",
"authentication": null,
"authorizer": {
"iam": {
"accessKey": "AKIA...",
"accountId": "111122223333",
"callerId": "AIDA...",
"cognitoIdentity": null,
"principalOrgId": null,
"userArn": "arn:aws:iam::111122223333:user/example-user",
"userId": "AIDA..."
}
},
"domainName": "<url-id>.lambda-url.us-west-2.on.aws",
"domainPrefix": "<url-id>",
"http": {
"method": "POST",
"path": "/",
"protocol": "HTTP/1.1",
"sourceIp": "123.123.123.123",
"userAgent": "agent"
},
"requestId": "id",
"routeKey": "$default",
"stage": "$default",
"time": "12/Mar/2020:19:03:58 +0000",
"timeEpoch": 1583348638390
},
"body": null,
"pathParameters": null,
"isBase64Encoded": false,
"stageVariables": null
}
48 changes: 48 additions & 0 deletions packages/parser/tests/events/lambda/invalid.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"version": "2.0",
"routeKey": "$default",
"rawQueryString": "parameter1=value1&parameter1=value2&parameter2=value",
"cookies": ["cookie1", "cookie2"],
"headers": {
"header1": "value1",
"header2": "value1,value2"
},
"queryStringParameters": {
"parameter1": "value1,value2",
"parameter2": "value"
},
"requestContext": {
"accountId": "123456789012",
"apiId": "<urlid>",
"authentication": null,
"authorizer": {
"iam": {
"accessKey": "AKIA...",
"accountId": "111122223333",
"callerId": "AIDA...",
"cognitoIdentity": null,
"principalOrgId": null,
"userArn": "arn:aws:iam::111122223333:user/example-user",
"userId": "AIDA..."
}
},
"domainName": "<url-id>.lambda-url.us-west-2.on.aws",
"domainPrefix": "<url-id>",
"http": {
"method": "POST",
"path": "/",
"protocol": "HTTP/1.1",
"sourceIp": "123.123.123.123",
"userAgent": "agent"
},
"requestId": "id",
"routeKey": "$default",
"stage": "$default",
"time": "12/Mar/2020:19:03:58 +0000",
"timeEpoch": 1583348638390
},
"body": null,
"pathParameters": null,
"isBase64Encoded": false,
"stageVariables": null
}
File renamed without changes.
167 changes: 101 additions & 66 deletions packages/parser/tests/unit/envelopes/lambda.test.ts
Original file line number Diff line number Diff line change
@@ -1,98 +1,133 @@
import { generateMock } from '@anatine/zod-mock';
import type {
APIGatewayProxyEventV2,
LambdaFunctionURLEvent,
} from 'aws-lambda';
import { describe, expect, it } from 'vitest';
import { ZodError } from 'zod';
import { ZodError, z } from 'zod';
import { ParseError } from '../../../src';
import { LambdaFunctionUrlEnvelope } from '../../../src/envelopes/index.js';
import { TestEvents, TestSchema } from '../schema/utils.js';
import { JSONStringified } from '../../../src/helpers';
import type { LambdaFunctionUrlEvent } from '../../../src/types';
import { getTestEvent, omit } from '../schema/utils.js';

describe('Lambda Functions Url ', () => {
describe('parse', () => {
it('should parse custom schema in envelope', () => {
const testEvent =
TestEvents.lambdaFunctionUrlEvent as APIGatewayProxyEventV2;
const data = generateMock(TestSchema);
const schema = z
.object({
message: z.string(),
})
.strict();

const baseEvent = getTestEvent<LambdaFunctionUrlEvent>({
eventsPath: 'lambda',
filename: 'base',
});

testEvent.body = JSON.stringify(data);
describe('parse', () => {
it('should throw if the payload does not match the schema', () => {
// Prepare
const event = structuredClone(baseEvent);

expect(LambdaFunctionUrlEnvelope.parse(testEvent, TestSchema)).toEqual(
data
// Act & Assess
expect(() => LambdaFunctionUrlEnvelope.parse(event, schema)).toThrow(
expect.objectContaining({
message: expect.stringContaining(
'Failed to parse Lambda function URL body'
),
cause: expect.objectContaining({
issues: [
{
code: 'invalid_type',
expected: 'object',
received: 'null',
path: ['body'],
message: 'Expected object, received null',
},
],
}),
})
);
});

it('should throw when no body provided', () => {
const testEvent =
TestEvents.lambdaFunctionUrlEvent as LambdaFunctionURLEvent;
testEvent.body = undefined;
it('parses a Lambda function URL event with plain text', () => {
// Prepare
const event = structuredClone(baseEvent);
event.body = 'hello world';

expect(() =>
LambdaFunctionUrlEnvelope.parse(testEvent, TestSchema)
).toThrow();
// Act
const result = LambdaFunctionUrlEnvelope.parse(event, z.string());

// Assess
expect(result).toEqual('hello world');
});

it('should throw when envelope is not valid', () => {
expect(() =>
LambdaFunctionUrlEnvelope.parse({ foo: 'bar' }, TestSchema)
).toThrow();
it('parses a Lambda function URL event with JSON-stringified body', () => {
// Prepare
const event = structuredClone(baseEvent);
event.body = JSON.stringify({ message: 'hello world' });

// Act
const result = LambdaFunctionUrlEnvelope.parse(
event,
JSONStringified(schema)
);

// Assess
expect(result).toEqual({ message: 'hello world' });
});

it('should throw when body does not match schema', () => {
const testEvent =
TestEvents.lambdaFunctionUrlEvent as APIGatewayProxyEventV2;
testEvent.body = JSON.stringify({ foo: 'bar' });
it('parses a Lambda function URL event with binary body', () => {
// Prepare
const event = structuredClone(baseEvent);
event.body = Buffer.from('hello world').toString('base64');
event.headers['content-type'] = 'application/octet-stream';
event.isBase64Encoded = true;

expect(() =>
LambdaFunctionUrlEnvelope.parse(testEvent, TestSchema)
).toThrow();
// Act
const result = LambdaFunctionUrlEnvelope.parse(event, z.string());

// Assess
expect(result).toEqual('aGVsbG8gd29ybGQ=');
});
});
describe('safeParse', () => {
it('should parse custom schema in envelope', () => {
const testEvent =
TestEvents.lambdaFunctionUrlEvent as APIGatewayProxyEventV2;
const data = generateMock(TestSchema);
it('should parse Lambda function URL event', () => {
const event = structuredClone(baseEvent);
event.body = JSON.stringify({ message: 'hello world' });

testEvent.body = JSON.stringify(data);
const result = LambdaFunctionUrlEnvelope.safeParse(
event,
JSONStringified(schema)
);

expect(
LambdaFunctionUrlEnvelope.safeParse(testEvent, TestSchema)
).toEqual({
expect(result).toEqual({
success: true,
data,
data: { message: 'hello world' },
});
});

it('should return original event when envelope is not valid', () => {
expect(
LambdaFunctionUrlEnvelope.safeParse({ foo: 'bar' }, TestSchema)
).toEqual({
success: false,
error: expect.any(ParseError),
originalEvent: { foo: 'bar' },
});
});
it('should return error with original event if Lambda function URL event is not valid', () => {
const event = omit(['rawPath'], structuredClone(baseEvent));

it('should return original event when body does not match schema', () => {
const testEvent =
TestEvents.lambdaFunctionUrlEvent as APIGatewayProxyEventV2;
testEvent.body = JSON.stringify({ foo: 'bar' });
const result = LambdaFunctionUrlEnvelope.safeParse(event, schema);

const parseResult = LambdaFunctionUrlEnvelope.safeParse(
testEvent,
TestSchema
);
expect(parseResult).toEqual({
expect(result).toEqual({
success: false,
error: expect.any(ParseError),
originalEvent: testEvent,
error: new ParseError('Failed to parse Lambda function URL body', {
cause: new ZodError([
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: ['rawPath'],
message: 'Required',
},
{
code: 'invalid_type',
expected: 'object',
received: 'null',
path: ['body'],
message: 'Expected object, received null',
},
]),
}),
originalEvent: event,
});

if (!parseResult.success && parseResult.error) {
expect(parseResult.error.cause).toBeInstanceOf(ZodError);
}
});
});
});
Loading
Loading