Skip to main content
Back to all articles
AI Engineering 17 min readUpdated November 3, 2026

A Compromise Budget for Multi-Tenant LLM Gateways

Design a safer LLM gateway with verified deployments, tenant-bound model routing, separate credential custody, restricted network paths, and testable incident recovery.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#LLM Gateway#Supply Chain Security#Multi-Tenancy#Workload Identity#DevSecOps#TypeScript#Python#Model Routing
On this page

A model gateway makes one architectural promise: applications can ask for an AI capability without carrying every provider integration themselves. In a multi-tenant system, that simplifies model selection, rate limiting, and cost accounting. It also creates a question that belongs in the threat model before the first production deployment:

If the gateway executes code we no longer trust, how much authority can that code exercise before we stop it?

I think of the answer as a *compromise budget*: the maximum provider accounts, tenants, data paths, deployment revisions, and time windows a compromised component can affect. This is a design objective, not a measured number or a formal security standard.

A recent case makes the question concrete. Microsoft Security Research reported that a malicious LiteLLM 1.107.0 release was distributed through PyPI and official container images on October 21, 2026. Its recovered Python startup components could execute without a normal application import and attempted to collect reachable credentials. Microsoft documented observed collection behavior but did not confirm execution of the optional remotely retrieved second-stage code. The report is primary evidence about the incident; it does not prove that every installation leaked data. See Microsoft's technical investigation.

The useful lesson for an engineer building a new platform is broader than any one package: a deployment trust decision, a workload identity, and a provider credential are three different things. I would not let a model gateway implicitly own all three.

This article develops an original architecture for a hypothetical analytics SaaS with several tenants, a routing service, model-provider connections, and AWS-based inference alongside API-key-based providers. It is a design exercise, not a claim that I deployed or benchmarked this exact system. It builds on my model-routing policy approach while focusing on the authority and recovery boundaries beneath the router.

Define the damage boundaries before choosing the proxy

Imagine two tenants: a regulated reporting customer and a low-risk internal experiment. Both use the same frontend and submit work through the same logical model API. That does not require both workloads to share a process that can retrieve both provider credentials or access both customers' configuration records.

I would start with five explicit budgets:

BoundaryQuestion to answer before deploymentEvidence to require
TenantCan one execution identity cross into another tenant's provider account or records?Deny tests and storage/service identity policies
ProviderWhich provider accounts and model routes can this workload invoke?Approved route-to-credential mapping and provider-side controls
NetworkWhich destinations can process code reach, including DNS and internal metadata?Enforced outbound policy plus negative network tests
ReleaseWhich exact artifact and build identity are eligible to execute?Verified digest, trusted provenance, and admission decision
TimeHow long can a compromised identity continue making calls after detection?Revocation drills, credential lifetime evidence, and drain timings

Reducing only one column rarely solves the whole problem. A digest-pinned image can contain malicious code that was present when its digest was approved. A narrow provider key can still expose one tenant's sensitive prompts. An outbound allowlist can stop arbitrary exfiltration yet still allow abusive calls to an authorized provider.

The objective is *bounded authority under failure*, not a belief that any one security product certifies a dependency as safe.

Separate public routing from credential-bearing execution

I would keep request authorization, model routing, and credential use in separate roles, even if a small team initially implements them as services in a single repository.

~~~text Authenticated application callers | [1] Request admission service user/tenant • budget • policy | signed, scoped work intent | [2] Model router (no root keys) model class • region • cell | authorized execution cell / \ [3a] IAM-backed cell [3b] API-key cell Bedrock role scoped secret access \ / [4] Controlled provider egress | approved provider destinations

Outside the request path: [Release admission] --> verifies deployed image + provenance [Audit pipeline] <-- receives metadata, not credentials [Revocation plane] --> can disable cells and credentials ~~~

The diagram shows trust boundaries, not a particular Kubernetes manifest or proof of isolation.

The request-admission service derives the tenant and principal from authenticated server context. It checks product permissions, model entitlements, and a spend reservation before a route is selected. The routing component receives an approved work intent, not the caller's self-declared role or direct credential reference.

An execution cell owns just enough provider authority for its assigned partition. A deployment might partition by tenant, risk tier, provider account, or region. Per-tenant processes offer stronger isolation but increase deployment and connection overhead; per-provider pools are cheaper but share a larger credential and memory boundary. Make that trade-off explicit rather than claiming all multi-tenant proxies are isolated by a tenant ID column.

The delegated-identity pattern explains how to preserve the caller's authority through agent tools. At the model gateway, that same identity should determine which cell may act; it should not become a client-provided string that the cell trusts without verification.

A broker cannot mint a provider capability that does not exist

Short-lived credentials are excellent when the provider supports them. For example, AWS documents workload identities and temporary role credentials for EKS, and Bedrock's IAM actions can be limited under identity-based policies. See EKS IAM guidance and Bedrock policy examples.

But do not assume that every commercial model provider accepts arbitrary short-lived, one-tenant, one-model tokens minted by *your* broker. An application-issued JWT accepted by an internal proxy is not automatically a valid provider credential.

For a provider that supports only an API key, there are two honest designs:

  1. Give a narrowly scoped execution cell its own provider key, configured with the provider's real account/project permissions when supported. The cell remains exposed to that key.
  2. Keep the API key in a separate credential-owning forwarding service. The gateway sends a signed, authorized request to that service; the forwarding service applies a fixed allowlist, request bounds, and tenant policy before making the provider call. The key never returns to the gateway.

Option two limits direct key disclosure from a compromised gateway, but it does not make abuse impossible. A compromised gateway might still submit permitted-looking requests through the forwarding service. That service needs independent authentication, replay protection, quotas, model restrictions, logging, and a kill switch. It must authenticate the tenant and approved work intent independently; trusting a free-form tenantId provided by a compromised gateway simply moves the vulnerability.

There is no universal “one token per model for five minutes” guarantee. The enforceable scopes and expiration behavior are determined by the actual provider's authentication capabilities and the application-owned forwarding boundary.

TypeScript: authorize a route before selecting a credential

The router below receives a trusted tenant identity and a versioned policy table. It returns a cell identifier, never a key or a key-vault path. Route names in client input are merely choices inside the current entitlement set.

~~~typescript type Provider = "bedrock" | "api-key"; type ModelClass = "fast" | "deliberate";

type TrustedPrincipal = Readonly<{ tenantId: string; actorId: string; }>;

type AllowedRoute = Readonly<{ tenantId: string; modelClass: ModelClass; provider: Provider; cellId: string; maxOutputTokens: number; region: string; }>;

type RouteRequest = Readonly<{ modelClass: ModelClass; outputTokens: number; region: string; }>;

type ApprovedPlan = Readonly<{ cellId: string; provider: Provider; tenantId: string; outputTokens: number; region: string; }>;

function planRoute( actor: TrustedPrincipal, request: RouteRequest, entitlements: readonly AllowedRoute[], ): ApprovedPlan { if (!actor.tenantId || !actor.actorId || !Number.isSafeInteger(request.outputTokens) || request.outputTokens <= 0) { throw new Error("invalid-input"); }

const matches = entitlements.filter(route => route.tenantId === actor.tenantId && route.modelClass === request.modelClass && route.region === request.region && route.maxOutputTokens >= request.outputTokens && route.cellId.length > 0 );

// Ambiguous entitlements are a configuration error, not a // reason to pick whichever credential appears first. if (matches.length !== 1) { throw new Error("route-not-authorized-or-ambiguous"); }

const selected = matches[0]; return { tenantId: actor.tenantId, cellId: selected.cellId, provider: selected.provider, outputTokens: request.outputTokens, region: selected.region, }; } ~~~

This is a policy-selection sketch, not a secure API endpoint. It assumes that the principal came from verified authentication, the entitlement list came from a protected and fresh policy source, and the model class/region values were validated against an actual runtime schema. The returned plan also needs to be bound to a specific authorized request, policy revision, expiry, and replay-resistant identifier before another service can accept it. The execution cell must verify that binding independently, rather than accept this JSON as authorization.

Notice the deliberate omission: there is no provider key lookup here. A compromised routing worker should not have permission to enumerate or fetch every cell's credentials. That separation is more valuable than a beautiful model-selection heuristic.

The route decision should also reserve cost under a tenant-level budget; admission and usage reconciliation are explored in my multi-tenant AI budgeting article.

Release admission must verify origin, not just bytes

A container digest answers which bytes will run. It does not by itself answer *who built those bytes, from which source, or under which approved workflow*.

I would build a release-admission decision around these independently checked facts:

EvidenceWhat it establishesWhat it does not establish
Registry digestArtifact identity at pull timeBenign code or trustworthy source
Signature verificationAn approved signing identity attested to an artifactThat the identity was uncompromised
Build provenanceClaimed source, builder, parameters, and artifact linkage, subject to verificationThat every dependency is safe
Protected deployment approvalAn authorized policy accepted the verified artifactSafety of runtime behavior
Post-deploy canarySelected workflows still satisfy observable contractsAbsence of hidden malicious behavior

The SLSA provenance specification defines fields such as the artifact subject, builder identity, and resolved dependencies. Sigstore's verification documentation explains signature validation, while GitHub artifact attestations provide one build-provenance mechanism. In practice, a deployment verifier must check the expected signer identity, source repository, workflow/builder, and artifact digest, not accept an arbitrary valid signature.

For Python build dependencies, pip's secure-install documentation recommends hash-checking mode and disallowing source distributions when the security policy requires it. Hash checking is an all-dependencies policy, not a lone hash for the top-level gateway library. Lock transitive packages and review the artifact update before promotion.

An important ordering detail: build or install dependencies in an isolated, low-trust environment before introducing production credentials. A package can execute build or startup code without being imported by the application. Only tested, attested artifacts move into the execution environment. Avoid mutable base-image tags and emergency upgrades that bypass the same admission process.

Python: enforce the deployment claim in a trusted verifier

Below is an intentionally small admission-policy function. It compares a local allowlist against a trusted attestation verification result. Cryptographic verification, certificate trust, signature identity, and provenance parsing must happen upstream in a properly configured verifier; an arbitrary JSON object claiming to be trusted must never be accepted from the candidate image.

~~~python from dataclasses import dataclass

@dataclass(frozen=True) class VerifiedArtifact: digest: str source_repo: str builder_id: str signer_identity: str provenance_verified: bool

@dataclass(frozen=True) class ReleasePolicy: digest: str source_repo: str builder_id: str signer_identity: str

def admit_release( observed: VerifiedArtifact, expected: ReleasePolicy, ) -> bool: """Policy comparison only; NOT a signature verifier.""" if not observed.provenance_verified: return False if not observed.digest.startswith("sha256:"): return False if len(observed.digest) != len("sha256:") + 64: return False try: int(observed.digest[7:], 16) except ValueError: return False return ( observed.digest == expected.digest and observed.source_repo == expected.source_repo and observed.builder_id == expected.builder_id and observed.signer_identity == expected.signer_identity )

Synthetic policy values; never approve real artifacts from these.

digest = "sha256:" + "a" * 64 policy = ReleasePolicy( digest=digest, source_repo="https://example.invalid/approved/gateway", builder_id="https://example.invalid/approved-builder", signer_identity="release@example.invalid", ) assert admit_release( VerifiedArtifact( digest=digest, source_repo=policy.source_repo, builder_id=policy.builder_id, signer_identity=policy.signer_identity, provenance_verified=True, ), policy, ) assert not admit_release( VerifiedArtifact( digest=digest, source_repo="https://example.invalid/untrusted/fork", builder_id=policy.builder_id, signer_identity=policy.signer_identity, provenance_verified=True, ), policy, ) ~~~

The example tests comparison logic, not a real build's provenance. In production, only the trusted verifier process should instantiate VerifiedArtifact, and its result must be authenticated or consumed in-process at the admission boundary. For a full implementation, also validate provenance subjects, build type, external parameters, applicable transparency information, and the deploy-time image digest. If signature verification is unavailable, fail closed rather than silently using provenance_verified=True as a configuration flag.

You can see the same design instinct in my coding-agent instruction provenance article: authority must be anchored in a protected source, not in data that the untrusted workload controls.

The network boundary must exist outside the gateway process

A compromised component should not be able to expand its outbound destinations by editing an application configuration flag.

For Kubernetes, a default-deny egress NetworkPolicy can isolate selected pods, provided the cluster uses a network plugin that enforces NetworkPolicy. Kubernetes explicitly documents that a deny-all policy also blocks DNS unless DNS is separately allowed. See the official NetworkPolicy guide.

The provider connection path introduces an important practical constraint: standard Kubernetes NetworkPolicy expresses network peers and ports, not a complete hostname- and HTTP-path-based security policy. Public model APIs can have changing IP addresses. I would send outbound traffic through a separately managed egress proxy or provider-adapter cell, with hostname/TLS checks and restricted destinations, while restricting the gateway pod to the internal endpoint it actually requires.

This needs careful testing. DNS access can itself be an exfiltration channel; an unrestricted hostname or DNS resolver is not a complete defense. Proxies can also be abused through redirect behavior, CONNECT methods, or permissive wildcard rules. Validate the effective destination after redirects, restrict outbound ports, and ensure the gateway cannot bypass the proxy through direct socket access. Network identity controls must live beyond the permissions of the compromised workload.

And egress control is not enough: a malicious but authorized request might put customer secrets in the prompt sent to an approved provider. Apply tenant authorization, content-release policy, and scoped data access before forwarding. The AI output and egress security boundary covers that separate leak path.

Treat provider credentials as a rotating ownership graph

Rotation plans often describe which secret to replace. Incident response needs a graph of where a secret was usable.

For each execution cell, I would maintain a protected inventory of its deployment identity, IAM roles, secret-store permissions, provider account/project, database permissions, other mounted credentials, and allowed destinations. A registry of *references* and policy is useful; it should not become another plaintext copy of every provider key.

Where the platform supports temporary workload identity, prefer it over long-lived cloud credentials. Google Cloud's Secret Manager best practices also recommend least-privilege access and caution against exposing secrets through environment variables and files. For API-key providers, use separate keys/accounts/projects where their actual authorization features permit, and restrict secret-store access to the relevant cell. If one global provider key is unavoidable, document that limitation in the blast-radius assessment.

The inventory makes three questions answerable during an incident: which credentials could the affected process reach, which other workloads share them, and which providers need key or session revocation? It does not prove those credentials were stolen.

Response to a suspected malicious dependency

Microsoft's investigation of the October 2026 LiteLLM release is useful here because it illustrates why normal application-level checks are insufficient. The injected startup behavior could run during interpreter initialization, and removing only the package was not necessarily enough to remove its effects. Microsoft advises investigating suspect environments from a known-clean toolchain, rather than invoking their Python interpreter to inspect them.

For a production gateway I would define the response in stages:

  1. Contain: disable admissions for the affected gateway revision; isolate its network identity and prevent automatic restart from the suspect artifact. Preserve appropriate forensic records without rerunning potentially hostile code.
  2. Scope: enumerate deployments, development environments, CI images, mirrors, caches, secret permissions, and authorized destinations that might have included the artifact. Use corroborated telemetry to distinguish possible exposure from observed execution.
  3. Restore: rebuild from a separately verified artifact in a clean environment; reapply known-good policy and test egress, tenant isolation, and provider invocation before reopening traffic.
  4. Revoke and rotate: from a clean administrative environment, rotate credentials reachable by the affected identities and revoke supported sessions/tokens. Confirm the replacement workloads cannot retrieve old secrets.
  5. Reconcile: inspect provider-side usage, unusual model invocation, billing anomalies, network events, and downstream customer-impact evidence within the known windows. Preserve uncertainty when telemetry cannot establish an outcome.

Rotation before isolating the compromised workload can expose the new secret to the same hostile process. Conversely, waiting for perfect forensics can extend exposure. The runbook needs a designated owner who can contain immediately while the investigation continues.

Treat suspected release compromise separately from a routine provider outage. A failover route should not automatically move traffic into another cell that shares the same possibly exposed credential. See provider failover and circuit breakers for availability controls; those controls need a security-aware disable state.

Measure whether the design actually limits authority

I would not describe the gateway as “secure” because all dependency scans are green. Instead I would monitor signals that correspond to the five budgets defined earlier.

Admission and release: count rejected artifact digests, failed provenance checks, unapproved builder identities, policy-version mismatches, and deployments that lack a verified record. Alert on bypass attempts, not just failed builds.

Tenant and provider authority: measure denied cross-tenant routes, execution-cell policy failures, requests against disallowed models, and provider usage that cannot be reconciled to an admitted work identity. A surge in blocked calls can be a security signal or an application bug; investigation must preserve both possibilities.

Egress: capture denied destinations and changes to approved destination profiles. Keep high-cardinality or sensitive details in restricted logs rather than metrics labels.

Revocation and recovery: track elapsed time between containment decision and effective denial of new requests, the percentage of affected credential references accounted for, validation of clean redeployments, and unresolved provider-side activity. Record the numerator and denominator; a green “rotation complete” badge without a credential inventory is poor evidence.

Use tests that attack the boundaries, not only tests that invoke the happy path:

Failure injectionExpected protected behavior
A new signed image comes from an unapproved builderAdmission blocks despite valid cryptography
An approved image digest is replaced by a mutable tagAdmission blocks when the resolved digest differs
A tenant sends another tenant's identifier to the routerServer derives scope from the authenticated principal
The router tries to read provider secretsSecret access is denied by workload identity
A cell attempts an unknown external HTTPS destinationOutbound connection is blocked and recorded
A compromised router tries to alter forwarding policySeparate policy owner rejects the change
An API-key provider lacks per-tenant scopesRisk assessment reflects the actual shared credential
A cell is revoked while requests are in flightNew admissions stop; pending requests follow documented drain/cancel rules

These are acceptance criteria for a proposed system—not results of a deployed penetration test. Test the actual identity provider, egress implementation, secret store, and hosting platform before relying on them.

Where extra isolation is worth its cost

A single shared gateway is simpler to deploy and cheaper to operate. Per-tenant cells add rollout complexity, connection management, model-provider quotas, warm-up overhead, and more policies to audit. A credential-forwarding service introduces another critical dependency and can itself become a bottleneck or confused deputy.

For a small internal product with one provider key, the practical first step might be a locked release pipeline, isolated runtime identity, bounded access to a single provider project, and monitored outbound access. For a regulated multi-tenant workload, I would invest earlier in stronger account partitioning and a separate credential-use plane.

The point is not to build the most complicated security diagram. It is to choose what a compromised gateway cannot do, prove that the boundary is enforced independently of its process, and build a recovery plan for the authority that remains.

Primary references and provenance

Topic provenance: This topic was discovered through Viral Ruparel's October 27, 2026 article about LLM gateway supply-chain risk. The hypothetical analytics platform, compromise-budget model, service-cell architecture, admission-policy examples, tests, and analysis here were developed independently. The documented LiteLLM incident is attributed to Microsoft's primary investigation rather than treated as a personal observation.

KEEP READING

Related engineering notes