I have a postgres instance on AWS RDS. This instance allows you to connect to it using IAM authentication. I also have a lambda function that executes various queries defined in a separate file from the function implementation. This function is executed when calling an endpoint defined in API Gateway.
File with queries implementation:
const { Pool } = require("pg");
const region = process.env.REGION;
const signer = new aws.RDS.Signer({
region: process.env.REGION,
hostname: process.env.PG_HOST,
port: 5432,
username: "db_iamuser",
});
const pool = new Pool({
user: "db_iamuser",
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
port: 5432,
ssl: {
rejectUnauthorized: false,
},
password: () => signer.getAuthToken(),
});
async function destroy() {
await pool.end().then(() => console.log("DB Connection ended"));
}
async function getInfo1() {
const query = `SELECT field1, field2 FROM public.table1`;
try {
const response = await pool.query(query);
return response.rows;
} catch (error) {
throw error;
}
}
async function getInfo2() {
const query = `SELECT field1, field2 FROM public.table2`;
try {
const response = await pool.query(query);
return response.rows;
} catch (error) {
throw error;
}
}
async function getInfo3() {
const query = `SELECT field1, field2 FROM public.table3`;
try {
const response = await pool.query(query);
return response.rows;
} catch (error) {
throw error;
}
}
module.exports = {
getInfo1,
getInfo2,
getInfo3,
};
In the same function I create a user in AWS Cognito.
const { Responses } = require("../../libs/response");
const {
getInfo1,
getInfo2,
getInfo3,
} = require("../../libs/queries");
const { CognitoService } = require("../../libs/cognito");
exports.handler = async function (event, context) {
const { Authorization } = event.headers;
const user = JSON.parse(event.body);
try {
console.log("Getting Info1 ");
const info1 = await getInfo1();
console.log("Getting Info2 ");
const info1 = await getInfo2();
console.log("Getting Info3 ");
const info1 = await getInfo3();
//... Creating user in Cognito
await provider
.adminCreateUser(request)
.promise();
await provider
.adminAddUserToGroup({ request, GroupName })
.promise();
return Responses._200({ });
} catch (error) {
console.log("Error ", error);
throw error;
}
};
When I call the endpoint that executes the lambda function, the queries are executed without problems.
However, if I call again and immediately the endpoint throws me this error:
PAM authentication failed for user \"db_iamuser\"
Note: I isolated the queries in a lambda function that will not perform any actions in Cognito and it works every time I call it.
Please someone help me understand why this happens.