diff --git a/apigw-websocket-api-sns/README.md b/apigw-websocket-api-sns/README.md new file mode 100644 index 000000000..e84cf422b --- /dev/null +++ b/apigw-websocket-api-sns/README.md @@ -0,0 +1,75 @@ +# API WebSocket to SNS with request validation + +This pattern creates a WebSocket API to send notification via SNS topic with request validation. + +Learn more about this pattern at Serverless Land Patterns: + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) installed + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +1. Change directory to the pattern directory: + ``` + cd apigw-websocket-api-sns/ + ``` +1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file: + ``` + sam deploy --guided + ``` +1. During the prompts: + * Enter a stack name + * Enter the desired AWS Region + * Allow SAM CLI to create IAM roles with the required permissions. + + Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. + +1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. + +## How it works + +This sample project demonstrates how to use WebSocket API to integrate with Amazon Simple Notification service (SNS) to send notifications. This pattern also implements data validation in WebSocket API using model in API Gateway. This template does not implement Authentication in WebSocket API to keep it simple. However, it is recommended to implement Authentication on WebSocket API. +This pattern is utilizing native AWS Integration between WebSocket API Gateway and SNS. Request template is used in WebSocket integration to map the input to SNS payload. +This pattern is also a workaround to invoke AWS services in WebSocket API which requires Content-Type header to be application/x-www-form-urlencoded. By default, WebSocket APIs do not support overriding headers from AWS console and supports application/json in Content-Type header. + +## Testing + +1. The stack will output the **api endpoint**. Use wscat to test the API (see [documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-wscat.html) for more details on how to set it up): + +```bash +wscat -c < API ENdpoint from the stack > +``` +2. Send a payload to the API in the correct format of the Model, otherwise you will receive a 'Forbidden' exception. The model in the template expects the request in below format: +``` +{"action":"sendOrder","Name":"Jon","SirName":"Doe","Number":"123"} +``` +3. A successful invocation to Amazon SNS would return the message ID like below: +``` +{"PublishResponse":{"PublishResult":{"MessageId":"10e10111-a2bf-3a33-b44b-5b55dbde5555","SequenceNumber":null},"ResponseMetadata":{"RequestId":"bd11111e-2222-3c33-4444-055c5550c55e"}}} +``` + + +## Cleanup + +1. Delete the stack + ```bash + aws cloudformation delete-stack --stack-name STACK_NAME + ``` +1. Confirm the stack has been deleted + ```bash + aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus" + ``` +---- +Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 \ No newline at end of file diff --git a/apigw-websocket-api-sns/example-pattern.json b/apigw-websocket-api-sns/example-pattern.json new file mode 100644 index 000000000..b7df652a4 --- /dev/null +++ b/apigw-websocket-api-sns/example-pattern.json @@ -0,0 +1,58 @@ +{ + "title": "API WebSocket to SNS with request validation", + "description": "Create a WebSocket API to send notification via SNS topic with request validation", + "level": "300", + "framework": "SAM", + "introBox": { + "headline": "How it works", + "text": [ + "This sample project demonstrates how to use WebSocket API to integrate with Amazon Simple Notification service (SNS) to send notifications. This pattern also implements data validation in WebSocket API using model in API Gateway.", + "This pattern is utilizing native AWS Integration between WebSocket API Gateway and SNS. Request template is used in WebSocket integration to map the input to SNS payload.", + "This pattern is also a workaround to invoke AWS services in WebSocket API which requires Content-Type header to be application/x-www-form-urlencoded. By default, WebSocket APIs do not support overriding headers from AWS console by default", + "This pattern deploys one API Gateway and one SNS topic." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-websocket-api-sns", + "templateURL": "serverless-patterns/apigw-websocket-api-sns", + "projectFolder": "apigw-websocket-api-sns", + "templateFile": "apigw-websocket-api-sns/template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Request validation in WebSocket API", + "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-api-request-validation.html" + }, + { + "text": "Mapping template in WebSocket API", + "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/websocket-api-data-transformations.html" + } + ] + }, + "deploy": { + "text": [ + "sam deploy" + ] + }, + "testing": { + "text": [ + "See the Github repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "sam delete" + ] + }, + "authors": [ + { + "name": "Bharat Sahni", + "image": "https://drive.google.com/file/d/1ajooLmbTGN2KI2IcehV4neB2rHxGzZD2/view", + "bio": "Bharat Sahni is a Cloud Support Engineer 2 in Serverless team at AWS based in BLR, India.", + "linkedin": "https://www.linkedin.com/in/sahnibharat/" + } + ] +} diff --git a/apigw-websocket-api-sns/template.yaml b/apigw-websocket-api-sns/template.yaml new file mode 100644 index 000000000..efdc4daeb --- /dev/null +++ b/apigw-websocket-api-sns/template.yaml @@ -0,0 +1,238 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +AWSTemplateFormatVersion: 2010-09-09 +Transform: 'AWS::Serverless-2016-10-31' +Description: > + Serverless patterns - This template will help you to deploy API Gateway WebSocket API which validates input and invokes SNS topic + +Parameters: + ApiStageName: + Description: Name of WebSocket API stage + Type: String + Default: production + +Resources: +####################################################### +# SNS topic - we need to configure the subscription after deployment +####################################################### + SNSTopic: + Type: AWS::SNS::Topic + Properties: + DisplayName: !Sub "${AWS::StackName}-SNSTopic" + +####################################################### +# API Gateway +####################################################### + WebSocketApi: + Type: AWS::ApiGatewayV2::Api + Properties: + Name: !Sub "${AWS::StackName}-WebSocketApi" + ProtocolType: WEBSOCKET + RouteSelectionExpression: "$request.body.action" + + Deployment: + Type: AWS::ApiGatewayV2::Deployment + DependsOn: + - ConnectRoute + - sendOrder + + Properties: + ApiId: !Ref WebSocketApi + + Stage: + Type: AWS::ApiGatewayV2::Stage + Properties: + StageName: !Ref ApiStageName + DeploymentId: !Ref Deployment + ApiId: !Ref WebSocketApi + + +####################################################### +# Connect route +####################################################### + + ConnectRoute: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref WebSocketApi + RouteKey: $connect + AuthorizationType: NONE + RouteResponseSelectionExpression: '$default' + OperationName: ConnectRoute + Target: !Join + - / + - - integrations + - !Ref ConnectRouteIntegration + + ConnectRouteIntegration: + Type: AWS::ApiGatewayV2::Integration + Properties: + ApiId: !Ref WebSocketApi + IntegrationType: MOCK + RequestTemplates: + "200": '{"statusCode":200}' + TemplateSelectionExpression: '200' + PassthroughBehavior: 'WHEN_NO_MATCH' + + + ConnectRouteResponse: + Type: AWS::ApiGatewayV2::RouteResponse + Properties: + RouteId: !Ref ConnectRoute + ApiId: !Ref WebSocketApi + RouteResponseKey: $default + + ConnectRouteIntegrationResponse: + Type: AWS::ApiGatewayV2::IntegrationResponse + Properties: + ApiId: !Ref WebSocketApi + IntegrationId: !Ref ConnectRouteIntegration + IntegrationResponseKey: /200/ + TemplateSelectionExpression: \$default + ResponseTemplates: + "200": '{"statusCode":, "message":"order initiated"}' +####################################################### +# IAM role +####################################################### + APIGWRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Action: + - "sts:AssumeRole" + Effect: Allow + Principal: + Service: + - apigateway.amazonaws.com + Path: / + Policies: + - PolicyName: SNSSFAccess + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: + - "sns:Publish" + Resource: + - !Ref SNSTopic +####################################################### +# Disconnect route +####################################################### + DisconnectRoute: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref WebSocketApi + RouteKey: $disconnect + OperationName: DisconnectRoute + Target: !Join + - / + - - integrations + - !Ref DisconnectRouteIntegration + + DisconnectRouteIntegration: + Type: AWS::ApiGatewayV2::Integration + Properties: + ApiId: !Ref WebSocketApi + IntegrationType: MOCK + RequestTemplates: + "200": '{"statusCode":200}' + TemplateSelectionExpression: '200' + PassthroughBehavior: 'WHEN_NO_MATCH' + + DisconnectRouteIntegrationResponse: + Type: AWS::ApiGatewayV2::IntegrationResponse + Properties: + ApiId: !Ref WebSocketApi + IntegrationId: !Ref DisconnectRouteIntegration + IntegrationResponseKey: /200/ + TemplateSelectionExpression: \$default + +####################################################### +# sendOrder route +####################################################### + sendOrder: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref WebSocketApi + RouteKey: sendOrder + AuthorizationType: NONE + ModelSelectionExpression: $request.body.action + RequestModels: + sendOrder: orderModel + Target: !Join + - / + - - integrations + - !Ref sendOrderRouteIntegration + + sendOrderRouteIntegration: + Type: AWS::ApiGatewayV2::Integration + Properties: + ApiId: !Ref WebSocketApi + IntegrationType: AWS + IntegrationUri: !Sub "arn:aws:apigateway:${AWS::Region}:sns:action/Publish" + CredentialsArn: !Sub "${APIGWRole.Arn}" + IntegrationMethod: POST + ContentHandlingStrategy: CONVERT_TO_TEXT + RequestParameters: + integration.request.header.Content-Type: "'application/x-www-form-urlencoded'" + RequestTemplates: + '$default': + Fn::Sub: | + #set ( $name = $input.path('$.Name')) + #set ($lastname =$input.path('$.SirName')) + #set ($phone =$input.path('$.Number')) + #set( $dq = '"') + Action=Publish&TopicArn=$util.urlEncode("${SNSTopic}")&Message=$util.urlEncode("{ + ${!dq}connectionId${!dq}: ${!dq}${!context.connectionId}${!dq}, + ${!dq}requestTimeEpoch${!dq}: ${!context.requestTimeEpoch}, + ${!dq}Name${!dq}: ${!dq}$name${!dq}, + ${!dq}LastName${!dq}:${!dq}$lastname${!dq}, + ${!dq}Phone${!dq}: ${!dq}$phone${!dq} + }") + TemplateSelectionExpression: request.body.action + + sendOrderRouteResponse: + Type: AWS::ApiGatewayV2::RouteResponse + Properties: + RouteId: !Ref sendOrder + ApiId: !Ref WebSocketApi + RouteResponseKey: $default + + sendOrderRouteIntegrationResponse: + Type: AWS::ApiGatewayV2::IntegrationResponse + Properties: + ApiId: !Ref WebSocketApi + IntegrationId: !Ref sendOrderRouteIntegration + IntegrationResponseKey: $default + + foodOrderModel: + Type: AWS::ApiGatewayV2::Model + Properties: + ApiId: !Ref WebSocketApi + ContentType: application/json + Description: this model helps us to ensure that all the required parameters are passed on to the SNS topic + Name: orderModel + Schema: + $schema: http://json-schema.org/draft-04/schema# + title: orderInputModel + type: object + properties: + Name: + type: string + SirName: + type: string + Number: + type: string + required: + - Name + - SirName + - Number + +Outputs: + APIEndpoint: + Description: "API Gateway endpoint URL" + Value: !Sub "wss://${WebSocketApi}.execute-api.${AWS::Region}.amazonaws.com/${ApiStageName}" + diff --git a/apigw-websocket-api-sns/wf-sns.png b/apigw-websocket-api-sns/wf-sns.png new file mode 100644 index 000000000..473b0bc76 Binary files /dev/null and b/apigw-websocket-api-sns/wf-sns.png differ