Use RDS MySQL to store API keys

Updated at:

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 hashPepper.

Storage location

sandbox-system namespace: the Kubernetes Secret e2b-key-store.

An external MySQL database.

Key storage format

Stores the original API key in a recoverable form.

Stores only the HMAC-SHA256(pepper, rawKey) hash and does not retain the original key.

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.

RDS MySQL selection recommendations

Configuration item

Recommendation

Instance edition

Use High-availability Edition for production environments. You can use Basic Edition for development and testing environments.

Database version

MySQL 8.0 is recommended. The minimum supported version is MySQL 5.7.

Instance type

Start with an instance type of 1 core and 2 GB. If the number of tenants or the concurrency is high, select 2 cores and 4 GB or higher.

Storage

Select an Enhanced SSD (ESSD) and the minimum storage capacity supported on the purchase page. Expand the capacity later as needed.

Network

(Recommended) Deploy the instance in the same region and the same VPC as the Container Compute Service cluster.

Billing method

Select Subscription for long-term use and Pay-As-You-Go for short-term testing.

The available instance types and storage capacity vary by region, zone, and instance edition. Refer to the purchase page for the actual options.
  1. 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.

  2. 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.

    1. Create a database, for example, e2b.

    2. Create a standard database account and record the account name and password.

    3. Grant the account the Read/Write (DDL + DML) permission on the target database.

  3. Configure an IP address whitelist.

    sandbox-manager and 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.
    1. Log on to the Container Compute Service console and go to the Basic Information page of the target cluster.

    2. In the Network section, on the right side of Control Plane vSwitch, click Edit and copy the CIDR blocks of all selected vSwitches.

    3. Log on to the RDS console and go to the Whitelist and SecGroup page of the target instance.

    4. Modify the default whitelist group and add the IPv4 CIDR blocks of the control plane vSwitch to the whitelist of that group.

  4. 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
  5. 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.sql

    The script creates the teams and team_api_keys tables and initializes the built-in admin Team. The hash of the admin API key does not need to be migrated. When ack-sandbox-manager starts, it automatically computes the hash based on the current hashPepper and writes the hash to team_api_keys.

Configure the MySQL storage backend

  1. Log on to the Container Compute Service console and go to the target cluster.

  2. On the Add-ons page, find ack-sandbox-manager and click Configuration.

  3. Configure the following parameters:

    Configuration item

    Value or description

    keyStorage.mode

    Set this parameter to mysql.

    keyStorage.mysql.dsn

    The 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.hashPepper

    The long-term secret used to compute the API key hash.

  4. Specify the DSN in the following format:

    <account>:<password>@tcp(<RDS internal endpoint>:<port>)/<database name>?charset=utf8mb4&parseTime=true&loc=Local

    Example:

    e2b_user:********@tcp(rm-******************.mysql.rds.aliyuncs.com:3306)/e2b?charset=utf8mb4&parseTime=true&loc=Local

    Generate a random 32-byte (256-bit) string as the hashPepper.

    openssl rand -hex 32

    The command outputs 64 hexadecimal characters, which you can use directly as the value of keyStorage.mysql.hashPepper.

    Important

    Store hashPepper securely 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.

  5. Save the configuration. ack-sandbox-manager automatically restarts and connects to RDS MySQL.

    When keyStorage.mode is set to mysql, the component fails to start if the DSN or hashPepper is not configured.

Verify the configuration

  1. Confirm that the ack-sandbox-manager Pod is running properly:

    kubectl get pods -n sandbox-system -l component=sandbox-manager

    Expected 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
  2. 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 of ack-sandbox-gateway.

    • ADMIN_KEY: the admin API key configured for ack-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 kubectl to read the e2b-key-store Secret.

  • 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.

Important

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.

  1. Validate the Secret data:

    python3 migrate_secret_keys_to_mysql.py \
      --namespace sandbox-system \
      --dry-run

    This command parses all entries in the Secret and validates fields such as id, name, and key. 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.

  2. Set hashPepper by entering it at a hidden prompt (the value must be exactly the same as the configured keyStorage.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
  3. Import the migration SQL into RDS MySQL:

    mysql -h <RDS internal endpoint> \
      -P <port> \
      -u <database account> \
      -p \
      <database name> < e2b_key_migration.sql
  4. Clean up the environment variables and the migration file:

    unset E2B_KEY_HASH_PEPPER
    rm -f e2b_key_migration.sql
Important

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.

Common parameters of the migration script

Parameter

Description

Default value

--namespace

The Kubernetes namespace that contains the e2b-key-store Secret. This parameter is required.

None

--secret-name

The name of the Secret.

e2b-key-store

--pepper

hashPepper value. If this parameter is not specified, the E2B_KEY_HASH_PEPPER environment variable is read.

None

--output

The output SQL file. If this parameter is set to -, the output is written to standard output.

e2b_key_migration.sql

--dry-run

Only validates the Secret data and does not generate SQL.

false