We are using lambda functions that authenticate with MongoDB via IAM. The IAM credentials are obtained via STS. This works fine in the beginning, but credentials obtained via role chaining are only valid for an hour max. When our lambda execution context lasts longer than an hours, then we get authentication errors from MongoDB.
How can I rotate my credentials?
Current situation
The flow is this:
- Lambda assumes MONGO_ACCESS_ROLE via STS
- Temporary STS credentials are used in a MongoClient instance as auth mechanism
To reuse connections I have db client defined outside of the lambda handler:
export class DatabaseClient {
private static client: null | MongoClient = null;
public static async create() {
if (this.client) {
return this.client;
} else {
const roleArn = "REDACTED ROLED ARN";
const region = "eu-central-1";
const sts = new STSClient({ credentials, region });
const { Credentials } = await sts.send(
new AssumeRoleCommand({
RoleArn: roleArn,
RoleSessionName: "AccessMongoDB",
DurationSeconds: 3600,
}),
);
// Create connection string
const { AccessKeyId, SessionToken, SecretAccessKey = "" } = Credentials;
const encodedSecretKey = encodeURIComponent(SecretAccessKey);
const combo = `${AccessKeyId}:${encodedSecretKey}`;
const url = new URL(`mongodb+srv://${combo}@aaaaa.bbb.mongodb.net`);
url.searchParams.set("authSource", "$external");
url.searchParams.set("authMechanismProperties", `AWS_SESSION_TOKEN:${SessionToken}`);
url.searchParams.set("w", "majority");
url.searchParams.set("retryWrites", "true");
url.searchParams.set("authMechanism", "MONGODB-AWS");
const connectionString = url.toString();
this.client = new MongoClient(connectionString);
return this.client;
}
}
}
Solutions considered
I checked https://github.com/scaleapi/mongodb-auth-aws-improved but it does not work with the current mongo driver.