B2BB2B LLM
Wgląd w biznes

Jak zbudować klienta idempotentnego API Udostępnianie kluczy dla partnera LLM API

Neutralny dla dostawcy projekt umożliwiający bezpieczne tworzenie kluczy LLM API dostosowanych do klienta, obejmujący żądania idempotentne, jednorazowe tajne oświadczenia, asynchroniczne udostępnianie, rotację, unieważnianie i uzgadnianie.

Creating a customer API key is not a simple database insert. The operation may need to validate tenant policy, configure scopes and budgets, create downstream resources, generate a secret, and deliver that secret exactly once. If the client times out after the operation succeeds, blindly retrying can create a second active key. Refusing the retry can be just as bad: the first secret may now be permanently unavailable.

The safe design is a durable provisioning workflow. Creation establishes the credential resource and an operation record; a separate claim step delivers the secret. Every transition is idempotent, tenant-scoped, auditable, and recoverable through reconciliation.

The lost-response problem

Consider a reseller provisioning an LLM API key for customer cust_742:

  1. The reseller sends a create request.
  2. The platform commits the credential and generates its secret.
  3. The response is lost because the connection times out.
  4. The reseller retries without knowing whether creation succeeded.

A conventional POST endpoint may create another key. A strict one-time-display endpoint may return only redacted metadata, leaving the original secret unusable. This conflict between retry safety and one-time disclosure is the central design problem in customer API key provisioning for LLM platforms.

Established credential APIs demonstrate several relevant facts: full secret values are commonly available only at creation; some provisioning calls complete asynchronously; and safe rotation can require two versions to remain valid temporarily. The architecture below turns those constraints into a provider-neutral contract. The state model and claim pattern are recommendations, not claims that every provider implements them.

Model credentials, operations, and secret delivery separately

Use three related resources rather than one overloaded key record:

  • Credential: the durable customer-owned identity, including tenant, scopes, environment, expiration, version, status, and public key identifier.
  • Operation: the progress and outcome of a create, rotate, or revoke request.
  • Claim: a short-lived capability used to retrieve a newly issued secret under tightly controlled conditions.

This separation lets the platform finish policy and downstream work before exposing usable credentials. It also lets a client inspect an operation without receiving secret material in status responses.

Store an identifier and digest, not a recoverable key

Format the presented key as a public identifier plus a random secret, for example:

llm_live_kid_7F3A.q9mJ...random-secret...

Use the identifier to locate the credential record, then authenticate by comparing a keyed digest of the supplied secret in constant time. Store metadata such as tenant_id, environment, scope_set, expires_at, version, and status separately. Do not store raw provider credentials in customer-facing records or expose provider-specific identifiers in public responses.

A keyed digest protects against offline testing if the credential table is copied, provided the digest key is held outside that database. If secret replay is supported for a short period, keep the recoverable ciphertext in a separate secret-delivery store encrypted under a dedicated key-encryption key.

Make creation idempotent at the tenant boundary

Require an idempotency key on every create and rotation request. Its uniqueness boundary should include:

partner_identity + tenant_id + endpoint + idempotency_key

Persist a canonical hash of all behavior-changing inputs, including scopes, environment, expiration, customer reference, budgets, and key restrictions. A retry with the same idempotency key and the same hash returns the existing operation. Reusing the key with different inputs returns a conflict.

POST /v1/tenants/tn_742/credentials
Idempotency-Key: onboard-order-9918

{
  "customer_reference": "account-8841",
  "environment": "production",
  "scopes": ["llm.responses:create"],
  "expires_at": "2027-01-31T00:00:00Z"
}

A suitable initial response is:

HTTP/1.1 202 Accepted
Location: /v1/operations/op_01J...

{
  "operation_id": "op_01J...",
  "credential_id": "cred_01J...",
  "status": "provisioning"
}

Insert the idempotency record, credential placeholder, operation, and first audit event in one transaction. Enforce uniqueness in the database; an application-level check alone does not prevent two concurrent workers from creating duplicates.

Use an explicit lifecycle state machine

A practical state model is:

requested -> provisioning -> claimable -> active
                         \-> failed
active -> rotation_pending -> active
active -> revoking -> revoked
claimable -> expired

Each transition should have an allowed source state, actor, timestamp, reason, and monotonically increasing version. Write the new state before publishing a callback. A transactional outbox can ensure the state change and event are committed together even if callback delivery fails.

Do not mark a credential claimable until tenant ownership, scopes, key limits, budget policy, and required downstream mappings have been committed. Do not mark it active merely because a provider-side operation started.

Prefer a separate one-time claim operation

After provisioning finishes, return a short-lived claim capability through the authenticated control channel:

{
  "credential_id": "cred_01J...",
  "status": "claimable",
  "claim_token": "clm_...",
  "claim_expires_at": "2026-12-03T11:30:00Z"
}

The client then calls:

POST /v1/credentials/cred_01J.../claim
Authorization: Bearer partner-control-token
Claim-Token: clm_...

The server verifies the partner identity, tenant ownership, credential ID, token digest, expiration, and claim state. The secret-bearing response must be excluded from application logs, traces, analytics, caches, error reports, and support tooling.

Choose claim retry semantics deliberately

There are three defensible delivery patterns:

  • Encrypted replay window: retain encrypted secret material briefly and return the same secret when an authenticated claim retry uses the same claim token. This handles a lost claim response but temporarily increases recoverable secret material.
  • Strict one-time claim: consume the claim at the first successful response attempt. This minimizes retention, but an interrupted response forces replacement.
  • Generate on claim: create the secret only when the claim is authorized. This avoids holding secrets for customers who never claim them, but policy changes between provisioning and claim must be revalidated.

For most partner platforms, a short encrypted replay window is the most operationally practical choice. Record claim_started_at and claim_confirmed_at, bind replay to the same partner and claim token, and delete ciphertext after confirmation or expiry. Never keep indefinitely decryptable customer secrets for support convenience.

Treat partial provisioning as a first-class outcome

Asynchronous provisioning can succeed in one system and fail in another. If a downstream credential is created but the local transaction cannot complete, do not retry downstream creation blindly. Record the external reference in a durable step log, enqueue a compensating revocation, and mark the operation for reconciliation.

Design each workflow step with a stable step idempotency key. A worker should be able to resume after a crash by reading completed steps rather than inferring success from a timeout.

FailureExpected behavior
Timeout before commitRetry creates the operation because no idempotency record exists.
Timeout after commitRetry returns the existing operation and credential IDs.
Concurrent duplicate requestsA uniqueness constraint selects one operation; the other request receives the same result.
Secret response lostReplay during the claim window or require replacement, according to the documented policy.
Claim token stolenRequire control-plane authentication, tenant binding, short expiry, single credential scope, and token revocation.
Callback delivery failsKeep retrying the event independently; clients can poll the operation resource.
Tenant deleted during provisioningStop issuance, revoke completed downstream credentials, and close the operation as failed.
Revocation fails downstreamDeny the key at the platform gateway immediately and continue downstream revocation retries.

Rotate with bounded overlap

Rotation should create a new credential version instead of mutating the existing secret. Keep both versions active during a documented migration window, expose last-used timestamps by version, and set a hard deadline for revoking the old version.

  1. Create version 2 with an idempotent rotation request.
  2. Provision and claim version 2 through the same workflow.
  3. Allow versions 1 and 2 to authenticate temporarily.
  4. Wait for customer confirmation or evidence that version 2 is in use.
  5. Revoke version 1 at confirmation or deadline expiry.

Overlap improves availability but temporarily expands the valid credential set. Limit the overlap duration, active versions per tenant, and number of abandoned rotations. Broader API key rotation workflow policy should also define emergency revocation, maximum lifetime, and ownership review.

Enforce policy on the provisioning API itself

The management API is a sensitive administrative surface. Apply authorization to every operation and verify that the authenticated partner can act on the target tenant. Recommended controls include:

  • Allowed scopes and maximum credential lifetime by partner and tenant.
  • Limits on active keys, creation frequency, and concurrent rotations.
  • Environment isolation so test identities cannot issue production keys.
  • Step-up authorization for broad scopes or emergency operations.
  • Audit events for requests, approvals, claims, rotations, revocations, and policy denials.
  • Immediate gateway-side denial for revoked, expired, or tenant-orphaned keys.

Attach usage to the credential ID and version rather than to the secret value. That supports per-customer investigation, revocation decisions, and API usage analytics by key without retaining secrets in telemetry.

Return stable, machine-readable errors

Use problem-details responses with stable types and operational fields. Never include a key, claim token, or recoverable secret in an error body.

{
  "type": "https://api.example.invalid/problems/idempotency-conflict",
  "title": "Idempotency key reused with different parameters",
  "status": 409,
  "operation_id": "op_01J...",
  "retryable": false,
  "conflicting_idempotency_key": "onboard-order-9918"
}

Distinguish authorization failures, key-limit exhaustion, idempotency conflicts, transitional states, terminal failures, and retryable downstream errors. For retryable responses, provide a bounded retry_after value.

Reconcile what request handling cannot prove

Run a periodic job that compares operation records, credential states, delivery records, tenant ownership, downstream references, and revocation queues. Alert on:

  • Operations stuck in provisioning, rotation_pending, or revoking.
  • Downstream credentials with no active owning tenant.
  • Claimable secrets approaching expiry.
  • Expired claim ciphertext that has not been deleted.
  • Revoked credentials that still authenticate.
  • Idempotency records whose operations or request hashes are missing.

Reconciliation is not a prediction that failures will be frequent. It is a control for states that distributed request handling cannot always resolve conclusively.

Implementation checklist

  • Require tenant-scoped idempotency keys for create and rotate operations.
  • Persist a canonical request hash and reject mismatched retries.
  • Represent provisioning with an operation resource and explicit states.
  • Use database uniqueness constraints for concurrent duplicate requests.
  • Separate public key identifiers from secret material.
  • Store a keyed digest for authentication.
  • Deliver secrets through a short-lived, authenticated claim operation.
  • Delete replay ciphertext after confirmation or expiry.
  • Make partial success visible and attach compensating revocation work.
  • Support bounded overlap rotation with per-version usage data.
  • Deny revoked credentials locally even when downstream cleanup is delayed.
  • Reconcile stuck, orphaned, unclaimed, and inconsistently revoked resources.

The key design decision is to stop treating issuance as CRUD. Build it as a resumable workflow with stable identities, explicit states, controlled secret delivery, and evidence for every transition. That gives partners safe retries without turning credential recovery into an indefinite secret-storage problem.

Related reading

FAQ

Często zadawane pytania

Dlaczego sam klucz idempotencji nie wystarczy?
Klucz idempotencji zapobiega duplikacjom operacji logicznych tylko wtedy, gdy jest trwale przechowywany, ma zakres dzierżawy, jest powiązany z kanonicznym skrótem żądania i chroniony przez ograniczenie unikalności. Samo w sobie nie rozwiązuje problemu jednorazowego tajnego doręczenia, częściowego sukcesu w dalszej części łańcucha dostaw, rotacji czy pojednania.
Czy API powinno zwrócić sekret w oryginalnej odpowiedzi na utworzenie?
Można, ale osobna operacja żądania zapewnia jaśniejszą semantykę odzyskiwania. Jeśli odpowiedź dotycząca utworzenia zawierająca jedyną kopię klucza tajnego zostanie utracona, klient może nie być w stanie określić, czy powinien ponowić próbę, pobrać czy zastąpić poświadczenie.
Czy można kiedykolwiek odzyskać odzyskany klucz API?
Bezpieczniejsza opcja domyślna to nie. Jeśli wymagana jest ponowna próba dostarczenia roszczenia, zachowaj zaszyfrowany tajny materiał tylko przez krótki udokumentowany okres, powiąż powtórkę z oryginalnym uwierzytelnionym roszczeniem i usuń zaszyfrowany tekst po potwierdzeniu lub wygaśnięciu.
Jak powinno działać odwołanie, gdy dostawca niższego szczebla jest niedostępny?
Odmów poświadczenia natychmiast na bramie platformy, zmień jego stan lokalny na unieważnienie lub odwołanie zgodnie z umową i ponów próbę oczyszczenia dalszej części z trwałej kolejki. Uzgadnianie powinno ostrzegać, jeśli poświadczenia podrzędne pozostają aktywne.