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
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
AgentgatewayBackendbased on anapi-keyrequest header. On allow, inject an upstream header and strip theapi-keybefore forwarding. On deny, return a403with a custom body and a custom client response header. - Protect a Model Context Protocol (MCP) route: Reuse the same
AuthConfigto protect an MCP route. The same Rego policy returns the same allow/deny decisions for theinitialize,notifications/initialized, andtools/listMCP 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:
- Set up an agentgateway proxy.
- Set up an LLM provider, such as OpenAI.
- Set up an MCP backend such as
mcp-website-fetcherin theagentgateway-systemnamespace. 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"],
}
}
EOFReview 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.| Field | Description |
|---|---|
allow | Required. true to forward the request; false to reject it. |
http_status | The HTTP status code returned to the client. Set on both allow (200) and deny (403) so the response status is explicit. |
body | The response body returned to the client on deny. |
headers | Headers 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_add | Headers added to the response sent to the client. Useful for surfacing the OPA decision to the caller or to downstream filters. |
request_headers_to_remove | Headers 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
EOFReview the following table to understand this configuration.
| Setting | Description |
|---|---|
opaAuth | Configures 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. |
modules | A list of references to Kubernetes config maps that contain Rego rules. Each entry takes a name and a namespace. |
query | The 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:
AcceptedProtect 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.
Create the OpenAI
AgentgatewayBackendand an HTTPRoute that exposes it on the/openaipath. Replace theAuthorizationdata 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 EOFCreate an
EnterpriseAgentgatewayPolicythat attaches the AuthConfig to the OpenAI HTTPRoute. The policy uses theentExtAuthfield, which sends each request through the provisioned external auth service. NobackendRefis 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 EOFConfigure how to reach the
agentgateway-proxyfrom 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:80Keep this command running in its own terminal session. Use another terminal for the
curlcommands in the following steps, and choose the Local host tab each time.Send a request to the OpenAI route without the
api-keyheader. Verify that the request is denied with a403response, the custom body, and thex-opa-decision: deniedresponse 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 keySend the same request with the expected
api-keyheader. Verify that the request is allowed, that thex-opa-decision: allowedresponse header is added, and that OpenAI returns a chat completion. Inside the gateway, theapi-keyheader is stripped and thex-validated-by: opa-security-checkpointheader 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.
Create an
AgentgatewayBackendfor an MCP server such asmcp-website-fetcher, and an HTTPRoute that exposes it on the/mcppath.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 EOFAttach the same AuthConfig from the Protect an LLM route example to the MCP HTTPRoute by creating a second
EnterpriseAgentgatewayPolicythat 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 EOFSend an
initializerequest to the MCP route without theapi-keyheader. Verify that the request is denied with a403response.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 keySend the
initializerequest with the expectedapi-keyheader. Verify that the request is allowed, anmcp-session-idresponse header is returned, and the MCP server reports its capabilities. Save themcp-session-idfor 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", ...}}}Send the
notifications/initializednotification, then list the tools that the MCP server exposes. Both requests must include theapi-keyandMcp-Session-Idheaders.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