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.

OPA with Rego rules in config maps

Page as Markdown

Enforce Open Policy Agent (OPA) policies with Rego rules in Kubernetes config maps.

The Solo Enterprise for agentgateway external auth service can use an embedded OPA engine to enforce Rego rules stored in Kubernetes config maps. You create an AuthConfig resource that references the config map, and the external auth service loads and evaluates the rules on each request. No standalone OPA deployment is required.

This guide walks through two examples that share a single Rego policy:

  • Protect a large language model (LLM) route: Authorize requests to an OpenAI-backed AgentgatewayBackend based on an api-key request header. On allow, inject an upstream header and strip the api-key before forwarding. On deny, return a 403 with a custom body and a custom client response header.
  • Protect a Model Context Protocol (MCP) route: Reuse the same AuthConfig to protect an MCP route. The same Rego policy returns the same allow/deny decisions for the initialize, notifications/initialized, and tools/list MCP methods.

About

When a request matches a route that references an AuthConfig with embedded OPA, the agentgateway proxy asks the Solo Enterprise for agentgateway external auth service to authorize the request. The external auth service runs the Rego query against the policy loaded from the config map and returns an allow or deny decision. The proxy either forwards the request to the upstream backend or rejects it with the configured response.

    sequenceDiagram
    participant Client
    participant GW as agentgateway proxy
    participant EA as Ext-auth (embedded OPA)
    participant UP as Upstream

    Client->>GW: HTTP request to protected route
    GW->>EA: gRPC Check()
    Note over EA: Evaluate Rego from config map
    EA-->>GW: Allow or deny decision
    alt Allow
        GW->>UP: Forward request
        UP-->>GW: Response
        GW-->>Client: Forwarded response
    else Deny
        GW-->>Client: Reject response
    end
  

Before you begin

Follow the quick starts or the following guides to:

  1. Set up an agentgateway proxy.
  2. Set up an LLM provider, such as OpenAI.
  3. Set up an MCP backend such as mcp-website-fetcher in the agentgateway-system namespace. The MCP example reuses this backend.

Create the Rego policy

Create a Rego policy and store it in a Kubernetes config map. The Solo Enterprise for agentgateway external auth service loads the policy through its embedded OPA engine.

The following policy denies all requests by default and allows requests that include a specific api-key header. Both branches return a structured result object that controls the HTTP response. The default rule is the deny branch, and the allow rule overrides it when the header matches.

kubectl apply -f- <<EOF
apiVersion: v1
kind: ConfigMap
metadata:
  name: llm-opa-policy
  namespace: agentgateway-system
data:
  policy.rego: |-
    package llm_authz
    import future.keywords.if

    # Default: deny with 403 + custom body + response header
    default rule := {
      "allow": false,
      "response_headers_to_add": {"x-opa-decision": "denied"},
      "request_headers_to_remove": ["api-key"],
      "body": "Access denied: missing or invalid API key",
      "http_status": 403,
    }

    # Allow when api-key matches; inject upstream header, strip api-key
    rule := result if {
      input.http_request.headers["api-key"] == "authorized-user-key"
      result := {
        "allow": true,
        "http_status": 200,
        "headers": {"x-validated-by": "opa-security-checkpoint"},
        "response_headers_to_add": {"x-opa-decision": "allowed"},
        "request_headers_to_remove": ["api-key"],
      }
    }
EOF

Review the following table to understand the OPA result-object fields used in this policy. The external auth service interprets these field names directly.

Review the following table to understand this configuration.
FieldDescription
allowRequired. true to forward the request; false to reject it.
http_statusThe HTTP status code returned to the client. Set on both allow (200) and deny (403) so the response status is explicit.
bodyThe response body returned to the client on deny.
headersHeaders added to the upstream request on allow. Use this to inject context for the backend, such as a proof-of-authorization header.
response_headers_to_addHeaders added to the response sent to the client. Useful for surfacing the OPA decision to the caller or to downstream filters.
request_headers_to_removeHeaders stripped from the request before it is forwarded upstream. Use this to remove credentials such as the api-key so they do not leak to the LLM provider.

Note

If you modify this policy, keep the package llm_authz declaration. The query field in the AuthConfig that you create next references this package.

Create the AuthConfig

Create an AuthConfig resource that loads the config map as an OPA module and points at the Rego rule to evaluate.

kubectl apply -f- <<EOF
apiVersion: extauth.solo.io/v1
kind: AuthConfig
metadata:
  name: llm-opa
  namespace: agentgateway-system
spec:
  configs:
  - opaAuth:
      modules:
      - name: llm-opa-policy
        namespace: agentgateway-system
      query: data.llm_authz.rule
EOF

Review the following table to understand this configuration.

SettingDescription
opaAuthConfigures the embedded OPA engine in the external auth service. Use this option to load Rego rules from one or more config maps in the cluster.
modulesA list of references to Kubernetes config maps that contain Rego rules. Each entry takes a name and a namespace.
queryThe Rego query that the external auth service evaluates on each request. The query path is data.<package>.<rule>. The example references the rule rule in the llm_authz package from the config map.

Verify that the AuthConfig is in the Accepted state.

kubectl get authconfig llm-opa -n agentgateway-system -o jsonpath='{.status.state}'

Example output:

Accepted

Protect an LLM route

This example attaches the AuthConfig to an HTTPRoute that fronts an OpenAI AgentgatewayBackend. Requests without the expected api-key header are denied with a 403 response. Requests with the correct header are forwarded to OpenAI with an x-validated-by header injected upstream and the api-key header stripped.

  1. Create the OpenAI AgentgatewayBackend and an HTTPRoute that exposes it on the /openai path. Replace the Authorization data value with your LLM provider’s API key.

    kubectl apply -f- <<EOF
    apiVersion: v1
    kind: Secret
    metadata:
      name: openai-secret
      namespace: agentgateway-system
    type: Opaque
    stringData:
      Authorization: "Bearer $OPENAI_API_KEY"
    ---
    apiVersion: agentgateway.dev/v1alpha1
    kind: AgentgatewayBackend
    metadata:
      name: openai
      namespace: agentgateway-system
    spec:
      ai:
        provider:
          openai:
            model: gpt-4o-mini
      policies:
        auth:
          secretRef:
            name: openai-secret
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: openai
      namespace: agentgateway-system
    spec:
      parentRefs:
      - name: agentgateway-proxy
        namespace: agentgateway-system
      rules:
      - matches:
        - path:
            type: PathPrefix
            value: /openai
        backendRefs:
        - name: openai
          namespace: agentgateway-system
          group: agentgateway.dev
          kind: AgentgatewayBackend
    EOF
  2. Create an EnterpriseAgentgatewayPolicy that attaches the AuthConfig to the OpenAI HTTPRoute. The policy uses the entExtAuth field, which sends each request through the provisioned external auth service. No backendRef is required.

    kubectl apply -f- <<EOF
    apiVersion: enterpriseagentgateway.solo.io/v1alpha1
    kind: EnterpriseAgentgatewayPolicy
    metadata:
      name: llm-opa-policy
      namespace: agentgateway-system
    spec:
      targetRefs:
      - group: gateway.networking.k8s.io
        kind: HTTPRoute
        name: openai
      traffic:
        entExtAuth:
          authConfigRef:
            name: llm-opa
            namespace: agentgateway-system
    EOF
  3. Configure how to reach the agentgateway-proxy from your workstation.

    export INGRESS_GW_ADDRESS=$(kubectl get gateway agentgateway-proxy \
      -n agentgateway-system -o jsonpath='{.status.addresses[0].value}')
    kubectl port-forward deployment/agentgateway-proxy -n agentgateway-system 8080:80

    Keep this command running in its own terminal session. Use another terminal for the curl commands in the following steps, and choose the Local host tab each time.

  4. Send a request to the OpenAI route without the api-key header. Verify that the request is denied with a 403 response, the custom body, and the x-opa-decision: denied response header.

    curl -i $INGRESS_GW_ADDRESS/openai \
      -H "Content-Type: application/json" \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"hi"}],"max_tokens":5}'
    curl -i http://localhost:8080/openai \
      -H "Content-Type: application/json" \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"hi"}],"max_tokens":5}'

    Example output:

    HTTP/1.1 403 Forbidden
    x-opa-decision: denied
    content-length: 41
    
    Access denied: missing or invalid API key
  5. Send the same request with the expected api-key header. Verify that the request is allowed, that the x-opa-decision: allowed response header is added, and that OpenAI returns a chat completion. Inside the gateway, the api-key header is stripped and the x-validated-by: opa-security-checkpoint header is injected before the request is forwarded to OpenAI.

    curl -i $INGRESS_GW_ADDRESS/openai \
      -H "Content-Type: application/json" \
      -H "api-key: authorized-user-key" \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hi"}],"max_tokens":5}'
    curl -i http://localhost:8080/openai \
      -H "Content-Type: application/json" \
      -H "api-key: authorized-user-key" \
      -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hi"}],"max_tokens":5}'

    Example output:

    HTTP/1.1 200 OK
    content-type: application/json
    openai-organization: ...
    x-opa-decision: allowed
    
    {"choices":[{"message":{"role":"assistant","content":"Hello!"}, ...}], ...}

Protect an MCP route

The same AuthConfig can protect MCP routes. This example reuses the llm-opa AuthConfig and creates a separate EnterpriseAgentgatewayPolicy that targets an MCP HTTPRoute.

  1. Create an AgentgatewayBackend for an MCP server such as mcp-website-fetcher, and an HTTPRoute that exposes it on the /mcp path.

    kubectl apply -f- <<EOF
    apiVersion: agentgateway.dev/v1alpha1
    kind: AgentgatewayBackend
    metadata:
      name: mcp
      namespace: agentgateway-system
    spec:
      mcp:
        targets:
        - name: mcp-website-fetcher
          static:
            host: mcp-website-fetcher.agentgateway-system.svc.cluster.local
            port: 80
            protocol: SSE
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: HTTPRoute
    metadata:
      name: mcp
      namespace: agentgateway-system
    spec:
      parentRefs:
      - name: agentgateway-proxy
        namespace: agentgateway-system
      rules:
      - matches:
        - path:
            type: PathPrefix
            value: /mcp
        backendRefs:
        - name: mcp
          namespace: agentgateway-system
          group: agentgateway.dev
          kind: AgentgatewayBackend
    EOF
  2. Attach the same AuthConfig from the Protect an LLM route example to the MCP HTTPRoute by creating a second EnterpriseAgentgatewayPolicy that targets the MCP HTTPRoute.

    kubectl apply -f- <<EOF
    apiVersion: enterpriseagentgateway.solo.io/v1alpha1
    kind: EnterpriseAgentgatewayPolicy
    metadata:
      name: mcp-opa-policy
      namespace: agentgateway-system
    spec:
      targetRefs:
      - group: gateway.networking.k8s.io
        kind: HTTPRoute
        name: mcp
      traffic:
        entExtAuth:
          authConfigRef:
            name: llm-opa
            namespace: agentgateway-system
    EOF
  3. Send an initialize request to the MCP route without the api-key header. Verify that the request is denied with a 403 response.

    curl -i $INGRESS_GW_ADDRESS/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -d '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}'
    curl -i http://localhost:8080/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -d '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}'

    Example output:

    HTTP/1.1 403 Forbidden
    x-opa-decision: denied
    
    Access denied: missing or invalid API key
  4. Send the initialize request with the expected api-key header. Verify that the request is allowed, an mcp-session-id response header is returned, and the MCP server reports its capabilities. Save the mcp-session-id for subsequent requests.

    HEADERS=$(mktemp)
    curl -D "$HEADERS" $INGRESS_GW_ADDRESS/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}'
    
    SESSION=$(grep -i "mcp-session-id" "$HEADERS" | awk '{print $2}' | tr -d '\r')
    HEADERS=$(mktemp)
    curl -D "$HEADERS" http://localhost:8080/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}},"id":1}'
    
    SESSION=$(grep -i "mcp-session-id" "$HEADERS" | awk '{print $2}' | tr -d '\r')

    Example output:

    HTTP/1.1 200 OK
    content-type: text/event-stream
    mcp-session-id: <session-id>
    x-opa-decision: allowed
    
    data: {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{...},"serverInfo":{"name":"mcp-website-fetcher", ...}}}
  5. Send the notifications/initialized notification, then list the tools that the MCP server exposes. Both requests must include the api-key and Mcp-Session-Id headers.

    curl $INGRESS_GW_ADDRESS/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "Mcp-Session-Id: $SESSION" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
    
    curl $INGRESS_GW_ADDRESS/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "Mcp-Session-Id: $SESSION" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"tools/list","id":2}'
    curl http://localhost:8080/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "Mcp-Session-Id: $SESSION" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
    
    curl http://localhost:8080/mcp \
      -H "Content-Type: application/json" \
      -H "Accept: application/json, text/event-stream" \
      -H "Mcp-Session-Id: $SESSION" \
      -H "api-key: authorized-user-key" \
      -d '{"jsonrpc":"2.0","method":"tools/list","id":2}'

    Example output:

    data: {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"fetch","description":"Fetches a website and returns its content", ...}]}}

Cleanup

You can optionally remove the resources that you set up as part of this guide.
kubectl delete -n agentgateway-system EnterpriseAgentgatewayPolicy llm-opa-policy mcp-opa-policy
kubectl delete -n agentgateway-system AuthConfig llm-opa
kubectl delete -n agentgateway-system ConfigMap llm-opa-policy
kubectl delete -n agentgateway-system HTTPRoute openai mcp
kubectl delete -n agentgateway-system AgentgatewayBackend openai mcp
kubectl delete -n agentgateway-system Secret openai-secret