Skip to content
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

Example web app using local modules #457

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions LocalModules/ExampleWebApp/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
site/node_modules
DS_Store
local/

7 changes: 7 additions & 0 deletions LocalModules/ExampleWebApp/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# AWS CloudFormation Web App Sample with Local Modules

This sample demonstrates how to break down a CloudFormation template into
modules that can be re-used and shared.



1 change: 1 addition & 0 deletions LocalModules/ExampleWebApp/api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bootstrap
22 changes: 22 additions & 0 deletions LocalModules/ExampleWebApp/api/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package api

import "github.com/aws/aws-lambda-go/events"

// Fail returns a failure response
func Fail(code int, msg string) events.APIGatewayProxyResponse {
response := events.APIGatewayProxyResponse{
StatusCode: code,
Body: "{\"message\": \"" + msg + "\"}",
}
response.Headers = make(map[string]string)
AddCORSHeaders(response)
response.Headers["X-Rain-Webapp-Error"] = msg
return response
}

// AddCORSHeaders adds the necessary headers to a response to enable cross site requests
func AddCORSHeaders(response events.APIGatewayProxyResponse) {
response.Headers["Access-Control-Allow-Headers"] = "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent,X-KG-Partition"
response.Headers["Access-Control-Allow-Origin"] = "*"
response.Headers["Access-Control-Allow-Methods"] = "OPTIONS, GET, PUT, POST, DELETE, PATCH, HEAD"
}
1 change: 1 addition & 0 deletions LocalModules/ExampleWebApp/api/dist/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lambda-handler.zip
2 changes: 2 additions & 0 deletions LocalModules/ExampleWebApp/api/dist/.gitkeep
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@


209 changes: 209 additions & 0 deletions LocalModules/ExampleWebApp/api/resources/jwt/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
package main

import (
"context"
"fmt"
"log"

"encoding/json"
"errors"
"net/http"
"net/url"
"os"
"strings"

"example/api"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
)

func HandleRequest(ctx context.Context,
request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

fmt.Printf("request: %+v\n", request)
message := fmt.Sprintf("{\"message\": \"Request Resource: %s, Path: %s, HTTPMethod: %s\"}", request.Resource, request.Path, request.HTTPMethod)
fmt.Printf("message: %s\n", message)

headers := make(map[string]string)
code := request.QueryStringParameters["code"]
refresh := request.QueryStringParameters["refresh"]

response := events.APIGatewayProxyResponse{
StatusCode: 200,
Headers: headers,
Body: "{\"message\": \"Success\"}",
}

api.AddCORSHeaders(response)

switch request.HTTPMethod {
case "GET":
jsonData, err := handleAuth(code, refresh)
if err != nil {
fmt.Printf("handleAuth: %v", err)
return api.Fail(401, "Auth Failure"), nil
}
response.Body = jsonData
return response, nil
case "OPTIONS":
response.StatusCode = 204
response.Body = "{}"
return response, nil
default:
return api.Fail(400, fmt.Sprintf("Unexpected HttpMethod: %s", request.HTTPMethod)), nil
}

}

func main() {
lambda.Start(HandleRequest)
}

// getCognitoIssuer returns the Cognito issuer URL.
func getCognitoIssuer() (string, error) {
region := os.Getenv("COGNITO_REGION")
if region == "" {
return "", errors.New("missing COGNITO_REGION")
}

cognitoPoolID := os.Getenv("COGNITO_POOL_ID")
if cognitoPoolID == "" {
return "", errors.New("missing COGNITO_POOL_ID")
}

return fmt.Sprintf("https://cognito-idp.%s.amazonaws.com/%s", region, cognitoPoolID), nil
}

// getPublicKeys retrieves the public keys from the Cognito issuer.
func getPublicKeys() (jwk.Set, error) {

cognitoIssuer, err := getCognitoIssuer()
if err != nil {
return nil, err
}

url := cognitoIssuer + "/.well-known/jwks.json"
fmt.Printf("JWK URL: %s\n", url)

set, err := jwk.Fetch(context.Background(), url)
if err != nil {
fmt.Printf("failed to fetch JWK: %s\n", err)
return nil, err
}

{
jsonbuf, err := json.Marshal(set)
if err != nil {
log.Printf("failed to marshal key set into JSON: %s\n", err)
return nil, err
}
fmt.Printf("json jwk: %s\n", jsonbuf)
}

return set, nil
}

func handleAuth(code string, refresh string) (string, error) {

redirectURI := os.Getenv("COGNITO_REDIRECT_URI")
cognitoDomainPrefix := os.Getenv("COGNITO_DOMAIN_PREFIX")
cognitoDomainPrefix = strings.ReplaceAll(cognitoDomainPrefix, ".", "-")
cognitoClientID := os.Getenv("COGNITO_APP_CLIENT_ID")
cognitoRegion := os.Getenv("COGNITO_REGION")

tokenEndpoint := fmt.Sprintf("https://%s.auth.%s.amazoncognito.com/oauth2/token",
cognitoDomainPrefix, cognitoRegion)

var postData url.Values

if code != "" {
postData = url.Values{
"grant_type": {"authorization_code"},
"client_id": {cognitoClientID},
"code": {code},
"redirect_uri": {redirectURI},
}
} else {
if refresh == "" {
return "", errors.New("no refresh token")
}

postData = url.Values{
"grant_type": {"refresh_token"},
"client_id": {cognitoClientID},
"refresh_token": {refresh},
}
}

fmt.Printf("About to post to %s: %+v\n", tokenEndpoint, postData)

resp, err := http.PostForm(tokenEndpoint, postData)
if err != nil {
fmt.Printf("PostForm error from %s: %v\n", tokenEndpoint, err)
return "", errors.New("token endpoint failed")
}
defer resp.Body.Close()

fmt.Printf("resp: %+v\n", resp)

if resp.StatusCode >= 400 {
return "", fmt.Errorf("request to %s failed with Status %d",
tokenEndpoint, resp.StatusCode)
}

var token struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"`
}
err = json.NewDecoder(resp.Body).Decode(&token)
if err != nil {
fmt.Printf("json token response error: %v\n", err)
return "", errors.New("failed to decode token response")
}

fmt.Printf("Got token: %+v\n", token)

keys, err := getPublicKeys()
if err != nil {
return "", err
}
fmt.Printf("keys: %+v\n", keys)

parsed, err := jwt.Parse([]byte(token.AccessToken), jwt.WithKeySet(keys))
if err != nil {
fmt.Printf("failed to verify: %s\n", err)
return "", errors.New("failed to verify token")
}

fmt.Printf("parsed: %+v", parsed)

userName, ok := parsed.Get("username")
if !ok {
return "", errors.New("missing username")
}

retval := struct {
IDToken string `json:"idToken"`
RefreshToken string `json:"refreshToken"`
Username string `json:"username"`
ExpiresIn int64 `json:"expiresIn"`
}{
IDToken: token.IDToken,
RefreshToken: token.RefreshToken,
Username: strings.TrimPrefix(userName.(string), "AmazonFederate_"),
ExpiresIn: token.ExpiresIn,
}

jsonData, err := json.Marshal(retval)
if err != nil {
return "", errors.New("failed to encode response")
}

return string(jsonData), nil

}
71 changes: 71 additions & 0 deletions LocalModules/ExampleWebApp/api/resources/test/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package main

import (
"context"
"encoding/json"
"fmt"
"log"
"os"

"example/api"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

func HandleRequest(ctx context.Context,
request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

fmt.Printf("request: %+v\n", request)
message := fmt.Sprintf("{\"message\": \"Request Resource: %s, Path: %s, HTTPMethod: %s\"}", request.Resource, request.Path, request.HTTPMethod)
fmt.Printf("message: %s\n", message)

cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
log.Fatal(err)
}

client := dynamodb.NewFromConfig(cfg)

response := events.APIGatewayProxyResponse{
StatusCode: 200,
Body: "{\"message\": \"Success\"}",
Headers: make(map[string]string),
}

api.AddCORSHeaders(response)

switch request.HTTPMethod {
case "GET":
input := &dynamodb.ScanInput{
TableName: aws.String(os.Getenv("TABLE_NAME")),
}
res, err := client.Scan(context.Background(), input)
if err != nil {
fmt.Printf("Scan failed: %v\n", err)
return api.Fail(500, fmt.Sprintf("%v", err)), nil
}
fmt.Printf("Scan result: %+v", res)
jsonData, err := json.Marshal(res.Items)
if err != nil {
fmt.Printf("Marshal failed: %v\n", err)
return api.Fail(500, fmt.Sprintf("%v", err)), nil
}
response.Body = string(jsonData)
case "OPTIONS":
response.StatusCode = 204
response.Body = "{}"
return response, nil
default:
return api.Fail(400, fmt.Sprintf("Unexpected HttpMethod: %s", request.HTTPMethod)), nil
}

return response, nil
}

func main() {
lambda.Start(HandleRequest)
}
24 changes: 24 additions & 0 deletions LocalModules/ExampleWebApp/buildapi.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env bash

set -eou pipefail

SCRIPT_DIR=$(dirname "$0")
echo "SCRIPT_DIR: ${SCRIPT_DIR}"
cd $SCRIPT_DIR

function build() {
echo "Building $1..."
cd ../$1
staticcheck .
go vet .
GOOS=linux GOARCH=amd64 go build -o bootstrap main.go
mkdir -p ../../dist/$1
zip ../../dist/$1/lambda-handler.zip bootstrap
}

cd api/resources/test

build test
build jwt


34 changes: 34 additions & 0 deletions LocalModules/ExampleWebApp/buildsite.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/local/bin/bash
set -eou pipefail

SCRIPT_DIR=$(dirname "$0")
echo "SCRIPT_DIR: ${SCRIPT_DIR}"

cd ${SCRIPT_DIR}/site

if [ "$#" -eq 4 ]
then
echo "Editing config file..."

APIGW=$1
REDIRECT=$2
DOMAIN=$3
APPCLIENT=$4

ESCAPED_APIGW=$(printf '%s\n' "${APIGW}" | sed -e 's/[\/&]/\\&/g')
ESCAPED_REDIRECT=$(printf '%s\n' "${REDIRECT}" | sed -e 's/[\/&]/\\&/g')

cat js/config-template.js | sed s/__APIGW__/"${ESCAPED_APIGW}"/ | sed s/__REDIRECT__/"${ESCAPED_REDIRECT}"/ | sed s/__DOMAIN__/"${DOMAIN}"/ | sed s/__APPCLIENT__/"$APPCLIENT"/ > js/config.js

echo "Config file:"
cat js/config.js
else
echo "Number of args was $#"
fi

echo "Linting..."
npm run lint

echo "Building site..."
npm run build

Loading