Search code examples
mysqlnode.jsamazon-web-servicesamazon-rdsknex.js

How to securely connect Knex to RDS


I have a NodeJS application using Objection and Knex libraries connecting to a MySQL database in AWS RDS. I am able to connect to it with knex if I set up the knex file with the proper accessibility tokens and credentials, as well as make the RDS publicly accessible with Inbound Rules allowing traffic to 3306 from everywhere.

I realize that anyone with the accessibility tokens and password can access the database.

Can I ask, if there is a more secure way to connect to RDS? For example, I am able to connect to AWS RDS through MySQL workbench by using a PEM file to an EC2 instance which has a connection to the RDS database. For this connection, the RDS Database need not be publicly accessible nor does it need to allow Inbound traffic from anywhere.

What I Have Tried

With the credentials set up, I have tried connecting without public accessibility and with Inbound traffic only allowing from my IP. And I have tried w/o pub access + allowing traffic anywhere. And w/ public access + allowing only my IP.

All of those did not succeed.

Only when I made it publicly accessible and open to all Inbound traffic, did it work.

Also, I tried looking at the Knex documentation and could not find a connection to EC2 or using a PEM file.

Is this the most secure way to have Knex connect to RDS? Is this good in terms of best practices?

This is a template of my connection object code:

{
    client: 'mysql2',
    connection: {
      host: HOST,
      user: USERNAME,
      password: PASSWORD,
      database: DATABASE,
    },
    migrations: {
      tableName: MIGRATIONS_TABLE_NAME,
    },
  };

Solution

    1. Your RDS should generally be accessed from applications that are also running on AWS. It should not have any public access.
    2. Use the [AWS Secrets Manager(https://aws.amazon.com/secrets-manager/) to manage credentials
    3. If you need to connect from your personal environment, set up a bastion host on EC2 (you can use a tiny free machine) that can connect to RDS and then restrict access to that bastion server to specific IP addresses outside of AWS. In this case you'll basically be tunneling to RDS via that bastion host.