logoStacktape docs


CDN Lambda FunctionsWork in progress
Work in progress

Overview and basic concepts

  • Cdn Lambda function is a scalable and highly available computing resource that runs your code closer to users of your application, improving performance and latency.

  • Functions are globally distributed across regional CDN cache locations (13 locations spread across the globe), which makes it possible to execute them closer to the end user

  • Lambda functions are "serverless" and fully managed. You don't have to worry about provisioning and managing servers, container and OS security, patching, scaling & many other DevOps tasks.

  • Supported runtimes are Node.js (Javascript and Typescript) and Python.

  • Use-cases for CDN lambda functions: performing user authentication, cookie inspection, validation of requests, and many more.

Advantages

  • Low latency - By running code closer to end user, latency and overall performance is improved.
  • Scalability - Run your code without neccessity to manage any infrastructure. Similarly to regular functions, CDN lambda functions provide high scalability.
  • Pay-per-use - You only pay for the compute time you consume (rounded to 1ms). Refer to Lambda@Edge pricing in AWS docs.

Disadvantages

  • Limited execution environment - (Applies to onRequest/onResponse lambdas) Your CDN lambda functions are limited to 128MB of memory and maximum execution time of 5 seconds.

Basic usage

  • You can associate cdn-lambda-function with CDN to be executed:

    • onRequest - function is executed when CDN receives a request from a client(viewer) before checking CDN cache
    • onResponse - function is executed before returning the response to the client(viewer)
  • Potential use-cases for using cdn functions:

    • generating immediate HTTP response without the need to check CDN cache or forward to origin
    • modifying request (i.e rewrite url, headers etc) before forwarding to the origin
    • inspection of cookies
    • inspection/validation of authorization headers and tokens

In the following example we are using cdn-lambda-function to validate Authorization header of each incoming user request. If user is not authorized, he is redirected to login page.

Copy

resources:
authFunction:
type: cdn-lambda-function
properties:
packaging:
type: stacktape-lambda-buildpack
properties:
entryfilePath: auth-function.ts
myBucket:
type: bucket
properties:
cdn:
enabled: true
cdnFunctions:
onRequest: authFunction

Copy

const validateAuthorizationToken = (token) => {
// perform some validation
return true;
};
export default async (event) => {
const { request } = event.Records[0].cf;
const { headers } = request;
const authorizationToken = headers.authorization?.[0]?.value;
const userAuthorized = validateAuthorizationToken(authorizationToken);
// if user is not authorized, redirect him to login page
if (!userAuthorized) {
return {
status: '302',
headers: {
location: [
{
key: 'Location',
value: '/login'
}
],
'cache-control': [
{
key: 'Cache-Control',
value: 'no-cache, no-store, max-age=0, must-revalidate'
}
]
}
};
}
// after we validated that user is authorized, we can return the request
// request will be forwarded to origin
return request;
};

Code of authorizer function authFunction

CdnLambdaFunction  API reference
type
Required

No description

Type: string "cdn-lambda-function"

properties.packaging
Required

Configures how your source code is turned into a deployment package (deployment artifact)

Type: (StpBuildpackLambdaPackaging or CustomArtifactLambdaPackaging)

  • Currently supported packaging types are:
    • stacktape-lambda-buildpack - Stacktape automatically builds your source code from the supplied source file path.
    • custom-artifact - You provide path to your own lambda artifact. Stacktape will zip it for you if it's not zipped.
  • Your deployment artifacts are automatically uploaded to the S3 deployment bucket.
properties.runtime

Runtime used to execute the function

Type: string ENUM

Possible values: nodejs12.xnodejs14.xpython3.7python3.8python3.9

  • Stacktape automatically detects the function's language uses the latest runtime version associated with that language
  • Example: uses nodejs14.x for all files ending with .js and .ts
  • You might want to use an older version if some of your dependencies are not not compatible with the default runtime version
properties.memory
Default: 128

Amount of memory (in MB) available to the function during execution

Type: number

  • Maximum allowed is 128 MB
properties.timeout
Default: 3

Maximum amount of time (in seconds) the lambda function is allowed to run

Type: number

Maximum allowed time is 5 seconds.

properties.accessControl

Configures access to other resources of your stack (such as dynamo-db-tables, buckets, etc.).

Type: AccessControl

  • Currently using accessControl with cdn-lambda-function is limited to following resources:
    • dynamo-db-tables
    • buckets
    • event-buses
properties.logging

Configures logging behavior for this cdn-lambda-function

Type: LambdaFunctionLogging

  • Information about the function invocation and function logs (stdout and stderr) are automatically sent to a pre-created CloudWatch log group.
  • By default, logs are retained for 180 days..
  • You can see the logs in the log group page in the AWS CloudWatch console. You can use stacktape stack-info command to get a direct link.

Cdn lambda functions are executed in multiple locations (regions) across the world depending on the cdn edge location which serves the client request (usually the location closest to the client).

As a result the logs for the function executed in given region are delivered to a log group in that region. The list of regions where edge lambda can execute: us-east-1, us-east-2, us-west-1, us-west-2, ap-south-1, ap-northeast-1, ap-northeast-2, ap-southeast-1, ap-southeast-2, eu-west-1, eu-west-2, eu-central-1, sa-east-1

overrides

Overrides one or more properties of the specified child resource.

Type: Object

  • Child resources are specified using their cloudformation logical id (e.g. MyBucketBucket).
  • To see all configurable child resources for given Stacktape resource, use stacktape stack-info --detailed command.
  • To see the list of properties that can be overridden, refer to AWS Cloudformation docs.

Event structure

Event delivered to the function differs based on whether you are using onRequest or onResponse trigger:

On request trigger

When using onRequest trigger with cdn-lambda-function you can:

  1. Return response from function - In this case the response is served to the client directly and the request is NOT forwarded to the origin.
  2. Forward request to origin - You can modify the request (path, body, headers ...) before forwarding to origin or you can forward it as is.

Following example code combines both options:

  • If user is authorized - forwards request to the origin
  • If user is not authorized - return redirect response to login page

Copy

const validateAuthorizationToken = (token) => {
// perform some validation
return true;
};
export default async (event) => {
const { request } = event.Records[0].cf;
const { headers } = request;
const authorizationToken = headers.authorization?.[0]?.value;
const userAuthorized = validateAuthorizationToken(authorizationToken);
// if user is not authorized, redirect him to login page
if (!userAuthorized) {
return {
status: '302',
headers: {
location: [
{
key: 'Location',
value: '/login'
}
],
'cache-control': [
{
key: 'Cache-Control',
value: 'no-cache, no-store, max-age=0, must-revalidate'
}
]
}
};
}
// after we validated that user is authorized, we can return the request
// request will be forwarded to origin
return request;
};

Code of authorizer function

Copy

resources:
authFunction:
type: cdn-lambda-function
properties:
packaging:
type: stacktape-lambda-buildpack
properties:
entryfilePath: auth-function.ts
myBucket:
type: bucket
properties:
cdn:
enabled: true
cdnFunctions:
onRequest: authFunction

Example config

On response trigger

When using onResponse trigger with cdn-lambda-function you can modify the response before returning.

In following example we are using it to set response cookie.

Copy

export default async (event) => {
const { response } = event.Records[0].cf;
response.headers['set-cookie'] = [
{
key: 'Set-Cookie',
value: 'my-experimental-cookie=cookie-value'
}
];
return response;
};

Code of the function

Copy

resources:
cookieFunction:
type: cdn-lambda-function
properties:
packaging:
type: stacktape-lambda-buildpack
properties:
entryfilePath: set-cookie.ts
myBucket:
type: bucket
properties:
cdn:
enabled: true
cdnFunctions:
onResponse: cookieFunction

Example config

Packaging

Refer to packaging docs.

When using cdn-lambda function with onReqeust or onResponse trigger the zipped package size is limited to 1 MB.

Logging

  • Information about the function invocation and function logs (stdout and stderr) are automatically sent to a pre-created CloudWatch log group.
  • By default, logs are retained for 180 days..
  • You can see the logs in the log group page in the AWS CloudWatch console. You can use stacktape stack-info command to get a direct link.

Cdn lambda functions are executed in multiple locations (regions) across the world depending on the cdn edge location which serves the client request (usually the location closest to the client).

As a result the logs for the function executed in given region are delivered to a log group in that region. The list of regions where edge lambda can execute: us-east-1, us-east-2, us-west-1, us-west-2, ap-south-1, ap-northeast-1, ap-northeast-2, ap-southeast-1, ap-southeast-2, eu-west-1, eu-west-2, eu-central-1, sa-east-1

LambdaFunctionLogging  API reference
Parent API reference: CdnLambdaFunction
disabled

Disables the collection of function's application logs (stdout and stderr) to CloudWatch

Type: boolean

retentionDays
Default: 180

Amount of days the logs will be retained in the log group

Type: number ENUM

Possible values: 13571430609012015018036540054573118273653

Accessing other resources

  • For most of the AWS resources, resource-to-resource communication is not allowed by default. This helps to enforce security and resource isolation. Access must be explicitly granted using IAM (Identity and Access Management) permissions.

  • Stacktape automatically handles IAM permissions for the underlying AWS services that it creates (i.e. granting cdn lambda function permission to write logs to Cloudwatch).

  • If your function needs to communicate with other infrastructure components, you need to add permissions manually. You can do this in 2 ways listed below.

AccessControl  API reference
Parent API reference: CdnLambdaFunction
iamRoleStatements

Raw AWS IAM role statements appended to your resources's role.

Type: Array of StpIamRoleStatement

allowAccessTo

Names of the resources that will receive basic permissions.

Type: Array of string

Granted permissions:

Bucket

  • list objects in a bucket
  • create / get / delete / tag object in a bucket

DynamoDb Table

  • get / put / update / delete item in a table
  • scan / query a table
  • describe table stream

MongoDb Atlas Cluster

  • Allows connection to a cluster with accessibilityMode set to scoping-workloads-in-vpc. To learn more about MongoDb Atlas clusters accessibility modes, refer to MongoDB Atlas cluster docs.

Relational database

  • Allows connection to a relational database with accessibilityMode set to scoping-workloads-in-vpc. To learn more about relational database accessibility modes, refer to Relational databases docs.

Redis cluster

  • Allows connection to a redis cluster with accessibilityMode set to scoping-workloads-in-vpc. To learn more about redis cluster accessibility modes, refer to Redis clusters docs.

Event bus

  • publish events to the specified Event bus

Function

  • invoke the specified function

Batch job

  • submit batch-job instance into batch-job queue
  • list submitted job instances in a batch-job queue
  • describe / terminate a batch-job instance
  • list executions of state machine which executes the batch-job according to its strategy
  • start / terminate execution of a state machine which executes the batch-job according to its strategy

Using allowAccessTo

  • List of resource names that this function will be able to access (basic IAM permissions will be granted automatically). Granted permissions differ based on the resource.
  • Works only for resources managed by Stacktape (not arbitrary Cloudformation resources)
  • This is useful if you don't want to deal with IAM permissions yourself. Handling permissions using raw IAM role statements can be cumbersome, time-consuming and error-prone.

Copy

resources:
authFunction:
type: cdn-lambda-function
properties:
packaging:
type: stacktape-lambda-buildpack
properties:
entryfilePath: auth-function.ts
accessControl:
allowAccessTo:
- myDynamoTable
myDynamoTable:
type: dynamo-db-table
properties:
primaryKey:
partitionKey:
name: id
type: string

Using iamRoleStatements

  • IAM Role statements are a low-level, granular and AWS-native way of controlling access to your resources.
  • IAM Role statements can be used to add permissions to any Cloudformation resource.
  • Configured IAM role statement objects will be appended to the function's role.

Be advised when accessing resources from cdn-lambda-functions. While your stack (and the resources you are accessing) are deployed in a specific region, the function can be executed in any edge location around the world. This might result in higher latencies when function is accessing the resource from a more distant region.


Example:

  1. You have stack with a bucket and a cdn lambda function (which has access gratned to the bucket) deployed in region eu-west-1.
  2. Request to CDN comes to us-east-1 region.
  3. The function is executed in us-east-1 region. Due to network delays the communication between the function and the bucket might be slower.

API reference

StpIamRoleStatement  API reference
Parent API reference: AccessControl
Resource
Required

List of resources we want to access

Type: Array of string

  • See AWS reference here.
Sid

Statement identifier.

Type: string

  • See AWS reference here.
Effect

Effect of the statement

Type: string

  • See AWS reference here.
Action

List of actions allowed/denied by the statement

Type: Array of string

see AWS reference here.

Condition

No description

Type: UNSPECIFIED

Need help? Ask a question on SlackDiscord or info@stacktape.com.