DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS
  • Breaking AWS Lambda: Chaos Engineering for Serverless Devs
  • AWS Step Functions Local: Mocking Services, HTTP Endpoints Limitations

Trending

  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Passwordless Database Authentication for AWS Lambda

Passwordless Database Authentication for AWS Lambda

In this post, we take a look at how to allow access to your RDS database from a serverless application! Read on for the details!

By 
Andreas Wittig user avatar
Andreas Wittig
·
Oct. 20, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
11.5K Views

Join the DZone community and get the full member experience.

Join For Free

Does your serverless application need to access an RDS database? Where do you store the username and the password required to authenticate with the database? Storing the password in plain text within your source code should not be an option. Same is true for the environment variables of your Lambda function. Using KMS to encrypt the database password is possible but cumbersome. Lucky you, there is an elegant solution to the problem of authenticating a Lambda function with an RDS database.

Instead of using a conventional database user with password make use of IAM Database Authentication for MySQL and Amazon Aurora. As shown in the following figure using an IAM role to authenticate at an RDS database is possible. You no longer have to cope with a database password, you are using the IAM role of your Lambda function instead.

Overview of Passwordless Database Authentication

The following instructions guide you through configuring IAM database authentication for a Lambda function written in Node.js accessing an RDS database cluster with Aurora (MySQL) engine.

Before we start, let’s talk about the restrictions when using IAM database authentication:

  • Using the MySQL or Aurora RDS engine is required (MySQL >=5.6.34, MySQL >=5.7.16, Aurora >1.10).
  • A Secure Sockets Layer (SSL) database connection is needed.
  • Smallest database instance types do not support IAM database authentication. db.t1.micro and db.m1.small instance types are excluded for MySQL. The db.t2.small instance type is excluded for Aurora.
  • AWS recommends creating no more than 20 database connections per second when using IAM database authentication.

Step 1: Enabling IAM Database Authentication

First of all, you need to enable IAM database authentication. Type in the following command into your terminal to enable IAM database authentication for your Aurora database cluster. Replace <DB_CLUSER_ID> with the identifier of your Aurora database cluster.

aws rds modify-db-cluster --db-cluster-identifier <DB_CLUSTER_ID> --enable-iam-database-authentication --apply-immediately

See Enabling and Disabling IAM Database Authentication if you need more detailed information.

Step 2: Preparing a Database User

Next, you need to connect to your database and create a user using the AWS authentication plugin.

The following SQL statement creates a database user named lambda. Instead of specifying a password, the AWSAuthenticationPlugin is used for identifying the user. Replace <DB_NAME> with the name of the database you want to grant the user access to.

CREATE USER 'lambda' IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS';GRANT ALL PRIVILEGES ON <DB_NAME>.* TO 'lambda'@'%';FLUSH PRIVILEGES;

I’m using a database named lambda_test. Therefore, my SQL query looks as follows.

CREATE USER 'lambda' IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS';GRANT ALL PRIVILEGES ON lambda_test.* TO 'lambda'@'%';FLUSH PRIVILEGES;

Step 3: Creating an IAM Role

Probably, you have already configured an IAM role for your Lambda function. To be able to authenticate with the RDS database you need to add an IAM policy to the IAM role.

The following snippet shows a policy granting access to authenticate with an RDS database. Replace <REGION> with the region the database is running in, <AWS_ACCOUNT_ID> with the account id of your AWS account and <DB_RESOURCE_ID> with the resource id of your database cluster. Also, don’t forget to replace <DB_USERNAME> with the username lambda created in step 2.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "rds-db:connect",
      "Resource": "arn:aws:rds-db:<REGION>:<AWS_ACCOUNT_ID>:dbuser:<DB_RESOURCE_ID>/<DB_USERNAME>"
    }
  ]
}

My IAM policy looks like this, for example.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "rds-db:connect"
      ],
      "Resource": [
        "arn:aws:rds-db:eu-west-1:486555357186:dbuser:cluster-PWZUABBM2Y3H354WLBRDGBL7MI/lambda"
      ]
    }
  ]
}

Warning: It might take a few minutes until changes to your IAM role are in effect. Be careful when debugging authentication issues. Sometimes getting a cup of coffee or tea solves the problem.

Step 4: Connecting to the Database

Finally, you can write the source code for your Lambda function. Install the mysql2 module used to establish a database connection to Aurora.

 npminstallmysql@1.4.2 

The following snippet contains the source code needed to access the RDS database from your Lambda function. Note you have to edit the database connection details as well as the query (see TODO).

'use strict';
const mysql = require('mysql2');
const AWS = require('aws-sdk');
// TODO use the details of your database connection
const region = 'eu-west-1';
const dbPort = 3306;
const dbUsername = 'lambda'; // the name of the database user you created in step 2
const dbName = 'lambda_test'; // the name of the database your database user is granted access to
const dbEndpoint = 'lambdatest-cluster-1.cluster-c8o7oze6xoxs.eu-west-1.rds.amazonaws.com';
module.exports.handler = (event, context, cb) => {
  var signer = new AWS.RDS.Signer();
  signer.getAuthToken({ // uses the IAM role access keys to create an authentication token
    region: region,
    hostname: dbEndpoint,
    port: dbPort,
    username: dbUsername
  }, function(err, token) {
    if (err) {
      console.log(`could not get auth token: ${err}`);
      cb(err);
    } else {
      var connection = mysql.createConnection({
        host: dbEndpoint,
        port: dbPort,
        user: dbUsername,
        password: token,
        database: dbName,
        ssl: 'Amazon RDS',
        authSwitchHandler: function (data, cb) { // modifies the authentication handler
          if (data.pluginName === 'mysql_clear_password') { // authentication token is sent in clear text but connection uses SSL encryption
            cb(null, Buffer.from(token + '\0'));
          }
        }
      });
      connection.connect();
      // TODO replace with your SQL query
      connection.query('SELECT * FROM lambda_test.test', function (err, results, fields) {
        connection.end();
        if (err) {
          console.log(`could not execute query: ${err}`);
          cb(err);
        } else {
          cb(undefined, results);
        }
      });
    }
  });
};

Summary

The IAM database authentication is superseding handling the database password within your serverless application. All you need is to attach an IAM role to your Lambda function.

Using an authentication token instead of a password increases security:

  • You don’t have to store the password in your source code or the Lambda function’s environment variables.
  • The authentication token is a generated secret (Signature Version 4 signing process).
  • The authentication token has a limited lifetime (15 minutes).
Database connection authentication AWS AWS Lambda Aurora (protocol)

Published at DZone with permission of Andreas Wittig. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building Scalable Data Lake Using AWS
  • Building a Scalable ML Pipeline and API in AWS
  • Breaking AWS Lambda: Chaos Engineering for Serverless Devs
  • AWS Step Functions Local: Mocking Services, HTTP Endpoints Limitations

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!