Move pwd rotation stuff to the new sql conn obj

This commit is contained in:
Fang-Pen Lin
2025-10-24 12:29:22 -07:00
parent cc6f0e79dd
commit 3e8b6bf3e7
@@ -33,6 +33,15 @@ export interface SqlResourceConnection {
*/ */
validate: (connectOnly: boolean) => Promise<void>; validate: (connectOnly: boolean) => Promise<void>;
/**
* Rotate password and return the new credentials.
*
* @param currentCredentials the current credentials to rotate
*
* @returns Promise to be resolved with the new credentials
*/
rotateCredentials: (currentCredentials: TSqlAccountCredentials) => Promise<TSqlAccountCredentials>;
/** /**
* Close the connection. * Close the connection.
* *
@@ -103,6 +112,11 @@ const makeSqlConnection = (
}); });
} }
}, },
rotateCredentials: async (currentCredentials) => {
const newPassword = alphaNumericNanoId(32);
await client.raw(`ALTER USER ?? WITH PASSWORD ?'`, [currentCredentials.username, newPassword]);
return { username: currentCredentials.username, password: newPassword };
},
close: () => client.destroy() close: () => client.destroy()
}; };
} }
@@ -148,6 +162,12 @@ const makeSqlConnection = (
await client?.end(); await client?.end();
} }
}, },
rotateCredentials: async (currentCredentials) => {
// TODO: the pwd rotation for MySQL is not supported yet
throw new BadRequestError({
message: "Unsupported operation"
});
},
close: async () => {} close: async () => {}
}; };
} }
@@ -269,9 +289,7 @@ export const sqlResourceFactory: TPamResourceFactory<TSqlResourceConnectionDetai
currentCredentials currentCredentials
) => { ) => {
try { try {
const newPassword = alphaNumericNanoId(32); return await executeWithGateway(
await executeWithGateway(
{ {
connectionDetails, connectionDetails,
gatewayId, gatewayId,
@@ -280,20 +298,8 @@ export const sqlResourceFactory: TPamResourceFactory<TSqlResourceConnectionDetai
password: rotationAccountCredentials.password password: rotationAccountCredentials.password
}, },
gatewayV2Service, gatewayV2Service,
async (client) => { (client) => client.rotateCredentials(currentCredentials)
switch (resourceType) {
case PamResource.Postgres:
await client.raw(`ALTER USER ?? WITH PASSWORD '${newPassword}'`, [currentCredentials.username]);
break;
default:
throw new BadRequestError({
message: `Password rotation for ${resourceType as PamResource} is not supported.`
});
}
}
); );
return { username: currentCredentials.username, password: newPassword };
} catch (error) { } catch (error) {
if (error instanceof BadRequestError) { if (error instanceof BadRequestError) {
if (error.message === `password authentication failed for user "${rotationAccountCredentials.username}"`) { if (error.message === `password authentication failed for user "${rotationAccountCredentials.username}"`) {