Leaked API Keys and Runaway Inference Bills: Preventing Uncontrolled Model Costs
A leaked client-side key can turn into a runaway inference bill when a project’s capability boundary changes. This article examines a reported case, explains permission drift and why budget alerts are not hard limits, and outlines practical controls for server-side credentials, layered quotas, budget circuit breaking, and incident response.
1. How Did a Feature Test Become a Cost Incident?
Adding intelligent features to an existing application may look like simply enabling a service and running a few tests. But if the project already contains an old key that is publicly distributed and lacks restrictions, that change can alter the security boundary of the entire project.
In the referenced material, an independent developer runs an education app. He states that after enabling a model inference service in the existing project, an old key previously embedded in the client was abused by others, ultimately producing a bill of approximately $15,400 (about RMB 106,000). The original title also notes that he deleted the old key about 10 minutes after discovering the problem, while billing display lagged by about 30 hours.
These times and amounts are the individual’s statements. They should not be used to determine the attack method, platform responsibility, or the timing of each charge. In particular, distinguish this point: a new bill appearing after a key is deleted does not necessarily mean new requests were successfully executed after deletion; it may also reflect delayed accounting for earlier usage.
Still, the case reveals a common problem: what a developer considers a “client-side configuration that can be public” and the “paid services” the system actually allows it to call may not sit within the same security boundary.
2. Root Cause: The Capability Boundary Changed, Not the Key Itself
2.1 Public Identifiers and Access Credentials Are Not the Same
Some keys in client-side configurations mainly serve project identification, request routing, and similar roles. In that case, real access control may depend on user authentication, resource authorization rules, or application origin restrictions rather than key secrecy.
This does not mean all API keys can be made public, and it certainly does not mean the same key always has the same capabilities throughout a project’s lifecycle.
To assess key risk, answer three questions:
- With only this key, can a caller successfully invoke the service?
- Can it read or modify sensitive resources, or consume paid quota?
- Does the server also verify user identity, resource permissions, and invocation origin?
If possession of the key alone can generate charges, then it is an access credential that requires strict protection. Even if it was previously used in a public-facing scenario, the old assumptions should not continue to apply.
2.2 Enabling a New Service Can Expand an Old Key’s Reach
In systems that enable services at the project level and whose keys lack service restrictions, an old key may gain new callable capabilities after a new API goes live. The specific outcome depends on the platform’s authorization model and cannot be generalized.
Therefore, risk review should not only check “whether the newly created key is secure.” It should also ask:
Which existing credentials in the project will gain additional capabilities because of this change?
This is permission drift: the credential itself has not changed, but the services, resources, or billing capabilities it can reach have changed.
A pre-launch checklist should include, at minimum, the scope of service enablement, an inventory of old keys, where keys are located, invocation restrictions, billing status, and the impact scope after deactivation.
2.3 Client Code Is Not a Secret Store
Credentials in browser scripts, mobile app packages, desktop programs, and public examples can all be extracted. Code minification, string splitting, or simple obfuscation only raises the cost of extraction; it does not create a reliable security boundary.
If an interface must rely on secret credentials, those credentials should be held by a controlled server. If the business genuinely requires direct client access, it must use a restricted authorization mechanism supported by the service and confirm its security properties, rather than assuming that “if it is hidden deeply enough, it will not leak.”
3. Why Budget Alerts Cannot Replace Hard Limits
3.1 Alerts Are Notification Mechanisms, Not Necessarily Blocking Mechanisms
“Setting a budget to a certain amount” may only mean that a notification is sent when costs reach a threshold. It does not mean all requests will automatically stop.
It is important to distinguish four types of controls:
- Budget alerts: notify when costs reach a threshold, usually depending on cost data updates.
- Rate limits: limit request volume or other resource usage per unit of time.
- Concurrency limits: limit the number of requests executing at the same time.
- Business budget controls: the application decides whether to accept new requests based on remaining budget.
Only controls with explicit blocking behavior can directly limit subsequent consumption. Even if a platform provides automatic deactivation, teams should verify the trigger conditions, coverage, data delay, and execution delay.
3.2 Slow Billing Updates Widen the Invisible Risk Window
Cost display usually goes through usage collection, aggregation, pricing, and presentation. It is not necessarily synchronized with request execution.
In a simplified scenario with a relatively stable average cost, the risk can be understood with the following relationship:
Approximate cost during the risk window ≈ successful request rate × average request cost × time without effective blocking
This is not a precise billing formula. Model type, input and output length, cache hits, and handling of failed requests can all affect actual cost. Its value is in showing that if calls are already out of control, even a relatively short discovery or blocking delay can accumulate significant losses.
Therefore, cost alerts are suitable for financial monitoring but not for serving as the sole real-time security line.
3.3 Real-Time Monitoring Should Sit Closer to the Call Path
More timely anomaly signals include sudden spikes in request volume, abnormal concurrency, sharp increases in input and output volume, unfamiliar invocation sources, concentrated exhaustion of user quotas, and abnormal changes in the proportion of successful requests.
These signals should be collected from the server or a controlled gateway, rather than relying only on client reporting. Clients can be bypassed and can also be forged.
4. Building a Controllable Model Invocation Architecture
For applications that need to protect paid credentials, the following general structure can be used:
Client → Business Service → Identity and Quota Checks → Model Inference Service
The business service should not only forward requests. It should also enforce cost control and centralize permissions.
4.1 Keep Secret Credentials on the Server
Credentials should be stored in controlled configuration or secret management facilities, with restricted read permissions and a rotation mechanism. Do not write them into frontend build artifacts, public repositories, exception logs, or shared documents.
When logs need to record credential identifiers for auditing, use redacted identifiers or irreversible fingerprints rather than full keys.
4.2 The Proxy Entry Point Needs Its Own Security Controls
Moving a key to the server does not make the risk disappear. If the proxy interface allows anonymous, unlimited calls, attackers can still consume budget through the proxy.
The business entry point should at least verify user identity, check user and tenant quotas, and limit request body size, maximum output, and concurrency. For high-cost operations, require additional confirmation or make them available only to accounts that meet certain conditions.
4.3 Use Layered Quotas Instead of a Single Master Switch
It is advisable to set user-level, tenant-level, and project-level controls at the same time:
- User-level quotas limit abuse by a single account.
- Tenant-level quotas prevent one business space from consuming the overall budget.
- Project-level quotas protect the final financial boundary.
- Request-level limits prevent a single call from becoming too expensive.
These limits should cover different time windows. Minute-level limits suppress burst traffic, while daily or monthly quotas constrain cumulative consumption.
4.4 Separate Test and Production Environments
When testing a new service, prefer an independent project and independent credentials, configure lower quotas, and avoid binding an excessively large available budget.
The value of environment isolation is not only reducing operational mistakes. It also limits the impact scope after a credential leak. A runaway test key should not simultaneously affect authentication, storage, and inference services in the production application.
5. How to Implement Application-Side Budget Circuit Breaking
Budget control can follow a “reserve quota—execute request—settle based on actual usage” approach:
Receive requestVerify user identity and business permissionsCalculate a conservative upper bound on the cost of this requestAtomically check and reserve user, tenant, and project quotaReject the request if quota is insufficientExecute the inference callRecord actual usage and update settlement statusRelease unused reserved quota
This flow is an architectural illustration and does not correspond to any specific product interface.
Several details are easy to overlook during implementation.
First, budget checks and quota reservation must be atomic. If multiple concurrent requests each read “there is still balance” and then execute together, they may exceed the budget.
Second, cost estimation must have constraint foundations. For example, limit maximum input size, maximum output, and the categories of services that can be called. When an upper bound cannot be estimated reliably, use more conservative quota reservation and keep a safety margin.
Third, a network timeout does not mean the remote side did not execute. For requests with unknown outcomes, do not immediately release all quota and automatically retry, or duplicate consumption may occur. Store request state and reconcile it later with usage records.
Finally, when budget storage or the quota service is unavailable, high-cost requests should use a conservative rejection or degraded strategy. A control-system failure must not become a reason to fall back to unlimited calls.
6. After a Leak Is Discovered: Stop the Bleeding and Preserve Evidence
Phase 1: Immediately Cut Off the Consumption Path
After discovering an anomaly, first deactivate suspicious keys and check whether other credentials have been exposed. If necessary, pause the relevant paid services, close business entry points, or tighten project quotas.
After taking action, verify the blocking effect: can the old key still successfully call the service, can the proxy entry point still be abused, and are there long-running tasks still executing? Do not end the response simply because the console shows “deleted.”
Phase 2: Rebuild the Incident Timeline
Record when the anomaly first occurred, when it was first discovered, when the key was deactivated, changes in call success rates, and when billing was updated.
When analyzing costs, distinguish among:
- When requests actually occurred;
- When usage entered the statistics system;
- When costs were displayed or billed.
This avoids mistaking delayed display of historical usage for an ongoing attack and helps determine whether blocking actually failed.
Phase 3: Preserve Materials and Submit for Review
Retain request statistics, redacted logs, configuration change records, alert information, and billing details. When submitting the situation to the service provider, focus on abnormal invocation patterns, the scope of credential exposure, and the loss-control measures taken.
Whether a billing adjustment is supported depends on specific rules and review results; a reduction is not guaranteed. Technical teams should first complete loss control and evidence organization, then handle billing disputes.
7. What Really Needs Fixing Is the Security Boundary
This type of incident should not be reduced to “the developer was careless,” nor should a definite platform defect be concluded from a one-sided statement alone. The more valuable conclusion is this: when a project’s capabilities change, the permissions and cost boundaries of existing credentials must be reviewed again.
Before launching model features, complete at least the following checks:
- Inventory publicly distributed old keys and the services they can call.
- Create independent, least-privilege credentials for paid capabilities.
- Clarify the difference between budget alerts and actual blocking mechanisms.
- Deploy identity verification, rate limiting, and quota controls along the call path.
- Verify whether key deactivation, service suspension, and budget circuit breaking actually work.
- Regularly reconcile internal usage with billing and investigate deviations promptly.
For independent developers, security designs can be lightweight, but cost boundaries cannot be missing. For enterprises, key governance, service changes, and cost control should be part of the same launch process. Reliable protection does not depend on hoping that an abnormal bill appears quickly; it depends on making abnormal calls lose the opportunity to continue consuming resources before the bill appears.
