import handlebars from "handlebars"; import { Knex } from "knex"; import { TRotationFactory, TRotationFactoryCheckActiveCredentials, TRotationFactoryGetSecretsPayload, TRotationFactoryIssueCredentials, TRotationFactoryRevokeCredentials, TRotationFactoryRotateCredentials } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types"; import { BadRequestError } from "@app/lib/errors"; import { AppConnection } from "@app/services/app-connection/app-connection-enums"; import { executeWithPotentialGateway, getRoleUsernameForHost, SQL_CONNECTION_ALTER_LOGIN_STATEMENT } from "@app/services/app-connection/shared/sql"; import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator"; import { DEFAULT_PASSWORD_REQUIREMENTS, generatePassword } from "../utils"; import { TSqlCredentialsRotationGeneratedCredentials, TSqlCredentialsRotationWithConnection } from "./sql-credentials-rotation-types"; const redactPasswords = (e: unknown, credentials: TSqlCredentialsRotationGeneratedCredentials) => { const error = e as Error; if (!error?.message) return "Unknown error"; let redactedMessage = error.message; credentials.forEach(({ password }) => { redactedMessage = redactedMessage.replaceAll(password, "*******************"); }); return redactedMessage; }; const validateRotationUsernames = ( connectionUsername: string, host: string, rotationUsername1: string, rotationUsername2: string ) => { const connectionRoleUsername = getRoleUsernameForHost(connectionUsername, host); const rotationRoleUsername1 = getRoleUsernameForHost(rotationUsername1, host); const rotationRoleUsername2 = getRoleUsernameForHost(rotationUsername2, host); if (rotationRoleUsername1 === connectionRoleUsername || rotationRoleUsername2 === connectionRoleUsername) { throw new BadRequestError({ message: "Rotation username cannot be the same as the connection username. The connection credentials are used to execute rotation operations and changing their password would break the connection." }); } }; const ORACLE_PASSWORD_REQUIREMENTS = { ...DEFAULT_PASSWORD_REQUIREMENTS, length: 30 }; export const sqlCredentialsRotationFactory: TRotationFactory< TSqlCredentialsRotationWithConnection, TSqlCredentialsRotationGeneratedCredentials > = ( secretRotation, _appConnectionDAL, _dataKeyService, gatewayV2Service, gatewayPoolService, _keyStore, _instanceConfigService, passwordValidationContext ) => { const { connection, parameters: { username1, username2, rotationStatement: userProvidedRotationStatement, passwordRequirements: userProvidedPasswordRequirements }, activeIndex, secretsMapping } = secretRotation; validateRotationUsernames(connection.credentials.username, connection.credentials.host, username1, username2); const defaultPasswordRequirement = connection.app === AppConnection.OracleDB ? ORACLE_PASSWORD_REQUIREMENTS : DEFAULT_PASSWORD_REQUIREMENTS; const passwordRequirement = userProvidedPasswordRequirements || defaultPasswordRequirement; // When a secret validation rule covers this rotation, its constraints // fully replace the user-configured passwordRequirements. const generateRotationPassword = () => passwordValidationContext ? generatePasswordWithConstraints(passwordValidationContext.constraints) : generatePassword(passwordRequirement); let resolvedConnection: typeof connection | undefined; const getResolvedConnection = async () => { if (!resolvedConnection) { const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: connection.gatewayId, gatewayPoolId: connection.gatewayPoolId }); resolvedConnection = { ...connection, gatewayId: effectiveGatewayId, gatewayPoolId: null }; } return resolvedConnection; }; const executeOperation = async ( operation: (client: Knex) => Promise, credentialsOverride?: TSqlCredentialsRotationGeneratedCredentials[number] ) => { const conn = await getResolvedConnection(); const finalCredentials = { ...conn.credentials, ...credentialsOverride }; return executeWithPotentialGateway( { ...conn, credentials: finalCredentials }, gatewayV2Service, (client) => operation(client) ); }; const $validateCredentials = async (credentials: TSqlCredentialsRotationGeneratedCredentials[number]) => { try { await executeOperation(async (client) => { await client.raw(connection.app === AppConnection.OracleDB ? `SELECT 1 FROM DUAL` : `Select 1`); }, credentials); } catch (error) { throw new Error(redactPasswords(error, [credentials])); } }; const $executeQuery = async (tx: Knex, username: string, password: string) => { const filteredUsername = getRoleUsernameForHost(username, connection.credentials.host); if (userProvidedRotationStatement) { const revokeStatement = handlebars.compile(userProvidedRotationStatement)({ username: filteredUsername, password, database: connection.credentials.database }); const queries = revokeStatement.toString().split(";").filter(Boolean); for await (const query of queries) { await tx.raw(query); } } else { await tx.raw(...SQL_CONNECTION_ALTER_LOGIN_STATEMENT[connection.app]({ username: filteredUsername, password })); } }; const issueCredentials: TRotationFactoryIssueCredentials = async ( callback ) => { // For SQL, since we get existing users, we change both their passwords // on issue to invalidate their existing passwords const credentialsSet = [{ username: username1, password: generateRotationPassword() }]; // if both are same username like for mysql dual password rotation - we don't want to reissue twice loosing first cred access if (username1 !== username2) { credentialsSet.push({ username: username2, password: generateRotationPassword() }); } try { await executeOperation(async (client) => { await client.transaction(async (tx) => { for await (const credentials of credentialsSet) { await $executeQuery(tx, credentials.username, credentials.password); } }); }); } catch (error) { throw new Error(redactPasswords(error, credentialsSet)); } for await (const credentials of credentialsSet) { await $validateCredentials(credentials); } return callback(credentialsSet[0]); }; const revokeCredentials: TRotationFactoryRevokeCredentials = async ( credentialsToRevoke, callback ) => { const revokedCredentials = credentialsToRevoke.map(({ username }) => ({ username, password: generateRotationPassword() })); try { await executeOperation(async (client) => { await client.transaction(async (tx) => { for await (const credentials of revokedCredentials) { // invalidate previous passwords await $executeQuery(tx, credentials.username, credentials.password); } }); }); } catch (error) { throw new Error(redactPasswords(error, revokedCredentials)); } return callback(); }; const rotateCredentials: TRotationFactoryRotateCredentials = async ( _, callback ) => { // generate new password for the next active user const credentials = { username: activeIndex === 0 ? username2 : username1, password: generateRotationPassword() }; try { await executeOperation(async (client) => { await $executeQuery(client, credentials.username, credentials.password); }); } catch (error) { throw new Error(redactPasswords(error, [credentials])); } await $validateCredentials(credentials); return callback(credentials); }; const getSecretsPayload: TRotationFactoryGetSecretsPayload = ( generatedCredentials ) => { const { username, password } = secretsMapping; const secrets = [ { key: username, value: generatedCredentials.username }, { key: password, value: generatedCredentials.password } ]; return secrets; }; const checkActiveCredentials: TRotationFactoryCheckActiveCredentials< TSqlCredentialsRotationGeneratedCredentials > = async (activeCredentials) => { await $validateCredentials(activeCredentials); }; return { issueCredentials, revokeCredentials, rotateCredentials, getSecretsPayload, checkActiveCredentials }; };