Skip to content

added RDS IAM Auth example #908

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
Jul 9, 2024
Merged
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
10 changes: 10 additions & 0 deletions examples/lambda-rds-iam-auth/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Rust
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk
14 changes: 14 additions & 0 deletions examples/lambda-rds-iam-auth/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "rds-iam-rust-lambda"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_runtime = { path = "../../lambda-runtime" }
serde_json = "1.0.120"
aws-config = "1.0.1"
aws-credential-types = "1.0.1"
aws-sigv4 = "1.0.1"
url = "2.5.0"
tokio = { version = "1.25.0", features = ["full"] }
sqlx = { version = "0.7.4", features = ["tls-rustls", "postgres", "runtime-tokio"] }
134 changes: 134 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# CDK
node_modules
cdk.json

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
8 changes: 8 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# AWS Lambda Function that uses RDS's IAM Authnetication
This example shows how to build and deploy Rust Lambda Function and an RDS instance using AWS CDK and

Build & Deploy
1. `npm install`
1. `npx cdk deploy`
1. Using the dev instance or using a local Postgres client: connect into the RDS instance as root and create the required Users with permissions `CREATE USER lambda; GRANT rds_iam TO lambda;`
1. Go to the Lambda Function in the AWS console and invoke the lambda function
105 changes: 105 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { join } from 'path';
import * as cdk from 'aws-cdk-lib';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { RustFunction } from '@cdklabs/aws-lambda-rust'

class LambdaRDSStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Create a VPC
const vpc = new ec2.Vpc(this, 'VPC');

// Admin DB user
const DB_ADMIN_USERNAME = 'root';
const DB_USERNAME = 'lambda';

// Lambda DB user
const DB_NAME = 'foo';

// Create an RDS instance
const db = new rds.DatabaseInstance(this, 'Postgres', {
engine: rds.DatabaseInstanceEngine.POSTGRES,
vpc,
vpcSubnets: vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }),
credentials: rds.Credentials.fromGeneratedSecret(DB_ADMIN_USERNAME),
iamAuthentication: true,
publiclyAccessible: true,
databaseName: DB_NAME,
deleteAutomatedBackups: true,
removalPolicy: cdk.RemovalPolicy.DESTROY
})

db.connections.allowFromAnyIpv4(ec2.Port.allTcp())

// RDS SSL Cert Lambda Layer alternative to loading the certificates at compile time
/*
const certLayer = new lambda.LayerVersion(this, 'CertLayer', {
description: 'SSL Certificate Layer',
code: lambda.Code.fromAsset('certs'),
compatibleArchitectures: [lambda.Architecture.X86_64, lambda.Architecture.ARM_64]
});
*/

const lambdaSG = new ec2.SecurityGroup(this, 'LambdaSG', {
securityGroupName: 'LambdaSG',
allowAllOutbound: true,
vpc: vpc,
})
// create a rust lambda function
const rustLambdaFunction = new RustFunction(this, "lambda", {
entry: join(__dirname, '..', 'lambda'),
vpc: vpc,
securityGroups: [lambdaSG],
environment: {
DB_HOSTNAME: db.dbInstanceEndpointAddress,
DB_PORT: db.dbInstanceEndpointPort,
DB_NAME: DB_NAME,
DB_USERNAME: DB_USERNAME,
},
bundling: {
forceDockerBundling: true,
},
runtime: lambda.Runtime.PROVIDED_AL2023,
timeout: cdk.Duration.seconds(60),
});

// MySQL
/*
CREATE USER 'lambda' IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS';
GRANT ALL PRIVILEGES ON foo.* TO 'lambda';
ALTER USER 'lambda' REQUIRE SSL;
*/

// Postgres
/*
CREATE USER db_userx;
GRANT rds_iam TO db_userx;
*/
db.grantConnect(rustLambdaFunction, DB_USERNAME);
db.connections.allowDefaultPortFrom(rustLambdaFunction);

/*
Dev Instance for initialising the datbase with the above commands
*/
const devInstance = new ec2.Instance(this, 'dev', {
vpc,
vpcSubnets: vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }),
machineImage: ec2.MachineImage.latestAmazonLinux2023(),
instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MEDIUM)
})
db.grantConnect(devInstance, DB_ADMIN_USERNAME);
db.grantConnect(devInstance, DB_USERNAME);
db.connections.allowDefaultPortFrom(devInstance);

// Output the Lambda function ARN
new cdk.CfnOutput(this, 'LambdaFunctionConsole', {
value: `https://${this.region}.console.aws.amazon.com/lambda/home?region=${this.region}#/functions/${rustLambdaFunction.functionName}?tab=testing`
});
}
}

const app = new cdk.App();
new LambdaRDSStack(app, 'LambdaRDSStack');
21 changes: 21 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"app": "npx ts-node --prefer-ts-exts app.ts",
"watch": {
"include": [
"**.js",
"**.rs",
"**.ts"
],
"exclude": [
"README.md",
"cdk*.json",
"**/*.d.ts",
"**/*.js",
"tsconfig.json",
"package*.json",
"yarn.lock",
"node_modules",
"test"
]
}
}
13 changes: 13 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"dependencies": {
"@cdklabs/aws-lambda-rust": "0.0.4",
"aws-cdk-lib": "^2.147.0",
"path": "^0.12.7",
"prettier": "^3.3.2",
"rust.aws-cdk-lambda": "^1.2.1",
"ts-node": "^10.9.2"
},
"devDependencies": {
"@types/node": "^20.14.10"
}
}
31 changes: 31 additions & 0 deletions examples/lambda-rds-iam-auth/cdk/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": [
"es2020",
"dom"
],
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": false,
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
"typeRoots": [
"./node_modules/@types"
]
},
"exclude": [
"node_modules",
"cdk.out"
]
}
Loading
Loading