Use RDS MySQL to store API keys
Switch the API key storage backend of Agent Sandbox from the default Secret to ApsaraDB RDS for MySQL. This is suitable for multi-tenant production environments or production environments with a large number of API keys.
Background information
ack-sandbox-manager supports two API key storage backends, Secret and MySQL, controlled by the keyStorage.mode configuration item, which takes the value secret (default) or mysql. The Secret backend already meets the requirements of development and testing scenarios and of scenarios with a small number of keys. With the MySQL backend, the data scale is no longer limited by the size of a single Secret.
|
Comparison item |
Secret (default) |
MySQL |
|
External dependency |
None |
Requires a MySQL instance, and you must configure the Data Source Name (DSN) and |
|
Storage location |
|
An external MySQL database. |
|
Key storage format |
Stores the original API key in a recoverable form. |
Stores only the |
|
Capacity |
Constrained by the 1 MiB limit of a single Kubernetes Secret. |
Not limited by the size of a single Secret. The capacity depends on the database instance. |
|
Read and write method |
Each addition or deletion updates the entire Secret, so the read and write overhead increases as the number of records grows. |
Queries by key hash, so the read and write overhead remains relatively stable. |
|
Multiple replicas |
Multiple replicas share the same Secret. |
Multiple replicas share the same database. |
|
Scenarios |
Development and testing, single-tenant scenarios, or scenarios with a small number of keys. |
Production environments, multi-tenant scenarios, or scenarios with a large number of keys. |
Select a backend based on the total number of API keys in the cluster:
-
500 or fewer: Secret is sufficient.
-
501 to 1,000: (Recommended) Plan a migration to MySQL.
-
More than 1,000: Use MySQL to avoid write failures when the Secret approaches the 1 MiB limit.
Applicable scope
-
You have completed the multi-tenant management configuration of Agent Sandbox, installed
ack-sandbox-manager(v0.6.7 or later), and enabled API key authentication. For instructions, see Multi-tenancy management.
Create and configure an RDS MySQL instance
API key storage is an OLTP (Online Transaction Processing) workload with a small data volume that mainly performs hash-based point queries. Before you purchase an RDS MySQL instance, expand the selection recommendations panel below to plan the instance configuration.
-
Go to the RDS purchase page and create an RDS MySQL instance. (Recommended) Select the same region and VPC as the Container Compute Service cluster, and configure the instance based on the selection recommendations above.
-
Create a database and an account. Perform the following operations on the Databases and Accounts pages of the RDS instance. For instructions, see Create an account.
-
Create a database, for example,
e2b. -
Create a standard database account and record the account name and password.
-
Grant the account the Read/Write (DDL + DML) permission on the target database.
-
-
Configure an IP address whitelist.
sandbox-managerand other control plane components send access traffic from the control plane vSwitch, so you must add the control plane vSwitch CIDR block to the RDS whitelist.-
Log on to the Container Compute Service console and go to the Basic Information page of the target cluster.
-
In the Network section, on the right side of Control Plane vSwitch, click Edit and copy the CIDR blocks of all selected vSwitches.
-
Log on to the RDS console and go to the Whitelist and SecGroup page of the target instance.
-
Modify the
defaultwhitelist group and add the IPv4 CIDR blocks of the control plane vSwitch to the whitelist of that group.
-
-
On the database connection page of the RDS instance, record the Internal Endpoint and the Internal Port. For example:
rm-******************.mysql.rds.aliyuncs.com:3306 -
Manually initialize the table schema. Run the mysql-schema.sql script provided by the OpenKruise community:
mysql -h <RDS internal endpoint> \ -P <port> \ -u <database account> \ -p \ <database name> < mysql-schema.sqlThe script creates the
teamsandteam_api_keystables and initializes the built-inadminTeam. The hash of the admin API key does not need to be migrated. Whenack-sandbox-managerstarts, it automatically computes the hash based on the currenthashPepperand writes the hash toteam_api_keys.
Configure the MySQL storage backend
-
Log on to the Container Compute Service console and go to the target cluster.
-
On the Add-ons page, find
ack-sandbox-managerand click Configuration. -
Configure the following parameters:
Configuration item
Value or description
keyStorage.modeSet this parameter to
mysql.keyStorage.mysql.dsnThe DSN describes the account, password, address, port, and connection parameters used to connect to the target database. For the format, see the example below.
keyStorage.mysql.hashPepperThe long-term secret used to compute the API key hash.
-
Specify the DSN in the following format:
<account>:<password>@tcp(<RDS internal endpoint>:<port>)/<database name>?charset=utf8mb4&parseTime=true&loc=LocalExample:
e2b_user:********@tcp(rm-******************.mysql.rds.aliyuncs.com:3306)/e2b?charset=utf8mb4&parseTime=true&loc=LocalGenerate a random 32-byte (256-bit) string as the
hashPepper.openssl rand -hex 32The command outputs 64 hexadecimal characters, which you can use directly as the value of
keyStorage.mysql.hashPepper.ImportantStore
hashPeppersecurely for the long term and do not set it to the same value as the database password. After you change this value, the API keys of existing tenants can no longer pass authentication and must be reissued. -
Save the configuration.
ack-sandbox-managerautomatically restarts and connects to RDS MySQL.When
keyStorage.modeis set tomysql, the component fails to start if the DSN orhashPepperis not configured.
Verify the configuration
-
Confirm that the
ack-sandbox-managerPod is running properly:kubectl get pods -n sandbox-system -l component=sandbox-managerExpected output:
NAME READY STATUS RESTARTS AGE sandbox-manager-79b7449778-xxx 2/2 Running 0 78m sandbox-manager-79b7449778-yyy 2/2 Running 0 79m sandbox-manager-79b7449778-zzz 2/2 Running 0 78m -
Create, query, and then delete a temporary API key to verify that the MySQL backend reads and writes data correctly. Before you run the commands, replace the following variables based on your actual environment:
-
BASE_URL: the external access address ofack-sandbox-gateway. -
ADMIN_KEY: the admin API key configured forack-sandbox-manager.
The following script relies on jq (a command-line JSON processor) to parse responses. Before you run the script, make sure that it is installed on your local machine.
BASE_URL="https://api.your.domain.com" ADMIN_KEY="your-admin-key" TEST_KEY_ID=$( curl -fsS -X POST \ -H "X-API-KEY: ${ADMIN_KEY}" \ -H "Content-Type: application/json" \ -d '{"name":"mysql-storage-verification"}' \ "${BASE_URL}/api-keys" | jq -r '.id' ) echo "Created: ${TEST_KEY_ID}" curl -fsS \ -H "X-API-KEY: ${ADMIN_KEY}" \ "${BASE_URL}/api-keys" | jq -e --arg id "${TEST_KEY_ID}" \ 'any(.[]; .id == $id)' >/dev/null && echo "Query OK" curl -fsS -X DELETE \ -H "X-API-KEY: ${ADMIN_KEY}" \ "${BASE_URL}/api-keys/${TEST_KEY_ID}" && echo "Deleted: ${TEST_KEY_ID}"Expected output:
Created: 4f2ab49a-aced-4830-b5da-5d382xxxxxxx Query OK Deleted: 4f2ab49a-aced-4830-b5da-5d382xxxxxxx -
Migrate existing API keys (optional)
If you need to keep using the existing API keys from the original Secret backend after the switch to MySQL, run the migrate_secret_keys_to_mysql.py script provided by the OpenKruise community. The migration script performs the following operations:
-
Uses
kubectlto read thee2b-key-storeSecret. -
Computes the HMAC-SHA256 hash of each API key by using the same value as
keyStorage.mysql.hashPepper. -
Generates the table creation DDL and the upsert statements for Teams and API keys.
-
Preserves the original Teams, key names, creation information, and quota configurations.
The script depends only on the Python 3 standard library and kubectl.
After the migration starts, pause calls to POST /api-keys and DELETE /api-keys/{id} until the data import is complete, so that data changes made during the migration are not lost.
-
Validate the Secret data:
python3 migrate_secret_keys_to_mysql.py \ --namespace sandbox-system \ --dry-runThis command parses all entries in the Secret and validates fields such as
id,name, andkey. It also checks whether the Team metadata is consistent and whether the original keys are unique. If any check fails, the migration is aborted to prevent incomplete SQL from being generated. -
Set
hashPepperby entering it at a hidden prompt (the value must be exactly the same as the configuredkeyStorage.mysql.hashPepper) and generate the migration SQL:read -rsp "Enter hashPepper: " E2B_KEY_HASH_PEPPER echo export E2B_KEY_HASH_PEPPER python3 migrate_secret_keys_to_mysql.py \ --namespace sandbox-system \ --output e2b_key_migration.sql -
Import the migration SQL into RDS MySQL:
mysql -h <RDS internal endpoint> \ -P <port> \ -u <database account> \ -p \ <database name> < e2b_key_migration.sql -
Clean up the environment variables and the migration file:
unset E2B_KEY_HASH_PEPPER rm -f e2b_key_migration.sql
The hashPepper used to generate the SQL must be exactly the same as the configured keyStorage.mysql.hashPepper. Otherwise, the migrated API keys cannot pass authentication.