Как создать журналы аудита с защитой от несанкционированного доступа для API-интерфейсов LLM с несколькими поставщиками
Практическая архитектура для регистрации того, кто инициировал каждый запрос LLM, какая политика его санкционировала, почему была выбрана модель и были ли впоследствии изменены записи аудита.
An LLM request can pass through an application, gateway, cloud account, provider API, billing pipeline, and observability stack. Each system records a different fragment. During an investigation, the resulting logs may show that a request happened without proving who initiated it, which policy allowed it, why a provider was selected, or whether someone later changed the record.
The solution is to treat auditability as a separate security ledger—not as another observability dashboard. Generate a canonical request-decision event at the gateway, preserve it in tamper-evident storage, and enrich it with provider and billing evidence without rewriting the original event.
Why provider and application logs are not enough
Provider administrative logs, cloud audit logs, gateway traces, and invoices answer different questions:
- Administrative logs can show that a key, project, role, or service account changed.
- Cloud audit logs can show that an API operation reached a managed service under a particular cloud identity.
- Distributed traces explain latency, retries, errors, and the path through an application.
- Usage and billing records establish metered consumption and settled cost.
None is automatically a complete LLM request audit trail. Provider records differ in schema, enablement, retention, and content exposure. Traces may be sampled. Search indexes may permit updates or deletions. Billing data often arrives after the request and may aggregate several operations.
This distinction is a fact about the records' purposes, not a prediction about provider reliability. OpenTelemetry, for example, defines traces and logs as telemetry signals; it does not make those records immutable compliance evidence. Some cloud audit systems offer integrity validation, but that protects their delivered files rather than the gateway's complete authorization and routing decision.
Use a dual-record architecture
Keep operational telemetry and audit evidence separate:
- Operational record: optimized for search, debugging, performance analysis, dashboards, and short-lived high-cardinality data.
- Audit record: a minimal, append-only account of identity, authorization, routing, outcome, and integrity.
A multi-model AI API gateway is the best place to create the authoritative request-decision event because it sees the caller identity, tenant context, policy result, and selected route before provider-specific details obscure them.
The operational record may include stack traces, timing breakdowns, or approved diagnostic samples. The audit record should exclude raw prompts, responses, API keys, bearer tokens, and unrestricted error bodies. Separating the two prevents a debugging feature from silently becoming a sensitive-content archive.
Define one canonical audit-event schema
A useful schema must support reconstruction without requiring an investigator to read prompt content. At minimum, record:
- A globally unique event ID, event timestamp, ingestion timestamp, schema version, and event type.
- Tenant, workspace, environment, application, and workload identifiers.
- Actor type, service-account ID, and a nonreversible API-key fingerprint.
- The requested capability or model alias, not just the final provider model.
- Authorization result, policy version, and stable decision reason code.
- Selected provider, concrete model version, route reason, and fallback or override status.
- Provider request ID, outcome class, usage-ledger reference, and trace ID when available.
- Content HMAC reference, content classification, retention class, sequence number, and integrity fields.
A compact request-decision event might look like this:
{
"event_id": "evt_01J...",
"event_type": "llm.request.decision",
"tenant_id": "tenant_42",
"workload_id": "support_summarizer_prod",
"actor": {
"type": "service_account",
"id": "svc_support_01",
"key_fingerprint": "kfp_8b31..."
},
"request": {
"capability": "text.summarize",
"content_hmac": "hmac:v3:91ab...",
"classification": "internal"
},
"policy": {
"decision": "allow",
"version": "policy-2027-02-14.3",
"reason_code": "ALLOW_MODEL_TIER_STANDARD"
},
"route": {
"provider": "provider_b",
"model": "model-x-2027-01",
"reason_code": "ROUTE_REGION_AND_QUALITY_MATCH"
},
"trace_id": "4bf92f...",
"sequence": 184223,
"previous_hash": "sha256:2c70..."
}
Use controlled enums for decisions and reason codes. Free-form messages can be included as secondary context, but they should not determine how investigators classify an authorization, fallback, override, or denial.
Create the event before forwarding the request
The gateway should resolve identity, evaluate policy, select a route, and construct the audit event before sending traffic to a provider. This captures denied requests and failed routing decisions as well as successful calls.
There are two practical persistence patterns:
Synchronous durable write
Write the event to a durable append-only destination before provider dispatch. This offers the strongest completeness guarantee, but it adds latency and makes the audit service part of request availability. Define explicit fail-open or fail-closed behavior by workload risk; do not let an accidental timeout policy decide it.
Transactional outbox
Commit the request decision and an outbox record in the same transaction, then deliver it asynchronously to immutable storage. This reduces the synchronous dependency but introduces a short period during which evidence exists only in the transactional store. Monitor outbox age, delivery failures, and sequence gaps.
Either pattern should use idempotent event IDs. A retry must not create several authoritative decision events unless each provider attempt is intentionally modeled as a child event.
Fingerprint content without storing it
Plain hashes are unsafe for predictable or low-entropy prompts because an attacker can guess candidate content and compare hashes. Use a keyed HMAC with a tenant-scoped or appropriately segmented secret instead.
Record the HMAC key version, but never the key itself. Retain old verification keys under controlled access for as long as their records remain auditable. If policy requires cryptographic deletion, destroying a tenant-specific HMAC key can make old fingerprints unverifiable; document that consequence in the retention design.
A content fingerprint proves that two observed bodies were identical under the same canonicalization and key regime. It does not explain their meaning. Record an approved classification label—such as public, internal, confidential, or regulated—when investigators need risk context without prompt access.
Make the ledger tamper-evident
Immutable storage prevents or delays alteration, while cryptographic proofs make alteration detectable. Use both:
- Assign a monotonically increasing sequence number within each tenant or partition.
- Hash each canonical serialized event with the previous event hash.
- Periodically sign a checkpoint containing the partition ID, sequence range, terminal hash, and event count using a managed signing key.
- Place events and checkpoints in append-only or retention-locked storage under a separate security boundary.
- Run scheduled verification that detects changed records, missing sequence numbers, reordered events, invalid signatures, and absent partitions.
A global chain provides simple ordering but becomes a throughput bottleneck and expands the impact of one failure. Per-tenant or time-partitioned chains scale better. They require a signed manifest listing every expected partition and checkpoint so that an attacker cannot hide an entire chain.
Per-event signatures provide fine-grained verification but increase signing cost and key-management complexity. Hash chains with signed checkpoints are usually the more practical recommendation, although the right checkpoint interval depends on recovery objectives and evidence requirements.
Enrich records without mutating history
Provider request IDs, final token counts, settled costs, and administrative events may arrive later. Append enrichment events that reference the original event ID instead of updating the request-decision record.
For example, an initial event can record outcome=pending. A later provider-result event records the provider request ID and response status, while a cost-settlement event links the same request to LLM API cost attribution. This preserves what the gateway knew at each point in time.
Normalize provider administrative records through adapters, but retain the original provider event type and an immutable digest of the protected raw record. The canonical fields make cross-provider searches possible; the original evidence prevents normalization from erasing provider-specific meaning.
Protect access to the audit system
Platform administrators should not automatically be able to rewrite, export, or change retention for the ledger they operate. Separate these permissions:
- Audit-event writer
- Integrity verifier
- Search and investigation reader
- Bulk exporter
- Retention-policy administrator
- Signing-key administrator
Audit every read, export, failed verification, legal hold, retention change, and permission change. Connect actor attribution to governed service accounts and LLM API key management so that a fingerprint resolves to an accountable workload without exposing the credential.
Run reconstruction drills
Do not validate the design only by checking that records exist. Give an investigator a scenario and require a timeline without prompt access:
- Create and then revoke a workload key.
- Change a model-access policy and preserve both versions.
- Submit one allowed request and one denied request.
- Trigger a provider fallback or manual route override.
- Settle usage and cost after the request.
- Verify the chain and signed checkpoint.
- Reconstruct who acted, what policy applied, why routing occurred, what the provider returned, and whether evidence changed.
Track failures as control gaps: missing identity, ambiguous reason code, unavailable policy version, broken provider correlation, unverifiable fingerprint, sequence gap, or excessive access to sensitive records.
Implementation checklist
- Publish a versioned canonical event schema and reason-code registry.
- Generate request-decision events before provider dispatch.
- Exclude prompts, responses, keys, tokens, and unfiltered errors.
- Use tenant-scoped keyed HMACs when content correlation is necessary.
- Choose synchronous persistence or a monitored transactional outbox.
- Store canonical events separately from searchable operational indexes.
- Chain events by sequence and sign periodic checkpoint manifests.
- Append enrichment events instead of rewriting original records.
- Define retention by event class and legal need.
- Separate reader, exporter, verifier, retention, and key-administration roles.
- Test reconstruction and integrity verification on a schedule.
Build for reconstruction, not data accumulation
A defensible LLM audit trail does not need to retain every prompt. It needs to preserve attributable decisions: who or what initiated a request, which policy version authorized it, why a provider and model were selected, what happened next, and whether the evidence remains intact.
Start with the canonical request-decision event, append later evidence, and make integrity failures visible. That produces a smaller and safer ledger while giving security, platform, and compliance teams a repeatable way to reconstruct incidents across providers.