Skip to content

RFC: Validation #508

Open
Open
@misterjoshua

Description

Ref #445 for the structure of this RFC

Description of the proposal

There should be a consistent way to validate the structures of inputs and outputs for AWS lambdas.

Name of the core utility (and consequently the folders that contain the libraries):

  • packages/validation

Justification

The "Garbage in, garbage out" principle suggests that we should validate our inputs to prevent "garbage in," and for Lambda, those inputs include events passed to the lambda handler. A short, informal survey of GitHub projects using the CDK's NodejsFunction found that 90% of the studied projects hand-code their validation, indicating little consensus on any singular tool to validate inputs.

Additionally, the Java and Python toolkits saw fit to add validation of not only lambda input but lambda responses.

Validation support should be added to work toward feature parity between the AWS Lambda Powertools libraries and to offer developers a good alternative to hand-coding their validation.

Goals

  • Validate incoming events and responses
  • Unwrap events before validation applies
  • Built-in envelopes to unwrap popular event source payloads

Proposed API

Installation

Yarn

yarn add @aws-lambda-powertools/validation

Npm

npm install @aws-lambda-powertools/validation

Usage

Lambda Handler

import { Validation, Envelope } from "@aws-lambda-powertools/validation";

interface GreetingRequest {
  readonly name: string;
}

interface GreetingResponse {
  readonly message: string;
}

async function handlerBase(request: GreetingRequest, context: lambda.Context): Promise<GreetingResponse> {
  return {
    message: `Hello ${request.name}`,
  };
}

export const handler = Validation.handler(handlerBase, {
  envelope: Envelope.jmesPath("detail"),
  // Schemas are JSON Schema
  inboundSchema: {
    type: "object",
    required: ["name"],
    properties: {
      name: { type: "string" },
    },
  },
  outboundSchema: {
    type: "object",
    required: ["message"],
    properties: {
      message: { type: "string" },
    },
    additionalProperties: false,
  },
});

Ad-hoc validation

import { Logger } from "@aws-lambda-powertools/logger";
import { Validator } from "@aws-lambda-powertools/validation";

const logger = new Logger();

interface Person {
  readonly name: string;
}

const validator = new Validator<Person>({
  schema: {
    type: "object",
    required: ["name"],
    properties: {
      name: { type: "string" },
    },
  },
});

try {
  const person: Person = validator.map(JSON.parse(someInput));
  logger.info(`Person's name is ${person.name}`);
} catch (e) {
  logger.error(`Failure: ${e}`);
}

Survey Results

Obtained by searching GitHub code for NodejsFunction in TypeScript projects. The repositories are from the first twenty results, sorted by "best match." These cases are good enough evidence for me, but perhaps the community can suggest a better way to get this information.

Validation URL
JOI https://github.com/Mrdev1ce/rs-shop-be
Hand-coded https://github.com/jontiefer/space-finder-backend
@softchef/lambda-events https://github.com/taylorr-liu/EX7
Hand-coded https://github.com/ryands17/passwordless-auth
Hand-coded https://github.com/josh-hill-gene/cdk-serverless-react
Hand-coded https://github.com/zakiafada32/swj
Hand-coded https://github.com/martzcodes/blog-cdk-openapi
Hand-coded https://github.com/Shridharbhandar/CDK-Samples
Hand-coded https://github.com/roman-boiko/apigw-workshop
Hand-coded https://github.com/aws-samples/amazon-qldb-product-management
Hand-coded https://github.com/cjbatin/GetStatDashboard
Hand-coded https://github.com/jforge/iac-samples
Hand-coded https://github.com/okaharuna/e-payment
Hand-coded https://github.com/balancer-labs/pools-api
Hand-coded https://github.com/BertoDBQ/space-finder-backend
Hand-coded https://github.com/XiaozhouCui/space-finder-backend
Hand-coded https://github.com/akira393/2021-typescript-ddd
Hand-coded https://github.com/JonathanTurnock/aws-cabiinet
Hand-coded https://github.com/aws-samples/az-fail-away
Hand-coded https://github.com/enricoschaaf/analytics

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    RFCTechnical design documents related to a feature requestdiscussingThe issue needs to be discussed, elaborated, or refinedneed-customer-feedbackRequires more customers feedback before making or revisiting a decisionvalidationThis item relates to the Validation Utility

    Type

    No type

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions