API Key Management for LLM APIs: Application, Security, and Rotation Practices

    This article explains how to treat LLM API keys as managed infrastructure rather than plain strings. It covers account and role prerequisites before applying for a key, the one-time display behavior of the secret portion and how to store it safely, separating test and production credentials with matching network and data boundaries, enforcing least privilege through identity and access policies, running a 90-day rotation as a dual-key gradual process, recognizing leak signals and handling incidents, and folding credential governance into daily engineering standards. Readers will find practical steps, policy and environment-variable examples, and a short implementation checklist.

    1. Why API Keys Should Be Treated as Infrastructure

    When integrating large model capabilities, the API key is the only credential that spans three dimensions at once: identity, permission, and metering. It proves who the caller is, determines which capabilities a given call can reach, and serves as the basis for the platform to attribute usage and billing. Many production incidents are not model quality problems at all. A key gets hardcoded into a code repository, ends up in a frontend build artifact, or is copied into third-party logs, and the result is exhausted quota or unexpected charges.

    So the goal of key management is not “obtain a string.” It is to establish a credential lifecycle that is auditable, revocable, and minimal. The common approach on cloud platforms such as Baidu AI Cloud is to combine key management with the identity and permission system, monitoring and alerting, and logging services, instead of guarding a string in isolation.

    2. Before You Apply: Identity Verification and the Account Model

    Key issuance is normally bound to an account that has completed identity verification. The point of this step is clear accountability: calls can be traced back to an entity, and there is evidence to rely on if abuse occurs. In practice, teams should settle three things first:

    • Decide whether the account entity is an individual or an organization. An organization entity makes multi-member collaboration and permission tiering easier later.
    • Plan the hierarchy of accounts and projects (or resource directories), placing different business lines under different projects so quotas and permissions do not contaminate each other.
    • Define member roles, at minimum distinguishing administrator, developer, and read-only auditor.

    One point deserves emphasis: a key should not be held by a personal account over the long term. When people move on, personal credentials are often revoked late, leaving behind long-lived “shadow permissions.”

    3. Creating a Key: One-Time Display and Storage Strategy

    When you create a credential in the console’s key management section, the system generally generates an identifier part and a secret part. The former identifies which key it is; the latter performs the actual signature verification. The secret part is typically shown in full only once, in the successful creation response. Once the page is closed it cannot be viewed again, and the only option is to regenerate.

    This means the save action must be completed inside the creation flow. Workable engineering practices:

    1. Write the key into a key management service or a controlled secret storage tool immediately after creation, rather than first noting it in a scratchpad, a chat window, or personal notes.
    2. If you use a configuration center, inject by reference rather than in plaintext, so only the reference key appears in code.
    3. Fill in metadata on the key: purpose, owner, owning service, and expiration time, to support later auditing and rotation.
    4. Allow plaintext only in runtime memory and controlled storage media. Keep it out of code repositories, image layers, and frontend artifacts.

    Illustrative environment variable injection (expressing the reference relationship only, with no real credential):

    1. export LLM_ENDPOINT="https://<your-endpoint>"
    2. export LLM_API_KEY="<resolved-from-secret-manager>"
    1. import os
    2. def call_model(payload: dict):
    3. key = os.environ["LLM_API_KEY"] # injected at runtime by the secret management service
    4. if not key:
    5. raise RuntimeError("credential missing")
    6. # use the key to sign and issue the request
    7. return {"status": "ok", "echo": payload}

    4. Isolating Test and Production Keys

    Splitting credentials by environment into a test set and a production set pays off on both cost and security. Test credentials suit daily integration work: they have a lower call-rate ceiling and a shorter validity period, and they expire automatically, which naturally limits the risk of long-term exposure. Production credentials should go through a stricter application process that states the use case, expected call volume, data flow, and compliance requirements, with quota released only after approval.

    The key to isolation is not just “two keys” but the accompanying network and data boundaries:

    • Test environments use masked or synthetic data and must not connect real user personal information.
    • Production credentials work only inside the production network, and egress address restrictions reduce their usable range if stolen.
    • Set quota and alert thresholds separately for the two sets, so load testing does not exhaust the production quota.
    • Break out metrics by credential identifier in monitoring and alerting, so abnormal growth can be traced quickly to a specific environment.

    5. Least Privilege: Enforce It with Policies, Not Good Intentions

    Fine-grained control means narrowing “what can be called” from the account level down to the credential level. The common approach is to use identity and access management policies to constrain the resource scope that can be reached, the actions allowed, and the network conditions under which they take effect, following three principles:

    • Authorize on demand: grant only the model capabilities and resource scope the business actually needs, never a wildcard scope.
    • Separate duties: key creation, policy changes, and audit review are assigned to different roles, avoiding a single point of full control.
    • Stay revocable: any key must be disableable immediately without rebuilding the whole system.

    Illustrative policy structure (pseudocode, expressing constraint dimensions rather than a specific interface):

    1. allow:
    2. actions: [invoke-model, list-model]
    3. resource: project/prod-chat/*
    4. condition:
    5. source_network: corporate-egress
    6. time_window: business-hours
    7. deny:
    8. actions: [create-key, update-policy]

    6. Rotation: Turning 90 Days into an Executable Process

    “Rotate regularly” is almost always postponed if it is not automated. Set the rotation cycle to within 90 days and run it as a gradual process with two keys in parallel:

    1. On day T, create the new key while the old one stays valid.
    2. Use hot configuration updates to shift traffic gradually to the new key, watching error rates and throttling metrics.
    3. After a stable observation window, disable the old key, then observe for a while longer to confirm no residual calls.
    4. Archive the rotation record, including the operator, affected services, and verification conclusion.

    Before rotating, confirm in the logging service “who is calling,” so an unknown hardcoded call site does not cause widespread failures after the switch.

    7. Detecting Leaks and Emergency Response

    Common leak signals include a sudden rise in call volume with no release activity, abnormal distribution of source addresses, error codes concentrated on authentication failures and quota overruns, and unfamiliar project attribution on the bill. The recommended response is fixed at four steps: immediately disable or downgrade the credential involved; trace the call scope in logs and determine whether data exfiltration occurred; replace the key and check whether references to the old credential remain; and fill the detection gaps, for example scanning code repositories for credentials and checking images and build artifacts for sensitive information.

    8. Making Credential Governance Part of Daily Engineering Standards

    Mature teams operate keys as service objects with a lifecycle: application follows a process, usage has boundaries, changes are recorded, and revocation is verified. The implementation checklist reduces to this: no plaintext in the repository, permissions separated by environment, policies minimized, rotation within 90 days, alerts on abnormal usage, and revocation synchronized with departures and role changes. With these in place, the engineering path for calling large model capabilities has a security foundation that can run sustainably.