Print-ready version Back to the article
HMMNM Security
hmmnm.com

Security

Build a Local AI Agent Gateway: Auth, Rate Limits and Tool Allowlists with Kong or LiteLLM

By Prabhu Kalyan Samal | Published 28 November 2026 | 10 min read

https://hmmnm.com/build-a-local-ai-agent-gateway-auth-rate-limits-and-tool-allowlists-with-kong-or-litellm/

11 min read · 2,009 words

{
“@context”: “https://schema.org”,
“@type”: “TechArticle”,
“headline”: “Build a Local AI Agent Gateway: Auth, Rate Limits and Tool Allowlists with Kong or LiteLLM”,
“description”: “Hands-on tutorial: deploy a local AI agent gateway with Kong or LiteLLM enforcing per-tool auth, rate limits, tool allowlists and audit logging. Real configs included.”,
“keywords”: “AI agent gateway, Kong, LiteLLM, tool allowlists, agent security”,
“author”: {“@type”: “Organization”, “name”: “HMMNM Security”},
“publisher”: {“@type”: “Organization”, “name”: “HMMNM Security”}
}

An AI agent gateway is a dedicated control plane that brokers every call from your agent to its tools—authenticating the agent, enforcing per-tool allowlists, applying rate limits and quotas, and writing an audit log of each request. Put one between your agent and its tool APIs, and you convert an over-privileged prompt-driven process into a governed, observable service.

TL;DR: What an AI Agent Gateway Does and Why You Need One

An AI agent gateway intercepts every tool call an agent attempts to make. Instead of your LangChain loop, CrewAI crew, or homegrown orchestrator holding credentials for a database API, an email service, and a ticketing system simultaneously, the gateway holds them. The agent presents a scoped identity; the gateway decides—on every single call—whether that identity may invoke that tool, at what rate, and with what budget. Then it logs the whole thing. You get authentication, authorization, throttling, and forensics in one enforcement point instead of scattered across agent code. Kong Gateway and LiteLLM both do this job locally, today, with configs you can ship in an afternoon.

Why Agents Need a Gateway, Not Just an API Key

Traditional API security assumes the caller is a deterministic service. You issue a key, scope it broadly, and trust the code behind it. Agents break that assumption. An LLM agent decides which tools to call at runtime based on model output—and model output can be steered by anyone who controls text the model reads. That’s not hypothetical: OWASP’s GenAI Top 10 risks list prompt injection and excessive agency as first-class threats, and CISA’s joint guidance on AI system security emphasizes least-privilege tool access for exactly this reason.

The failure modes are predictable:

  • Prompt injection → tool abuse. A poisoned document instructs your agent to call delete_record or exfiltrate data through an outbound HTTP tool. If the agent holds broad credentials, the gateway-equivalent check lives in the model’s judgment. That’s not a control.
  • Over-privileged agents. The typical dev pattern is one API key with everything enabled because “the agent might need it later.” Now a single successful injection yields full tool access.
  • No audit trail. When an agent deletes 4,000 rows at 3 a.m., you need to answer: which agent identity, which tool, what arguments, on whose behalf? Scattered tool-side logs rarely reconstruct that.
  • Runaway loops. Agents retry. Agents loop. Without quota enforcement at a layer the model can’t talk its way past, one bad planning cycle can generate thousands of paid or destructive API calls.

The fix is architectural, not prompt engineering. Deny by default at a layer beneath the model.

Architecture: Agent, Gateway, Tool Layer

The request flow is simple and worth internalizing:

Agent ──▶ Gateway (auth → allowlist → quota → log) ──▶ Tool API
          ▲
          └── Audit log / SIEM

Three interception patterns matter:

  1. Gateway in front of each tool API. Kong proxies your internal REST services; the agent points at gateway routes, never at services directly. Network policy enforces that tools are only reachable through the gateway.
  2. Gateway in front of the LLM itself. LiteLLM’s proxy mode sits between your agent and model endpoints (OpenAI, Anthropic, local Ollama/vLLM), enforcing virtual keys, budgets, and allowed tool/function definitions per key.
  3. Both. LiteLLM in front of models, Kong in front of tools. This is the full production pattern.

Lab Setup and Prerequisites

You need Docker and Docker Compose, Kong Gateway (3.x works via the kong/kong-gateway image or OSS kong), LiteLLM (pip install "litellm[proxy]"), and a sample tool API. For the demo we’ll use a trivial internal REST service:

# docker-compose.yml (excerpt)
services:
  kong:
    image: kong:3.7
    environment:
      KONG_DATABASE: "off"
      KONG_DECLARATIVE_CONFIG: /kong/kong.yml
      KONG_PROXY_ACCESS_LOG: /dev/stdout
    ports: ["8000:8000", "8001:8001"]
    volumes: ["./kong:/kong"]
  tool-api:
    image: hashicorp/http-echo
    command: ["-text=TOOL-OK", "-port=5678"]
    ports: ["5678:5678"]

In production, keep the tool API on an internal network with no published ports—only Kong reaches it.

Option A: Building the Gateway with Kong

Kong’s declarative config defines a service, routes, and plugins. Here’s a tool API behind key-auth, rate limiting, and ACLs:

# kong/kong.yml
_format_version: "3.0"
services:
  - name: records-tool
    url: http://tool-api:5678
    routes:
      - name: records-route
        paths: ["/tool/records"]
    plugins:
      - name: key-auth
      - name: rate-limiting
        config:
          minute: 30
          policy: local
      - name: acl
        config:
          allow: ["records-group"]

consumers:
  - username: research-agent
    keyauth_credentials:
      - key: agent-key-research-001
    acls:
      - group: records-group

Test it:

curl -s http://localhost:8000/tool/records 
  -H "apikey: agent-key-research-001"
# → TOOL-OK

curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/tool/records 
  -H "apikey: agent-key-unauthorized-999"
# → 401

# A valid key without the ACL group:
# → 403 "You cannot consume this service"

The acl plugin is your per-tool allowlist: each tool route declares the consumer groups allowed to hit it. Agents get keys; keys get groups; groups map to tools. The agent physically cannot reach a tool its key isn’t assigned to—prompt injection can’t fix a 403.

Option B: Building the Gateway with LiteLLM

LiteLLM’s proxy takes an LLM-native approach: virtual keys with budgets and scoped tool access, enforced on chat/completions calls that include tools definitions. Per the LiteLLM virtual keys documentation:

# litellm/config.yaml
model_list:
  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/OPENAI_API_KEY

general_settings:
  master_key: sk-master-local-only

litellm_settings:
  max_budget: 50.0        # global cap, USD
  budget_duration: 30d

router_settings:
  num_retries: 2

Then mint a scoped key via the admin API:

curl -X POST http://localhost:4000/key/generate 
  -H "Authorization: Bearer sk-master-local-only" 
  -d '{
    "key_alias": "support-agent",
    "max_budget": 5.0,
    "rpm_limit": 20,
    "tpm_limit": 50000,
    "models": ["gpt-4o-mini"],
    "metadata": {"allowed_tools": ["search_kb", "create_ticket"]}
  }'

Budget and rate enforcement are built into the proxy—exhaust the key’s budget and LiteLLM returns 429/401 before the request reaches the model. For tool-level scoping, enforce allowed_tools in a custom callback that inspects the tools array on each request and rejects undeclared functions.

Enforcing Per-Tool Authorization and Allowlists

The principle either way: deny by default. Never a rule that says “block these tools”; always “allow these tools, block everything else.”

Kong: one route per tool, one ACL group per role, consumers mapped to groups. Adding a tool means adding a route and updating group membership—not editing agent code. The agent’s key only unlocks its routes.

LiteLLM: key metadata or team scoping defines the function allowlist; a callback compares requested tools against it per request. A key scoped to search_kb and create_ticket cannot invoke run_sql even if the model hallucinates a call to it.

On the agent side, also filter the tool definitions you pass into the prompt to match the key’s scope. Both layers together mean the model never even sees tools it can’t call—reducing injection surface, not just blocking exploitation.

Rate Limits and Quotas for Agent Traffic

Agent traffic is bursty by nature: one planning step can fan out into a dozen parallel tool calls, and a retry loop can sustain that indefinitely. Design limits in two dimensions:

  • Per-key limits cap a single agent. Kong’s rate-limiting plugin supports second, minute, hour, day counters; LiteLLM supports rpm_limit and tpm_limit per virtual key.
  • Per-tool limits cap individual routes—your payment API gets a tighter budget than your search API. In Kong, attach different rate-limiting configs per route.
  • Burst vs. sustained. Allow short bursts (e.g., 30 requests/minute with a 5-second window for spikes) but enforce daily caps that stop runaway loops cold. LiteLLM’s budget_duration handles the calendar-level quota.

On the agent side, treat 429 as a first-class signal: exponential backoff with jitter, and a hard retry ceiling. An agent that blindly retries a 429 in a tight loop is exactly the misbehavior the gateway exists to contain—so build the backoff into your orchestration code, not the model’s judgment.

Audit Logging Every Tool Call

The audit trail is where a gateway earns its keep. Kong ships structured logs with the http-log or file-log plugin:

plugins:
  - name: http-log
    config:
      http_endpoint: http://siem-local:8080/agent-audit

LiteLLM logs via callbacks—langfuse, otel, or a custom hook posting to your collector.

Whatever the transport, each log entry should carry: who (agent identity/key ID), what (tool/route invoked), when (UTC timestamp), outcome (status code), quota state (remaining budget/limit headers), and a payload hash plus sanitized metadata (argument names, sizes—not raw payloads, which may contain secrets or PII). Ship these to a local SIEM—Wazuh or Graylog run fine on-prem—and alert on anomalies: a key suddenly hitting a tool it never touched, or sustained 403s (that’s an injection attempt being blocked, and you want to know about it).

Testing the Gateway: Red-Team Your Own Agent

Treat the gateway like any other security control and attack it. CTF-style test cases:

  1. Forged tool call. Craft a prompt-injected request that attempts run_sql from a key scoped to search_kb. Expected: 403 (Kong ACL) or callback rejection (LiteLLM); a 403 line in the audit log.
  2. Missing/invalid credential. Call the gateway with no apikey header. Expected: 401 from key-auth, logged.
  3. Over-limit burst. Fire 60 rapid requests at a 30/minute route. Expected: 30 successes, then 429s with X-RateLimit-Remaining-Minute: 0; the agent’s backoff kicks in.
  4. Budget exhaustion. Drain a LiteLLM virtual key’s budget. Expected: 401 Quota exceeded (or 429) with no model call billed.
  5. Direct tool bypass. Hit tool-api:5678 directly, skipping the gateway. Expected: connection refused—verify your network policy actually enforces gateway-only access, or everything above is theater.

If test five succeeds, fix the network segmentation before anything else.

Hardening Tips and Common Mistakes

  • TLS everywhere. Even locally, terminate TLS at the gateway and use mTLS or a private network for gateway-to-tool traffic. Plaintext agent-to-gateway traffic leaks keys to anything on the host.
  • Rotate secrets. Agent keys in environment variables or a vault—not hardcoded. LiteLLM keys can be regenerated without redeploying the agent; use that.
  • Never trust prompt-derived tool arguments. The gateway authorizes which tool; validate argument shape, ranges, and authorization scope (can this agent touch this record ID?) at the tool API itself. Gateways authorize tools; tools must still authorize data.
  • Keep allowlists minimal. Every tool you grant “just in case” is injection surface. Revoke ruthlessly.
  • Log before you block, but block. Detection-only gateways are audit tools, not security tools.

Frequently Asked Questions

Can I run the gateway fully offline/local?

Yes. Both Kong and LiteLLM run entirely on-premises or in local Docker; the only external dependency is your LLM endpoint—and if that’s Ollama or vLLM on the same host, the whole stack is airgap-ready.

Kong vs LiteLLM: which is better for agent gateways?

Kong for mature API-gateway features—plugin ecosystem, ACLs, mTLS, deep observability—in front of your tool APIs. LiteLLM for LLM-native controls: token budgets, virtual keys, per-model and per-tool scoping in front of model endpoints. Serious deployments run LiteLLM in front of models and Kong in front of tools.

How do I stop prompt injection from triggering unauthorized tools?

Deny-by-default allowlists enforced at the gateway, not in the prompt. If the agent’s credentials can’t reach a tool, no injection payload changes that. Filter the tool definitions in the prompt to match, so the model never sees forbidden tools.

How granular can rate limits be?

Per API key/consumer, per route/tool, and per second/minute/hour/day window, with burst controls. Kong enforces per-route plugin configs; LiteLLM enforces RPM/TPM per virtual key plus USD budgets per day/week/month.

What should agent audit logs contain?

Identity (key/consumer ID), tool called, timestamp, status code, quota state, and sanitized payload metadata—argument names and hashes, not raw content. Enough to reconstruct an incident without storing secrets in your SIEM.

HMMNM Security · Independent security research and education · hmmnm.com
Printed from https://hmmnm.com/build-a-local-ai-agent-gateway-auth-rate-limits-and-tool-allowlists-with-kong-or-litellm/
© 2026 HMMNM Security. For personal and internal team use. Please link to the original article when sharing.