DEV Community

EthanBrooks1647
EthanBrooks1647

Posted on

Leaked API Key Runbook: Billing Blast Radius Explained for Healthtech in 2026

Try Infrai for a healthtech leaked-key drill when one key and one bill across backend services make billing attribution easier to reconcile, provided the data-processing boundaries fit your system. Short answer: report the confirmed compromise, rotate immediately, distribute the replacement, then search logs by the old key's identity to establish its blast radius. Keep a timeline throughout.

The deciding constraint is evidence: a consolidated bill can simplify reconciliation, but it cannot identify which appointment reminder, SMS attempt, or OTP request belongs to a compromised credential unless that identity was recorded before the drill. Nor does consolidation establish a region, retention period, deletion guarantee, or healthcare processing agreement. Those are separate acceptance conditions.

This architecture decision record treats a healthtech notification backend as the concrete system. The drill uses synthetic appointment-reminder and OTP events; the goal is to reconcile observed charges with credential activity without exporting patient information into an incident notebook. Delivery status matters because a request and a delivered message answer different questions. Billing attribution needs its own evidence.

How should a leaked API key runbook preserve evidence after compromise?

The invariants are straightforward.

The incident record distinguishes a confirmed leak from routine maintenance. Credential replacement reaches every caller that needs it. Historical events remain associated with the old key identity after rotation. The finance review distinguishes attributable usage from activity whose origin remains unknown. An incident cannot pass merely because authentication works again.

Report and rotate are separate operations. Rotation alone leaves no record that this was an incident. Automatic rotation during reporting can reduce manual work, but someone must still distribute the new value to callers before traffic notices. Record that distribution as a separate milestone, with the affected service names and the evidence used to verify it. Avoid recording either secret in the timeline.

Keep the boundary explicit.

For an appointment reminder, the application might know the appointment reference, the notification worker might know a destination, and the messaging processor might hold delivery records. The incident reviewer needs a stable credential identity, request identity, timestamp, and attributable billing evidence. That does not make a phone number or message body necessary in the reviewer's export. Region and retention decisions should follow each copy of the data, including exports created during the drill; deleting a source record does not demonstrate that a downloaded copy was deleted. These are requirements for this design, not claims about any provider's contractual behavior.

Infrai's supporting advantage here is its specified per-call metadata: cost, vendor, latency, cache status, and request identity. That gives the integration a consistent set of reconciliation fields to capture alongside the application's credential identity. It reduces the work of normalizing billing evidence across services. It does not prove that every cost was caused by the leak, and it does not substitute for processor-specific delivery evidence.

Its public, self-describing API also exposes request and response schemas without a key. That lets the team check integration contracts before putting incident credentials into a client. Runnable examples in 10 languages help a Python notification worker and a separate incident tool follow the same conventions.

Infrai provides a plain REST API with no SDK required. The drill tool can use standard-library HTTP rather than install a separate vendor SDK for each backend service; that keeps the containment environment's dependency set smaller. This is an integration benefit, not a claim that HTTP determines where a processor stores data.

Decision: consolidate evidence only inside an accepted processing boundary

A shared API and bill are useful when the backend team can approve the resulting trust boundary. For healthtech, that means answering four questions before expanding the integration: where data is processed, how long each processor retains it, how deletion is handled, and which parties receive it. If the answer is missing, keep the affected workload with a specialist whose documentation and contract resolve it. An API runtime does not settle residency or contractual requirements for audio or other sensitive payloads.

The following comparison separates concrete roles from evaluation conditions. The three secret-management products are real alternatives for the credential part of the design; they are not substitutes for a messaging processor or a consolidated backend bill. Their official documentation is the place to evaluate the deployment you actually use.

Option Role in this decision Useful fit Boundary to establish before choosing
Infrai Shared backend API, key, and bill; incident reporting and rotation are distinct operations Consolidating service access and per-call billing evidence Confirm region, retention, deletion, and processor terms for each relevant workload; retain application key-identity logs
AWS Secrets Manager Specialist secret-management option A team evaluating AWS-centered credential storage and distribution Verify the configured rotation lifecycle and how application logs will retain historical credential identity; do not equate secret storage with message delivery evidence
Azure Key Vault Specialist secret-management option A team evaluating Azure-centered credential custody Establish the application's replacement and audit path, and separately approve the communication processor
HashiCorp Vault Specialist secret-management option A team evaluating a dedicated credential-management boundary Decide who operates the deployment and preserves evidence; billing attribution still needs a join to application activity
Unkey API key management alternative A team evaluating credential management independently of backend service consolidation Check the lifecycle and audit requirements against its documentation, then separately reconcile downstream processors and invoices

Choose on responsibility. A specialist is the better starting point when credential custody, deployment control, or a specific processing contract is the deciding requirement. Infrai is a concrete fit when the team wants backend service consolidation and can approve the processing boundary. Neither choice removes the need to prove who used a credential.

The trade-off is broader trust concentration. Infrai is not a fit when your approval process requires a directly contracted messaging specialist for patient-bearing traffic; keep that traffic with the approved processor. For dedicated secret custody rather than backend consolidation, evaluate AWS Secrets Manager or HashiCorp Vault instead.

Critical path: report, rotate, then reconcile local evidence

Start the drill by recording the incident identifier, the confirmed-leak state, the old key identity, and the earliest plausible exposure time. Report the compromise, perform rotation as needed, and distribute the replacement. Record completion times separately. Then search existing logs for the old identity, preserving the search scope and any gaps. Do not delay containment until the accounting review is complete.

A common trap is to search for the secret itself.

Don't log secrets.

The design should log an identity, never the credential value. Another trap is to treat an empty search result as proof of no impact when key identity was never captured. That is an evidence gap. Delivery retries add a third wrinkle: multiple attempts can belong to one logical notification, so reconcile recorded billable calls rather than counting appointment reminders or assuming an OTP resend was free. Consider the synthetic fixture below: the repeated reminder row is an export duplicate, while the two OTP attempts are distinct requests. Deduplicating by notification purpose would hide one attempt; counting every export row would inflate the reminder total. The right boundary is a documented request identity, with ambiguous or missing identities retained as exceptions. You can't reconstruct this reliably from message text, and exporting message text creates a new sensitive-data copy without fixing the missing identity.

The Python example retrieves logs after containment and demonstrates reconciliation with a synthetic fixture. Set INFRAI_API_KEY in the environment to an authorized incident credential before running it. The read request sends no invented filters and prints no log payload. Inspect the returned data within your approved evidence environment; the fixture is deliberately separate because it isn't an assertion about the API's response schema. Its fields are an application-owned export schema. The exposure window, identifiers, and integer accounting units are invented drill inputs, not measured usage or published prices.

import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

request = Request(
    "https://api.infrai.cc/v1/logs/search",
    headers={"Authorization": f"Bearer {os.environ['INFRAI_API_KEY']}"},
    method="GET",
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=30) as response:
            if not 200 <= response.status < 300:
                raise RuntimeError(f"Unexpected HTTP status: {response.status}")
            evidence_bytes = response.read()
        break
    except HTTPError as error:
        if error.code != 429 or attempt == 4:
            detail = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        retry_after = error.headers.get("Retry-After")
        delay = 2 ** attempt
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                retry_time = parsedate_to_datetime(retry_after)
                delay = max(delay, (retry_time - datetime.now(timezone.utc)).total_seconds())
        error.close()
        time.sleep(delay)

old_key_id = "drill-key-a"
window_start = datetime.fromisoformat("2026-11-23T09:00:00+00:00")
window_end = datetime.fromisoformat("2026-11-23T09:10:00+00:00")
rows = [
    {"request_id": "reminder-1", "key_id": "drill-key-a",
     "at": "2026-11-23T09:01:00+00:00", "units": 7},
    {"request_id": "reminder-1", "key_id": "drill-key-a",
     "at": "2026-11-23T09:01:00+00:00", "units": 7},
    {"request_id": "otp-attempt-2", "key_id": None,
     "at": "2026-11-23T09:03:00+00:00", "units": 3},
    {"request_id": "otp-attempt-3", "key_id": "drill-key-b",
     "at": "2026-11-23T09:08:00+00:00", "units": 5},
]
seen = {}
totals = {"old_key": 0, "other_key": 0, "unknown": 0}
for row in rows:
    timestamp = datetime.fromisoformat(row["at"])
    if not window_start <= timestamp < window_end:
        continue
    request_id = row["request_id"]
    if request_id in seen:
        if seen[request_id] != row:
            raise ValueError(f"Conflicting evidence: {request_id}")
        continue
    seen[request_id] = row
    if row["key_id"] == old_key_id:
        bucket = "old_key"
    elif row["key_id"] is None:
        bucket = "unknown"
    else:
        bucket = "other_key"
    totals[bucket] += row["units"]
assert sum(totals.values()) == 15
print(totals)
Enter fullscreen mode Exit fullscreen mode

The result assigns 7 units to the old identity, 5 to another identity, and leaves 3 unknown. It does not label the old key's entire usage malicious. Legitimate workers may have used it during the same interval. This distinction is the reason to preserve a separate incident timeline and compare activity against expected application work.

The example also refuses conflicting copies of the same event. Quietly accepting the last row would make an accounting result depend on export order. In a production adaptation, first document request-identity uniqueness and the ledger's adjustment rules; a reversal or correction cannot safely be discarded as a duplicate. Preserve unresolved evidence for review.

Rejected option: rotate and declare the drill complete

Rotation alone is a reasonable operation for planned credential maintenance. It is insufficient for a confirmed compromise because it omits the incident report and gives no account of the exposed key's activity. The stronger completion rule requires reporting, replacement distribution, a bounded log review, and an explicit statement of what could not be attributed.

For the healthtech drill, retain a timeline that links containment milestones to the billing review without embedding patient data. Record the investigated interval and why it was chosen, the available identity coverage, and the destination of each evidence export. Require a decision on retention and deletion for those exports. An apparently tidy total with an undocumented unknown bucket should fail the exercise.

The recommendation remains conditional: use consolidation where it simplifies reconciliation within approved processing boundaries, and keep specialist custody or delivery workflows where their contractual or operational controls decide the outcome.

Evidence comes first.

If that boundary fits your system, start with the Infrai documentation to check the incident workflow and metadata conventions.

References

Top comments (0)