Rotate ApsaraDB for RDS credentials in Spring applications

更新时间:
复制 MD 格式

This topic describes how to rotate credentials for an ApsaraDB for RDS data source at runtime in a Spring application. By integrating Key Management Service (KMS) and Nacos, you can securely host, dynamically update, and seamlessly switch your database credentials. This ensures your application's security and stability during credential changes.

Overview

For Java applications built with the Spring Boot or Spring Cloud framework that use databases such as MySQL, SQL Server, PostgreSQL, or MariaDB, we recommend adopting a runtime data source rotation solution to enhance security. The solution architecture is shown in the following figure:

image

This solution uses Key Management Service (KMS) to encrypt and host database credentials, Nacos for dynamic configuration management, and Druid to manage the database connection pool. The solution supports the following features:

  • Centralized management and encrypted storage/transmission of data source configurations: Manage database connection information centrally and use encryption to secure configuration data during storage and transmission.

  • Fully-managed credentials with dual-layer access control: The system fully manages database credentials, using a dual-layer authentication mechanism to improve access security.

  • Scheduled runtime credential rotation and rapid leak remediation: Automatically rotate database credentials at runtime based on a defined policy and quickly remediate leaks to reduce security risks.

  • Seamless account switching at runtime: Switch database access accounts at runtime without interrupting business operations to ensure high availability and improve maintenance flexibility.

  • Application-side database performance parameter tuning: Flexibly adjust key performance parameters, such as connection pool size and timeout settings, to improve system stability and responsiveness.

  • Invalid parameter protection: Validates and protects critical parameters to prevent misconfigurations from causing business disruptions, ensuring a safe and controllable change process.

Prerequisites

  • Activate ApsaraDB for RDS and create an instance.

    Procedure

    After activating ApsaraDB for RDS, follow these steps to create an instance if you do not have one. For more information about configuration options, see Create an ApsaraDB RDS for MySQL instance.

    Click here to open the new RDS instance creation page and configure the following basic settings. Leave the other settings at their default values.

    1. Billing Method: For short-term testing, we recommend that you select Pay-As-You-Go.

    2. Region: Select a region. You cannot change this setting after the instance is created.

    3. Product Series: Select Basic Series. This series is cost-effective and suitable for learning or testing. It takes a long time to recover from failures and restart.

  • Activate Key Management Service (KMS), create a dedicated KMS instance, and create a KMS key ID.

    Create a dedicated KMS instance

    After activating Key Management Service (KMS), follow these steps to create an instance if you do not have one. For more information about configuration options, see Create a dedicated KMS instance.

    Go to the Instance Management page of the KMS console. In the top menu bar, select a region and click Create Instance. Select a region and leave the other settings at their default values.

    Create a KMS key ID

    If you do not have a key, follow these steps to create one. For more information about key configurations, see Manage keys.

    Go to the Key Management page of the KMS console. In the top menu bar, select a region, click the Default Keys tab, and click Enable in the Actions column of the customer master key. Configure the following basic settings and keep the default values for other settings:

    1. Alias: The alias of the key.

    2. Advanced Settings: The source of the key material.

      • Alibaba Cloud KMS: The key material is generated by KMS.

      • External: KMS does not generate the key material. You must import the key material. For more information, see Import symmetric key material.

      Carefully read and select I understand the methods and implications of using external key material.
  • Activate Microservices Engine (MSE) and create an Enterprise Edition instance.

    Create an Enterprise Edition instance

    After activating Microservices Engine, follow these steps to create an instance if you do not have one. For more information about configuration options, see Create an instance.

    Go to the Instance List page of the MSE console. In the top menu bar, select a region and click Create Instance. Configure the following basic settings and keep the default values for other settings:

    1. Billing Method: For short-term testing, we recommend that you select Pay-As-You-Go.

    2. Region: Select a region. You cannot change this setting after the instance is created.

    3. Edition: Select Enterprise Edition.

      This feature is available only in the Enterprise Edition of MSE Nacos, not in the Professional or Developer editions.
    4. Instance Name: Set a name for the instance. The name must be unique within the region and cannot be changed after the instance is created.

Create KMS credentials

  1. Go to the Credential Management page of the KMS console and select Database Credentials.

  2. Select an Instance ID, and then click Create Credential > Create a Single Credential.

  3. In the Create Database Credential panel, select a Database Type for the RDS Credential, enter a Credential Name, and select the associated RDS Instance.

  4. Select Managed dual accounts, enter a Custom Account Name, Select Database, and Specify Permissions.

    In the Set Credential Value section, select the New Account tab. After you enter a custom account name, the system automatically generates the corresponding database account.

  5. Select a customer master key, set the Rotation Period, and click OK.

When you create a KMS credential, the system automatically generates a database access account with a strong password.

Create a data source

Note

Data source configurations are managed by the Nacos configuration center and stored in an encrypted format.

  1. Go to the Instance List page of the MSE console. In the top menu bar, select a region.

  2. Click the name of the target Enterprise Edition instance. In the left-side navigation pane, choose Data Source Management.

    If the instance is not yet bound to a KMS key, follow the on-screen instructions to bind one.
  3. On the Data Source Management page, select the target namespace, and click Create Data Source.

  4. In the Create Data Source panel, configure the data source parameters. For more information about the parameters, see Create a data source.

    In this example, Data Source Type is set to spring-datasource, Sub-type is set to druid, and Database Type is set to rds and associated with an existing RDS instance. Database Engine Type is set to MySQL, Database Port is set to 3306, and Database Name is set to test-1. The default connection pool parameters are used: Initial Size is 20, Min Idle is 20, Max Active is 100, and Max Wait is 5000. Associate KMS Credential is set to test1(Rds).

  1. Click OK. In the Confirm Data Source Creation dialog box, click OK to submit the data source.

Credential rotation

KMS provides two methods for rotating data source credentials:

  • Scheduled rotation: Set a rotation period when creating a credential. The credential rotates automatically when the period expires.

  • Immediate rotation: If a credential is leaked or must be changed for other urgent reasons, you can trigger an immediate rotation from the KMS Credential Management console.

When KMS credentials are rotated, either on a schedule or manually, KMS notifies MSE Nacos to update the encrypted data source configuration. Nacos then pushes the update to the application in real time. Druid gracefully replaces the online connections, ensuring no impact on your business.

Note

Credential rotation is managed by Secrets Manager. If you directly change the password of a managed account through the ApsaraDB for RDS console, an OpenAPI call, or a high-privilege account in the database, the change cannot be pushed to the application in real time.

Application access

Click Application Access on the data source details page to view the access steps for each data source.

Note

For parameter configurations, use the actual settings provided on the Application Access tab in the console. The parameters shown in the console are customized for your specific instance and data source.

Step 1: Upgrade dependencies

  • Upgrade Spring Cloud to version 2023.0.3.3 or later.

  • Upgrade Druid to version 1.2.27 or later.

<!--  Druid connection pool, including Spring Starter and the Druid core version -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-3-starter</artifactId>
	<version>1.2.27</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.27</version>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2023.0.3.3</version>
</dependency>
<!--  Commercial KMS encryption/decryption plugin -->
<dependency>
	<groupId>com.alibaba.nacos</groupId>
	<artifactId>nacos-client-mse-extension</artifactId>
	<version>1.0.5</version>
</dependency> 

Step 2: Modify the configuration

  • Modify application.properties to enable dynamic data source rotation and specify the Nacos configuration for the data source.

# Import the data source configuration into Spring to initialize the data source.
spring.config.import[0]=optional:nacos:cipher-kms-aes-256-proxy-spring-{resourceName}.properties?group=nacos-datasource
# Specify the Nacos address. The public endpoint is used by default. Modify it as needed.
spring.cloud.nacos.config.server-addr={nacos server}
# Specify the namespace.
spring.cloud.nacos.config.namespace={namespace ID}
# Specify the KMS region ID.
spring.cloud.nacos.config.kms_region_id={instance region}
# Enable Druid data source management and specify the dataId for the encrypted rotation configuration.
spring.nacos.config.proxy.druid.enabled=true
spring.nacos.config.proxy.druid.data-id={dataID}

Step 3: Set access credentials

Because the data source configuration is encrypted, your application needs credentials with decryption permissions at runtime. You can provide these credentials using one of two methods:

AK-free access credentials (recommended)

If your application runs on Alibaba Cloud ECS or ACK, we recommend using the AK-free method. Set the following JVM parameter:

  • For ECS RAM roles:

    -Dspring.cloud.nacos.config.ramRoleName=${ramRoleName}
  • For OIDC Role ARN:

    -Dspring.cloud.nacos.config.alibabaCloudRoleSessionName=${sessionName}

AccessKey and SecretKey method

Set the following JVM parameters:

-Dspring.cloud.nacos.config.accessKey=${accessKey}
-Dspring.cloud.nacos.config.secretKey=${secretKey}

Replace ${accessKey} and ${secretKey} with your actual AccessKey and SecretKey.

Regardless of which method you choose, you must grant permissions to the credentials. Grant the "Decrypt permission for KMS encrypted configurations" to the corresponding account or role to allow the application to decrypt the encrypted configuration into plaintext in memory.

Go to the current instance page and choose Security > Authentication and Authorization > Client Authentication . For the authorization scope, select Decrypt permission for KMS encrypted configurations, and follow the instructions to complete the authorization. For more credential types, see Configure access credentials for a client.

FAQ

1. When does KMS credential rotation invalidate old credentials?

When KMS rotates credentials, it notifies MSE to update them. KMS keeps the two most recent credential versions active simultaneously; older versions are invalidated. In the future, this feature will integrate with the session management of specific data sources to ensure that old credentials are not invalidated until all online connections that use them are closed. This further improves stability.

2. Can I detect when the exception protection mechanism is triggered on the application side?

When the data connection pool's exception protection is triggered on the application side, the application reports a push failure to Nacos. You can check the config.log file for the "notify-error" keyword to detect these events. Future versions of Nacos will report the callback status of client listeners, allowing you to directly see failed client callbacks in the listener query function.