Skip to content
Latest (currently 2026.10.2) has the newest features, bug fixes, and CVE patches of Solo Enterprise for agentgateway.

For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.

Virtual keys

Page as Markdown

Issue API keys with per-key token budgets and cost tracking (also known as virtual keys).

Keep provider API keys on the gateway and give each client a revocable virtual key. Add token budgets and usage tracking as needed.

About

Clients use virtual keys to authenticate to agentgateway. The proxy replaces each virtual key with the provider key stored in a Kubernetes Secret before forwarding the request. Clients never receive the provider key, and the provider never receives the virtual key.

Each client has its own key, so you can revoke one client’s access without rotating the provider key or reconfiguring other clients. Provider-key rotation happens in the cluster.

How virtual keys work

    sequenceDiagram
    participant C as Client<br/>(holds a virtual key)
    participant AGW as Agentgateway<br/>(holds the provider key)
    participant P as LLM provider
    C->>AGW: Request with the virtual key
    AGW->>AGW: Validate the key and check model access
    AGW->>AGW: Replace the virtual key with the provider key
    AGW->>P: Request with the provider key
    P-->>AGW: Response
    AGW-->>C: Response
  

Security considerations

All clients depend on the provider key in the Secret. Protect it as you would any other production credential.

  • Restrict who can read the Secret. Limit the Kubernetes RBAC permissions to read Secrets in the namespace of the EnterpriseAgentgatewayBackend.
  • Encrypt client traffic. Virtual keys are bearer credentials. Serve clients over HTTPS, or keep the Gateway on a private network.
  • Keep agentgateway up to date with security patches.
  • Multiple policies: Keep authentication, model authorization, and rate limits in the same policy when they target the same Gateway. Separate policies can overwrite one another even when both report ACCEPTED/ATTACHED.

Before you begin

  1. Set up an agentgateway proxy.
  2. Set up access to the OpenAI LLM provider.

The OpenAI provider guide stores the provider key in openai-secret. For other ways to provide it, see Provider API keys.

Set up virtual keys

Create virtual keys for Alice and Bob, configure authentication, and verify their access. This setup does not require a rate limit server. Complete the following steps in order.

Create API keys for users

Store a SHA-256 hash of each virtual key in a ConfigMap. The proxy hashes each incoming key and compares it to the stored hash. You do not need to store raw virtual keys in the cluster.

  1. Generate a hash for each virtual key. This example creates keys for Alice and Bob. Do not include a trailing newline.

    printf '%s' 'vk-alice-4f9c2a' | sha256sum | awk '{print "sha256:"$1}'   # alice
    printf '%s' 'vk-bob-8d1e7b' | sha256sum | awk '{print "sha256:"$1}'     # bob
  2. Create a ConfigMap with the hash and metadata of each key. The label lets the authentication policy in the next step select the ConfigMap.

    kubectl apply -f- <<EOF
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: llm-api-keys
      namespace: agentgateway-system
      labels:
        agentgateway.dev/apikey: "true"
    data:
      alice: |
        {
          "keyHash": "sha256:84d589f2439e4d9ff4438aa840e63ffcbf231a87e7fef929f975d2bde03dc78c",
          "metadata": {
            "user_id": "alice"
          }
        }
      bob: |
        {
          "keyHash": "sha256:8373319fb10e2e023343d98ade630529f49c53f567cbc6626d09aaf650b2e58c",
          "metadata": {
            "user_id": "bob"
          }
        }
    EOF

Review the following table to understand this configuration.

SettingDescription
metadata.labelsThe label that the authentication policy uses to select the ConfigMap.
data.<name>One JSON entry per user, with a keyHash and optional metadata.
keyHashA SHA-256 hash in sha256:<hex> format. Clients send the raw key in the Authorization: Bearer <key> header.
metadata.user_idThe user identifier that budget and metrics policies read as apiKey.user_id.

Tip

ConfigMaps with hashed keys are the recommended storage format. If you already store keys in Secrets, use agctl migrate to convert them, or see API key authentication for Secret-based configuration.

Configure API key authentication

Create an EnterpriseAgentgatewayPolicy that requires API key authentication for all requests to the gateway. Unlike Secrets, which you can reference directly by name, ConfigMaps can be selected only by label. Use configMapSelector to match every ConfigMap that carries the label you added in the previous step, whether that is a single ConfigMap or several.

kubectl apply -f- <<EOF
apiVersion: enterpriseagentgateway.solo.io/v1alpha1
kind: EnterpriseAgentgatewayPolicy
metadata:
  name: api-key-auth
  namespace: agentgateway-system
spec:
  targetRefs:
    - group: gateway.networking.k8s.io
      kind: Gateway
      name: agentgateway-proxy
  traffic:
    apiKeyAuthentication:
      mode: Strict
      configMapSelector:
        matchLabels:
          agentgateway.dev/apikey: "true"
EOF

Review the following table to understand this configuration.

SettingDescription
targetRefsApply the policy to the entire Gateway so all routes require API keys.
apiKeyAuthentication.modeSet to Strict to require a valid API key for all requests.
configMapSelector.matchLabelsSelects all ConfigMaps that carry the given labels, combining their keys. Every entry in a selected ConfigMap must use keyHash; a raw key value is rejected because ConfigMaps are not confidential.

Set up an LLM backend

Create an EnterpriseAgentgatewayBackend that connects to your LLM provider.

kubectl apply -f- <<EOF
apiVersion: enterpriseagentgateway.solo.io/v1alpha1
kind: EnterpriseAgentgatewayBackend
metadata:
  name: openai
  namespace: agentgateway-system
spec:
  ai:
    provider:
      openai: {}
        # Optional: specify a default  model
        #model: gpt-3.5-turbo
     # Optional: custom host and port, if needed
     # host: api.openai.com  
     # port: 443
  policies:
    auth:
      secretRef:
        name: openai-secret
    ai:
      routes:
        "/v1/responses": "Responses"
        "/v1/chat/completions": "Completions"
        "/v1/models": "Models"          # also silences Codex's model-metadata probe
        "*": "Passthrough"
EOF

For detailed instructions on creating backends and storing provider API keys, see the API keys guide.

Create a route to the backend

Create an HTTPRoute that forwards all paths to the OpenAI EnterpriseAgentgatewayBackend. Clients can use the standard /v1/chat/completions path.

kubectl apply -f- <<EOF
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: openai
  namespace: agentgateway-system
spec:
  parentRefs:
    - name: agentgateway-proxy
      namespace: agentgateway-system
  rules:
    - backendRefs:
        - name: openai
          namespace: agentgateway-system
          group: enterpriseagentgateway.solo.io
          kind: EnterpriseAgentgatewayBackend
EOF

Test the virtual keys

Verify that a valid key succeeds and an unknown key gets a 401 response. No token budget is configured yet.

  1. Send a request with Alice’s API key. Verify that the request succeeds.

    curl "$INGRESS_GW_ADDRESS/v1/chat/completions" \
      -H "Authorization: Bearer vk-alice-4f9c2a" \
       -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello!"}]
      }'
    curl "localhost:8080/v1/chat/completions" \
      -H "Authorization: Bearer vk-alice-4f9c2a" \
       -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello!"}]
      }'

    Example successful response:

    {
      "id": "chatcmpl-abc123",
      "object": "chat.completion",
      "created": 1234567890,
      "model": "gpt-3.5-turbo",
      "choices": [{
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Hello! How can I help you today?"
        },
        "finish_reason": "stop"
      }],
      "usage": {
        "prompt_tokens": 10,
        "completion_tokens": 9,
        "total_tokens": 19
      }
    }
  2. Send a request with an unknown key. Verify that the proxy returns 401.

    curl -s -o /dev/null -w "%{http_code}\n" "$INGRESS_GW_ADDRESS/v1/chat/completions" \
      -H "Authorization: Bearer vk-unknown" \
      -H "Content-Type: application/json" \
      -d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}]}'

    Expected response:

    401

Configure other clients with the Gateway base URL, such as http://$INGRESS_GW_ADDRESS/v1, and their virtual key. See LLM clients for client-specific settings.

Manage client access

Choose a task to restrict model access, revoke a client key, or rotate provider credentials.

Restrict model access

By default, a key can request any model the provider offers.

  1. Add an authorization rule to the existing api-key-auth policy. Include the model used by this guide.

    kubectl patch EnterpriseAgentgatewayPolicy api-key-auth -n agentgateway-system \
      --type=merge --patch-file=/dev/stdin <<'EOF'
    spec:
      traffic:
        authorization:
          action: Require
          policy:
            matchExpressions:
              - 'request.method != "POST" || json(request.body).model in ["gpt-3.5-turbo", "gpt-4o-mini", "gpt-4o"]'
    EOF

    The rule allows POST requests only for listed models. Other methods, such as GET to list models, are allowed. To set access per user, combine the model expression with a metadata check such as apiKey.user_id == "bob".

  2. Request an unlisted model, such as o3. Verify that the proxy returns 403.

    curl -s -w "\n%{http_code}\n" "$INGRESS_GW_ADDRESS/v1/chat/completions" \
      -H "Authorization: Bearer vk-alice-4f9c2a" \
      -H "Content-Type: application/json" \
      -d '{"model": "o3", "messages": [{"role": "user", "content": "Hello!"}]}'

    Example output:

    authorization failed
    403

Revoke a virtual key

Revoke one client’s access without restarting the proxy or changing other keys.

  1. Remove Bob’s entry from the ConfigMap.

    kubectl patch configmap llm-api-keys -n agentgateway-system \
      --type=json -p='[{"op": "remove", "path": "/data/bob"}]'
  2. Send a request with Bob’s key. Verify that the proxy returns 401.

    curl -s -o /dev/null -w "%{http_code}\n" "$INGRESS_GW_ADDRESS/v1/chat/completions" \
      -H "Authorization: Bearer vk-bob-8d1e7b" \
      -H "Content-Type: application/json" \
      -d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}]}'
  3. To continue with the budget examples, restore Bob’s key by reapplying the ConfigMap from Create API keys for users.

Rotate a provider key

Replace the provider credential in the cluster. Clients keep their virtual keys.

  1. Follow Rotate a provider key to replace the credential and revoke the old provider key.
  2. Send a request with an existing virtual key. Verify that it still succeeds.

Configure token budgets

Token budgets are optional. Continue here to give Alice and Bob independent daily budgets, shared across proxy replicas. This example uses only 100 tokens per day so that you can test enforcement quickly.

Rate limiting runs before prompt guards, so requests rejected by those guards can still consume quota. Requests rejected during authentication do not consume a token budget.

Configure per-key token budgets

  1. Create a RateLimitConfig resource that defines the per-user token budget. It extracts the user_id from each API key and counts the token usage of each response against that user’s budget (100 tokens per day per user).

    kubectl apply -f- <<EOF
    apiVersion: ratelimit.solo.io/v1alpha1
    kind: RateLimitConfig
    metadata:
      name: daily-token-budget
      namespace: agentgateway-system
    spec:
      raw:
        descriptors:
        - key: user_id
          rateLimit:
            unit: DAY
            requestsPerUnit: 100
        rateLimits:
        - actions:
          - cel:
              expression: 'apiKey.user_id'
              key: "user_id"
          type: TOKEN
    EOF

    Review the following table to understand this configuration.

    SettingDescription
    RateLimitConfigDefines the rate limit rules that the built-in enterprise rate limit service enforces. No external Redis or rate limit server is required.
    descriptors[].keyThe descriptor key (user_id) that the budget is tracked by. Must match the key set in the rate limit action.
    descriptors[].rateLimitThe budget for each unique descriptor value. This example sets 100 tokens (requestsPerUnit) per DAY per user.
    rateLimits[].actions[].celA CEL expression that extracts the user_id from each API key’s metadata and assigns it to the user_id descriptor key. CEL expressions must evaluate to a string and are supported only by the Solo Enterprise for agentgateway data plane.
    rateLimits[].typeSet to TOKEN so the gateway counts each response’s token usage as the cost. Use REQUEST to count requests instead.
  2. Update the api-key-auth EnterpriseAgentgatewayPolicy from the previous step to also enforce the token budget by referencing the RateLimitConfig. Keep authentication and rate limiting in the same policy: when two policies target the same Gateway, one silently overwrites the other, so a separate rate limit policy would never take effect.

    kubectl apply -f- <<EOF
    apiVersion: enterpriseagentgateway.solo.io/v1alpha1
    kind: EnterpriseAgentgatewayPolicy
    metadata:
      name: api-key-auth
      namespace: agentgateway-system
    spec:
      targetRefs:
        - group: gateway.networking.k8s.io
          kind: Gateway
          name: agentgateway-proxy
      traffic:
        apiKeyAuthentication:
          mode: Strict
    
          configMapSelector:
            matchLabels:
              agentgateway.dev/apikey: "true"
    
        entRateLimit:
          global:
            rateLimitConfigRefs:
            - name: daily-token-budget
    EOF

    Note

    This example keeps the configMapSelector authentication from the previous step. If you selected your API keys differently, such as with secretSelector, keep that block instead.

    Review the following table to understand this configuration.

    SettingDescription
    apiKeyAuthenticationThe API key authentication from the previous step. Keeping it in the same policy as the rate limit avoids the silent conflict that occurs when two policies target the same Gateway.
    entRateLimit.global.rateLimitConfigRefsAttaches one or more RateLimitConfig resources to the Gateway. The built-in enterprise rate limit service enforces their rules. Replaces the open source rateLimit.global.backendRef.

Deploy the rate limit server

Solo Enterprise for agentgateway includes a built-in global rate limit service (the rate-limiter shared extension) backed by an in-cluster Redis cache (the ext-cache-enterprise-agentgateway extension), both deployed by default. You do not need to bring your own Redis or rate limit service.

Because the per-user token budget is defined in the RateLimitConfig that you applied in the previous step, there is nothing else to deploy. The built-in rate limit service reads the RateLimitConfig, tracks each user’s token usage, and rejects requests with a 429 status code when a user exceeds their daily budget.

To point the built-in rate limiter at your own Redis deployment instead of the bundled one, see the global rate limiting guide.

Verify budget enforcement

  1. Send requests with Alice’s API key until her 100-token daily budget is exhausted. Because the LLM provider returns roughly 20-30 tokens per response, a handful of requests pushes Alice over the budget. The request that crosses the budget still completes; subsequent requests are rejected with a 429 status code.

    for i in $(seq 1 10); do
      STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
        "$INGRESS_GW_ADDRESS/v1/chat/completions" \
        -H "Authorization: Bearer vk-alice-4f9c2a" \
        -H "Content-Type: application/json" \
        -d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello!"}]}')
      echo "Request $i: HTTP $STATUS"
    done

    Example 429 response:

    HTTP/1.1 429 Too Many Requests
    x-ratelimit-limit: 100
    x-ratelimit-remaining: 0
    x-ratelimit-reset: 43200
    
    rate limit exceeded
  2. Verify that Bob can still send requests with his own budget, independent of Alice’s usage.

    curl "$INGRESS_GW_ADDRESS/v1/chat/completions" \
      -H "Authorization: Bearer vk-bob-8d1e7b" \
       -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello!"}]
      }'
    curl "localhost:8080/v1/chat/completions" \
      -H "Authorization: Bearer vk-bob-8d1e7b" \
       -H "Content-Type: application/json" \
      -d '{
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "user", "content": "Hello!"}]
      }'

    Bob’s requests succeed because he has his own independent budget.

Monitor per-key spending

Usage tracking is optional and does not require a token budget. Add per-user labels to Prometheus metrics to attribute token usage and estimate spending.

By default, the agentgateway token usage metric (agentgateway_gen_ai_client_token_usage) is broken down by dimensions such as the model and token type, but not by user. To attribute usage to each virtual key, add a user_id label to the metrics with a metrics policy, then query Prometheus.

Note

The token usage metric only appears after a request succeeds and the LLM returns a usage count. Requests that are rejected (for example, a 401 from an invalid key or a 429 from the rate limit) never reach the LLM, so they do not produce token usage metrics.

Before you begin

Set up a Prometheus instance to scrape agentgateway metrics, such as by completing the OpenTelemetry stack guide. The following steps assume the kube-prometheus-stack release exists in the telemetry namespace, as deployed by that guide.

Add a per-key metric label

You can add a per-key metric label such as to track metrics by user ID. Note that the user_id label is high cardinality: every unique value creates a new metric series, which increases Prometheus memory and storage. This is acceptable for tens or hundreds of keys, but avoid attaching unbounded identifiers at large scale. Prefer lower-cardinality dimensions like tier or team when possible.

  1. Update the existing api-key-auth policy to add the key’s user_id as a Prometheus label. The merge patch keeps authentication, model restrictions, and any budgets already configured on the Gateway.

    kubectl patch EnterpriseAgentgatewayPolicy api-key-auth -n agentgateway-system \
      --type=merge --patch-file=/dev/stdin <<'EOF'
    spec:
      frontend:
        metrics:
          attributes:
            add:
              - name: user_id
                expression: 'apiKey.user_id'
    EOF

    Review the following table to understand this configuration.

    SettingDescription
    frontend.metrics.attributes.add[].nameThe name of the Prometheus label to add (user_id).
    frontend.metrics.attributes.add[].expressionA CEL expression that is evaluated per request. Use apiKey.user_id to read the user_id from the authenticated API key. If the expression fails to evaluate (for example, on an unauthenticated request), the label value is set to unknown.
  2. Send a few requests with each virtual key so that the metrics have per-user data to report. You can reuse the requests from Test the virtual keys.

Query per-key usage

  1. Port-forward the Prometheus server from the OpenTelemetry stack.

    kubectl port-forward -n telemetry svc/kube-prometheus-stack-prometheus 9090:9090

    Then open the Prometheus UI at http://localhost:9090/graph and run the following queries, or send them to the HTTP API with curl. For example:

    curl -s http://localhost:9090/api/v1/query \
      --data-urlencode 'query=sum by (user_id) (agentgateway_gen_ai_client_token_usage_sum)'

    Example output:

    {"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1782410561.391,"720"]},{"metric":{"user_id":"bob"},"value":[1782410561.391,"448"]},{"metric":{"user_id":"alice"},"value":[1782410561.391,"448"]}]}}
  2. Query token usage broken down by user ID. The token usage metric carries a separate series per token type (input, output, input_cache_read), so match both the input and output types in a single selector and sum them, rather than adding two selectors together.

    # Total tokens consumed by user over the last 24 hours
    sum by (user_id) (
      increase(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=~"input|output"}[24h])
    )
    
    # Percentage of a 100-token daily budget used (adjust the divisor to match your budget)
    (sum by (user_id) (
      increase(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=~"input|output"}[24h])
    ) / 100) * 100
    curl -s http://localhost:9090/api/v1/query \
      --data-urlencode 'query=sum by (user_id) (increase(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=~"input|output"}[24h]))'
    curl -s http://localhost:9090/api/v1/query \
      --data-urlencode 'query=(sum by (user_id) (increase(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=~"input|output"}[24h])) / 100) * 100'

    Each result series is labeled with a user_id, such as alice and bob. If a key is missing the user_id field, or the request is not attributed to a key, its usage appears under user_id="unknown".

    Example output:

    {"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1782411002.488,"0"]},{"metric":{"user_id":"bob"},"value":[1782411002.488,"372.2787929364588"]},{"metric":{"user_id":"alice"},"value":[1782411002.488,"309.56920815395927"]}]}}
    
    {"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1782411059.867,"0"]},{"metric":{"user_id":"bob"},"value":[1782411059.867,"370.95800165527817"]},{"metric":{"user_id":"alice"},"value":[1782411059.867,"307.9427844448483"]}]}}

    Note

    increase() and rate() need at least two samples within the time range to report a value, so a brand-new user_id series shows no result until it has been scraped a few times under continuous traffic. For a quick instant check, query the cumulative counter directly: sum by (user_id) (agentgateway_gen_ai_client_token_usage_sum).

  3. Calculate costs per user by multiplying token counts by your provider’s pricing. Input and output tokens are usually priced differently, so reduce each token type to a per-user series with sum by (user_id) before adding them, which keeps the two sides matchable.

    # Cost per user (assuming $0.50 per 1M input tokens, $1.50 per 1M output tokens)
    sum by (user_id) (rate(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type="input"}[24h])) / 1000000 * 0.50
    +
    sum by (user_id) (rate(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type="output"}[24h])) / 1000000 * 1.50
    curl -s http://localhost:9090/api/v1/query \
      --data-urlencode 'query=sum by (user_id) (rate(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type="input"}[24h])) / 1000000 * 0.50 + sum by (user_id) (rate(agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type="output"}[24h])) / 1000000 * 1.50'

    Example output:

    {"status":"success","data":{"resultType":"vector","result":[{"metric":{},"value":[1782410758.432,"0"]},{"metric":{"user_id":"bob"},"value":[1782410758.432,"6.101636101191084e-09"]},{"metric":{"user_id":"alice"},"value":[1782410758.432,"5.106526900820178e-09"]}]}}

For more information on cost tracking, see the cost tracking guide.

Advanced configuration

For tiered, hourly, and multi-tenant token budgets, see Advanced per-key budgets.

Cleanup

You can remove the resources that you created in this guide.
kubectl delete EnterpriseAgentgatewayPolicy api-key-auth -n agentgateway-system --ignore-not-found
kubectl delete configmap llm-api-keys -n agentgateway-system --ignore-not-found
kubectl delete secret llm-api-keys -n agentgateway-system --ignore-not-found
kubectl delete httproute openai -n agentgateway-system
kubectl delete EnterpriseAgentgatewayBackend openai -n agentgateway-system

To remove the rate limit server, follow the cleanup steps in the global rate limiting guide.

Create virtual keys in the Solo UI

Instead of writing the API key Secret by hand, admins can issue virtual keys from the Virtual Keys page of the Solo UI.

Before you begin, install the Solo UI with the Cost Management feature enabled.

  1. Open the Solo UI and select Virtual Keys from the menu, then click Create Virtual API Key.

  2. Fill out the key details.

    • Key ID: A unique identifier for the key, such as carol. This value is what the virtualKey budget dimension resolves to.
    • Key Set: The Kubernetes Secret that the key is stored in. The Secret is created if it does not exist, and is labeled so that gateway API key authentication policies can select it with a secretSelector.
    • Metadata: The user and group attribution fields are required. Add more metadata pairs for any custom budget dimensions that you configured.
  3. Click Create Virtual API Key, then copy the generated key value. For security, the raw key is shown only once and cannot be retrieved later. If the key is lost, delete it and create a new one.

  4. Review your keys on the Virtual Keys page. The list shows read-only metadata such as the group and user that each key’s traffic is attributed to. Raw key values are not exposed.

After a key is created, spend for its traffic is attributed on the Cost Management dashboard, and you can scope budgets to it with a virtualKey subject.