MongoDB-AWS Auth with arbitrary AWS.Credentials

MongoDB authentication with AWS IAM is a very convenient means of authentication with MongoDB Atlas that allows one to delegate database authentication to AWS IAM, reducing the number of auth systems one needs to manage.

However, the native implementation of this authentication, as provided by MongoDB's published client libraries, only support static credentials to login, and a subset of the mechanisms by which refreshing credentials are generated (namely, EC2 instance credentials and ECS agent credentials). This makes the client libraries very difficult to use for other types of credentials which expire and are automatically refreshed over time, such as credentials for EKS pods generated by IAM roles for service accounts, credentials provided via SAML or OIDC, or any role assumed via role chaining. When a Mongo connection is established using AWS IAM authentication with one of these role types, the connection initially succeeds, but reconnections or scaling up the connection pool later on will fail when the initial set of credentials has expired.

The AWS SDK provides Credentials objects that automatically refresh, but the MongoDB drivers cannot utilize these; this project aims to fix that by patching the behavior of the Mongo driver to use the dynamic credentials of a AWS.Credentials object to establish new connections.

Example

const { MongoClient } = require('mongodb');
const { getMongoAwsAuth } = require('mongodb-auth-aws-improved');

// ... retrieve AWS credentials
let credentialsOrProvider; // can be an AWS.Credentials from aws-sdk v2, or a CredentialProvider from aws-sdk v3

const client = await new MongoClient(uri, { auth: getMongoAwsAuth(credentialsOrProvider) }).connect();