Skip to main content

API key leak prevention best practices

Prevent API key leaks by shortening credential exposure, narrowing permissions, and configuring alerts with loss mitigation, covering temporary API keys, regular rotation, IP whitelists, private connections, budget alerts, and model monitoring alerts.

Overview

An API key is the credential used to call Alibaba Cloud Model Studio model services. Once leaked, anyone who obtains it can call the models within the key's authorization scope and consume your quota. The impact of a leak can be broken down into four factors: leak probability, exposure time, permission scope per call, and how long the anomaly lasts. Leak probability is compressed by the foundation practices throughout this page, and the other three factors are compressed by the following three layers respectively:

Layer

Factor compressed

Key measures

Shorten exposure time

Exposure time

Temporary API keys for clients, one-time display with controlled storage, regular rotation and revocation on departure

Narrow permission scope

Permission scope per call

One key per business, workspace isolation, IP whitelist and model scope, private connections

Alerts and loss mitigation

How long the anomaly lasts

Budget alerts with auto-stop, model monitoring alerts, platform risk detection

Foundation practices that apply across all three layers:
  • Applications read credentials from environment variables or a key management service instead of hard-coding them; configure sensitive information scanning in CI/CD (with credential scanning tools such as gitleaks), covering API key patterns.
  • Maintain a key ledger: start with a basic table of key IDs, purposes, owners, and last rotation dates, then gradually add regions, workspaces, permission scopes, and budgets; never store complete keys in the ledger.
  • Restrict key management permissions (create, view, edit, delete) to the administrators who need them.

Shorten the credential exposure time

Store long-term API keys securely

A newly created API key is displayed in full only once at creation; after you close the dialog, the plaintext can no longer be viewed or copied. If you did not save it, you can only reset or recreate the key. See Obtain an API key. After creation, store the complete key directly in a controlled credential store (a key management service or the secret management of your deployment platform) instead of relaying it through screenshots, emails, chat tools, or ordinary documents; the masked value in the list is only for identification and comparison. Never place long-term API keys in the following locations:
  • Browser scripts, frontend build artifacts, and mobile app packages
  • Public or shared code repositories (adding .gitignore alone does not remove credentials from historical commits)
  • Notebook outputs and sample code
  • Screenshots and screen recordings
  • Tickets, group chats, and online documents
  • Prompts, knowledge bases, and agent contexts
  • Request URLs and query parameters
  • Access logs and exception stacks
  • Third-party plug-ins and model relay services (services that forward your model calls)
  • Shared environments and externally exposed configuration files, images, and backups
For local debugging, set the environment variable with hidden input to avoid leaving plaintext in the command history:
read -r -s -p "Enter API key: " DASHSCOPE_API_KEY
printf '\n'
export DASHSCOPE_API_KEY
This example applies to Linux/macOS.
Environment variables avoid hard-coding but are not encrypted storage: credentials can still leak through process diagnostics, container configurations, crash dumps, or ops exports; avoid options such as set -x that print sensitive variables during debugging. For production, use a key management service or secret injection from your deployment platform.
If you have provided an API key to an untrusted model relay service or third-party plug-in, stop delivering new keys to it, switch to the official API or trusted server-side integration, and rotate the keys already delivered.

Use temporary API keys in client-side scenarios

Browsers, mobile apps, and mini programs cannot keep credentials reliably confidential. In these scenarios, have an authenticated backend issue temporary API keys for the frontend to call directly:
  1. Keep the long-term API key only on your own server and never deliver it to any client.
  2. When the frontend needs to call a model, request a temporary key from your backend first.
  3. The backend calls the temporary API key generation API and returns a short-lived st- key to the frontend.
  4. The frontend calls Model Studio directly with the st- key.
A temporary API key is valid for 60 seconds by default; you can set 1 to 1800 seconds via expire_in_seconds (set the shortest duration the task needs, and do not use the maximum unconditionally). It expires automatically and cannot be deleted in advance; it inherits all permissions of the long-term API key that issued it, so narrow the issuing key first when fewer permissions are needed. The issuing API is called over OpenAPI with the long-term key; validate caller permissions and rate-limit issuance to avoid turning it into a public credential dispenser. For API details, see Generate a temporary API key.

Rotate keys regularly and revoke them on departure

Long-lived keys configured in code or agents accumulate exposure over time and should be rotated regularly:
  1. Create a new key and reconfigure its permissions and budget for current needs.
  2. Update credential references in your business services.
  3. Verify that the new key works.
  4. Delete the old key and confirm it can no longer initiate calls.
  5. Update the key ledger.
A new key does not automatically inherit the permissions and budget of the old one; reconfigure them. When personnel leave or a business is decommissioned, you must separately inventory, delete, or rotate their keys: API keys created on or after March 25, 2026 are not deleted along with their RAM user and remain usable (relevant only when the key belongs to a RAM sub-account), so a deleted RAM user does not mean the credentials are revoked. See Validity and limits. If multiple keys are stored in the same compromised server, public configuration, code repository, or third-party environment, rotate all potentially affected credentials and fix the environment: neither replace all keys indiscriminately nor handle only one key while ignoring the shared exposure. Advanced practice: host key plaintext in a key management service (KMS), have applications retrieve it by credential name, and use KMS key rotation to update it periodically.

Narrow the credential permission scope

One key per business and workspace isolation

Assign independent API keys to different applications and environments (production, testing, and personal debugging): this shrinks the impact of a single key leak and makes it easier to trace issues and rotate keys per key. When you need permission isolation, fine-grained model access control, or independent cost accounting, assign a non-default workspace to the business (a workspace is a container in Model Studio that isolates permissions and costs; every account has a default workspace by default); the base calling scope of a key is constrained by its workspace. See Permission management. Also restrict key management permissions to the necessary administrators; accounts that can log in to the console to manage credentials should follow least privilege and enable multi-factor authentication as required by your organization.

Configure the IP whitelist and model scope

After setting the permission of an API key to Custom in the key creation or edit panel, you can further narrow its calling scope:
  • IP whitelist: allow only the public egress IPs or CIDR blocks actually used by the business, up to 20 entries (use a service such as curl ifconfig.me to find your public egress). All IPv4 addresses are allowed by default; creating a key alone does not mean source restrictions are in effect. When calling through NAT, a proxy, or a gateway, enter the public egress address that Model Studio actually sees, not the intranet address of the server.
  • Model scope: once enabled, the key can only call the selected models (up to 30, constrained by the models authorized in the workspace), preventing leaks from being used for high-cost models.
After configuration, verify that the narrowed scope works: only allowed networks and models can be called and unauthorized ones cannot; do not print the complete key during verification. For the entry point and complete rules, see How do I manage the permissions of an API key.
An IP whitelist cannot replace credential confidentiality: people or compromised hosts that can initiate calls from the same egress network can still misuse a leaked key.

Call through a private connection

For scenarios with high network security requirements, you can establish a private connection (PrivateLink) between your VPC and Model Studio: calls bypass the public network, so external attackers whose networks are not connected cannot call the service even if the key leaks. For configuration, see Access Model Studio APIs over a private network.

Configure alerts and loss mitigation

Budget alerts and auto-stop

Set monthly budgets and alert thresholds for the account, a workspace, or a single API key; prioritize independent budgets for high-risk keys such as development, testing, demos, and third-party integrations. When spending reaches the threshold and when the budget is exhausted, notifications are sent via in-site messages, SMS, email, or bots; after enabling stop on budget exhaustion, the service restricts pay-as-you-go calls for that dimension and returns 429. For configuration, see Budget management.
Stop on budget exhaustion takes effect with a delay, and charges incurred during the delay are still billed; calls from pre-provisioned throughput (PTU) overflow and applications are not yet supported for automatic stop. For production-critical businesses, do not enable automatic stop; prefer alerts plus controlled handling.

Model monitoring alerts

Model monitoring aggregates call counts, token usage, failure counts, and failure rates per workspace, supports filtering by API key, and lets you create alert rules from preset or custom alert templates that notify contacts or contact groups. Configure call-volume or call-count surge alerts for high-risk keys: anomalies become visible within minutes after the calls occur, and off-hours triggers call for manual intervention. First-time alert configuration requires authorizing the Cloud Monitor service role under data delivery; for configuration, see Alerts.

Platform risk detection

The platform periodically scans public environments such as public code repositories to identify leaked API keys and proactively notifies you; the actual channels depend on what is enabled (which may include SMS, email, and in-site messages). It also identifies anomalous behavior such as logins from unfamiliar IPs, off-hours traffic spikes, and abnormal cost surges.
Platform alerts are a supplementary signal for leak detection; identification and delivery take time, and they cannot replace the budget and monitoring alerts you configure yourself. When you receive an alert, locate and handle the issue following API key leak investigation.

Pre-launch checklist

Individual developers and small teams can start with the minimum: set a budget with alert notifications for the key, keep the credential only in environment variables, and rotate it regularly. The full checklist is as follows:
  • Production, testing, and third-party integrations do not share the same API key; key owners and purposes are clear.
  • Region, workspace, model scope, and request egress IPs are verified, with permissions covering only the necessary scope.
  • Long-term keys are stored only in controlled backends and never enter clients, source code, prompts, shared documents, or logs.
  • Keys have not been delivered to untrusted third-party relay services or plug-in environments; if they were, delivery has stopped and keys have been rotated.
  • Credentials are injected through environment variables or secrets; sensitive files and build artifacts contain no plaintext.
  • Client-direct scenarios use short-term keys issued by an authenticated backend, and the issuing long-term key has narrowed permissions.
  • New keys are stored under control; old keys, idle keys, and keys of departed personnel have been reviewed.
  • Budgets and alerts at the account, workspace, and key levels are configured, with notification channels and owners clarified.
  • The availability impact and effective delay of stop on budget exhaustion have been evaluated.
  • Rotation and leak response procedures are defined; investigation steps are described in API key leak investigation.

FAQ

No. A temporary API key inherits all permissions of the long-term API key that issued it; only its validity period is shorter. To get fewer permissions, narrow the issuing long-term API key first.
Yes. An IP whitelist only restricts the source network of calls; a key leaked within the same egress network can still be misused. Combine it with least privilege, budget alerts, and regular rotation.
Stop delivering new keys to that service, rotate the delivered keys, and switch to the official API or trusted server-side integration. For handling leaked keys, see API key leak investigation.