Skip to content
Kong Docs are moving soon! Our docs are migrating to a new home. You'll be automatically redirected to the new site in the future. In the meantime, view this page on the new site!
Kong Logo | Kong Docs Logo
  • Docs
    • Explore the API Specs
      View all API Specs View all API Specs View all API Specs arrow image
    • Documentation
      API Specs
      Kong Gateway
      Lightweight, fast, and flexible cloud-native API gateway
      Kong Konnect
      Single platform for SaaS end-to-end connectivity
      Kong AI Gateway
      Multi-LLM AI Gateway for GenAI infrastructure
      Kong Mesh
      Enterprise service mesh based on Kuma and Envoy
      decK
      Helps manage Kong’s configuration in a declarative fashion
      Kong Ingress Controller
      Works inside a Kubernetes cluster and configures Kong to proxy traffic
      Kong Gateway Operator
      Manage your Kong deployments on Kubernetes using YAML Manifests
      Insomnia
      Collaborative API development platform
  • Plugin Hub
    • Explore the Plugin Hub
      View all plugins View all plugins View all plugins arrow image
    • Functionality View all View all arrow image
      View all plugins
      AI's icon
      AI
      Govern, secure, and control AI traffic with multi-LLM AI Gateway plugins
      Authentication's icon
      Authentication
      Protect your services with an authentication layer
      Security's icon
      Security
      Protect your services with additional security layer
      Traffic Control's icon
      Traffic Control
      Manage, throttle and restrict inbound and outbound API traffic
      Serverless's icon
      Serverless
      Invoke serverless functions in combination with other plugins
      Analytics & Monitoring's icon
      Analytics & Monitoring
      Visualize, inspect and monitor APIs and microservices traffic
      Transformations's icon
      Transformations
      Transform request and responses on the fly on Kong
      Logging's icon
      Logging
      Log request and response data using the best transport for your infrastructure
  • Support
  • Community
  • Kong Academy
Get a Demo Start Free Trial
Kong Mesh
dev
  • Home icon
  • Kong Mesh
  • Features
  • MeshOPA - OPA Policy Integration
github-edit-pageEdit this page
report-issueReport an issue
  • Kong Gateway
  • Kong Konnect
  • Kong Mesh
  • Kong AI Gateway
  • Plugin Hub
  • decK
  • Kong Ingress Controller
  • Kong Gateway Operator
  • Insomnia
  • Kuma

  • Docs contribution guidelines
  • dev
  • 2.10.x (latest)
  • 2.9.x
  • 2.8.x
  • 2.7.x (LTS)
  • 2.6.x
  • 2.5.x
  • 2.4.x
  • 2.3.x
  • 2.2.x
  • Introduction
    • About service meshes
    • Overview of Kong Mesh
    • How Kong Mesh works
    • Architecture
    • Install
    • Concepts
    • Stages of software availability
    • Version support policy
    • Software Bill of Materials
    • Vulnerability patching process
    • Mesh requirements
    • Release notes
  • Quickstart
    • Deploy Kong Mesh on Kubernetes
    • Deploy Kong Mesh on Universal
  • Kong Mesh in Production
    • Overview
    • Deployment topologies
      • Overview
      • Single-zone deployment
      • Multi-zone deployment
    • Use Kong Mesh
    • Control plane deployment
      • Kong Mesh license
      • Deploy a single-zone control plane
      • Deploy a multi-zone global control plane
      • Zone Ingress
      • Zone Egress
      • Configure zone proxy authentication
      • Control plane configuration reference
      • Systemd
      • Kubernetes
      • kumactl
      • Deploy Kong Mesh in Production with Helm
    • Configuring your Mesh and multi-tenancy
    • Data plane configuration
      • Data plane proxy
      • Configure the data plane on Kubernetes
      • Configure the data plane on Universal
      • Configure the Kong Mesh CNI
      • Configure transparent proxying
      • IPv6 support
    • Secure your deployment
      • Manage secrets
      • Authentication with the API server
      • Authentication with the data plane proxy
      • Configure data plane proxy membership
      • Secure access across services
      • Kong Mesh RBAC
      • FIPS support
    • Kong Mesh user interface
    • Inspect API
      • Matched policies
      • Affected data plane proxies
      • Envoy proxy configuration
    • Upgrades and tuning
      • Upgrade Kong Mesh
      • Performance fine-tuning
      • Version specific upgrade notes
    • Control Plane Configuration
      • Modifying the configuration
      • Inspecting the configuration
      • Store
  • Using Kong Mesh
    • Zero Trust & Application Security
      • Mutual TLS
      • External Service
    • Resiliency & Failover
      • Dataplane Health
      • Service Health Probes
    • Managing incoming traffic with gateways
      • How ingress works in Kuma
      • Delegated gateways
      • Built-in gateways
      • Running built-in gateway pods on Kubernetes
      • Configuring built-in listeners
      • Configuring built-in routes
      • Using the Kubernetes Gateway API
    • Observability
      • Demo setup
      • Control plane metrics
      • Configuring Prometheus
      • Configuring Grafana
      • Configuring Datadog
      • Observability in multi-zone
    • Route & Traffic shaping
      • Protocol support in Kong Mesh
    • Service Discovery & Networking
      • Service Discovery
      • MeshService
      • MeshMultiZoneService
      • HostnameGenerator
      • DNS
      • Non-mesh traffic
      • MeshExternalService
      • Transparent Proxying
  • Policies
    • Introduction
      • What is a policy?
      • What do policies look like?
      • Writing a targetRef
      • Merging configuration
      • Using policies with MeshService
      • Examples
      • Applying policies in shadow mode
    • MeshAccessLog
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshCircuitBreaker
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshFaultInjection
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshHealthCheck
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshHTTPRoute
      • TargetRef support matrix
      • Configuration
      • Examples
      • Merging
    • MeshLoadBalancingStrategy
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshMetric
      • TargetRef support matrix
      • Configuration
      • Prometheus
      • OpenTelemetry
      • Examples
    • MeshPassthrough
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshProxyPatch
      • TargetRef support matrix
      • Configuration
      • Examples
      • Merging
    • MeshRateLimit
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshRetry
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshTCPRoute
      • TargetRef support matrix
      • Configuration
      • Examples
      • Route policies with different types targeting the same destination
    • MeshTimeout
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshTLS
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshTrace
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshTrafficPermission
      • TargetRef support matrix
      • Configuration
      • Examples
    • MeshOPA
    • MeshGlobalRateLimit (beta)
    • Previous Policies
      • General notes about Kong Mesh policies
      • How Kong Mesh chooses the right policy to apply
      • Traffic Permissions
      • Traffic Route
      • Traffic Metrics
      • Traffic Trace
      • Traffic Log
      • Locality-aware Load Balancing
      • Fault Injection
      • Health Check
      • Circuit Breaker
      • Retry
      • Timeout
      • Rate Limit
      • Virtual Outbound
      • MeshGatewayRoute
      • OPA policy
  • Guides
    • Federate zone control plane
    • Add a builtin Gateway
    • Add Kong as a delegated Gateway
    • Kubernetes Gateway API
    • Collect Metrics with OpenTelemetry
    • Migration to the new policies
    • Progressively rolling in strict mTLS
    • Producer and consumer policies
    • Configuring inbound traffic with Rules API
    • Upgrading Transparent Proxy
  • Enterprise Features
    • Overview
    • HashiCorp Vault CA
    • Amazon ACM Private CA
    • cert-manager Private CA
    • OPA policy support
    • MeshOPA
    • Multi-zone authentication
    • FIPS support
    • Certificate Authority rotation
    • Role-Based Access Control
    • Red Hat
      • UBI Images
      • Red Hat OpenShift Quickstart
    • Windows Support
    • ECS Support
    • Auditing
    • MeshGlobalRateLimit (beta)
    • Verify signatures for signed Kong Mesh images
    • Build provenance
      • Verify build provenance for signed Kong Mesh images
      • Verify build provenance for signed Kong Mesh binaries
  • Reference
    • HTTP API
    • Kubernetes annotations and labels
    • Kuma data collection
    • Control plane configuration reference
    • Envoy proxy template
  • Community
    • Contribute to Kuma
enterprise-switcher-icon Switch to OSS
On this pageOn this page
  • MeshOPA policy plugin
  • TargetRef support matrix
  • Configuration
    • Inline
    • With secrets
  • Configuration
  • Configuring the authorization filter
  • Support for external API management servers
  • Composing policies
  • Example
  • All policy options
You are browsing unreleased documentation. See the latest documentation here.

MeshOPA - OPA Policy Integration
Available with Kong Gateway Enterprise subscription - Contact Sales

Warning: This policy uses the new policy matching algorithm, it should not be mixed with the OPA Policy.

MeshOPA policy plugin

Kong Mesh integrates the Open Policy Agent (OPA) to provide access control for your services.

The agent is included in the data plane proxy sidecar, instead of the more common deployment as a separate sidecar.

When the MeshOPA policy is applied, the control plane configures the following:

  • The embedded policy agent, with the specified policy
  • Envoy, to use External Authorization that points to the embedded policy agent

TargetRef support matrix

Sidecar
Builtin Gateway
targetRef Allowed kinds
targetRef.kind Mesh, MeshSubset, MeshService, MeshServiceSubset
targetRef Allowed kinds
targetRef.kind Mesh, MeshGateway

To learn more about the information in this table, see the matching docs.

Configuration

To apply a policy with MeshOPA, you must do the following:

  • Specify the group of data plane proxies to apply the policy to with the targetRef property.
  • Provide a policy with the appendPolicies property. Policies are defined in the Rego language.
  • Optionally provide custom configuration for the policy agent.

Inline

Kubernetes
Universal
apiVersion: kuma.io/v1alpha1
kind: MeshOPA
metadata:
  name: mopa-1
  namespace: kong-mesh-system
  labels:
    kuma.io/mesh: default # optional, defaults to `default` if unset
spec:
  targetRef:
    kind: Mesh
  default:
    agentConfig: # optional
      inlineString: | # one of: inlineString, secret
        decision_logs:
          console: true
    appendPolicies:
      - ignoreDecision: false # optional, defaults to 'false'
        rego:
          inlineString: | # one of: inlineString, secret
            package envoy.authz

            import input.attributes.request.http as http_request

            default allow = false

            token = {"valid": valid, "payload": payload} {
                [_, encoded] := split(http_request.headers.authorization, " ")
                [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"})
            }

            allow {
                is_token_valid
                action_allowed
            }

            is_token_valid {
              token.valid
              now := time.now_ns() / 1000000000
              token.payload.nbf <= now
              now < token.payload.exp
            }

            action_allowed {
              http_request.method == "GET"
              token.payload.role == "admin"
            }
type: MeshOPA
mesh: default
name: mopa-1
spec:
  targetRef:
    kind: Mesh
  default:
    agentConfig: # optional
      inlineString: | # one of: inlineString, secret
        decision_logs:
          console: true
    appendPolicies: # optional
      - ignoreDecision: false # optional, defaults to 'false'
        rego:
          inlineString: | # one of: inlineString, secret
            package envoy.authz

            import input.attributes.request.http as http_request

            default allow = false

            token = {"valid": valid, "payload": payload} {
                [_, encoded] := split(http_request.headers.authorization, " ")
                [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"})
            }

            allow {
                is_token_valid
                action_allowed
            }

            is_token_valid {
              token.valid
              now := time.now_ns() / 1000000000
              token.payload.nbf <= now
              now < token.payload.exp
            }

            action_allowed {
              http_request.method == "GET"
              token.payload.role == "admin"
            }

With secrets

Encoding the policy in a Secret provides some security for policies that contain sensitive data.

Kubernetes
Universal
  1. Define a Secret with a policy that’s Base64-encoded:

    apiVersion: v1
    kind: Secret
    metadata:
      name: mopa-policy
      namespace: kong-mesh-system
      labels:
        kuma.io/mesh: default
    data:
      value: cGFja2FnZSBlbnZveS5hdXRoegoKaW1wb3J0IGlucHV0LmF0dHJpYnV0ZXMucmVxdWVzdC5odHRwIGFzIGh0dHBfcmVxdWVzdAoKZGVmYXVsdCBhbGxvdyA9IGZhbHNlCgp0b2tlbiA9IHsidmFsaWQiOiB2YWxpZCwgInBheWxvYWQiOiBwYXlsb2FkfSB7CiAgICBbXywgZW5jb2RlZF0gOj0gc3BsaXQoaHR0cF9yZXF1ZXN0LmhlYWRlcnMuYXV0aG9yaXphdGlvbiwgIiAiKQogICAgW3ZhbGlkLCBfLCBwYXlsb2FkXSA6PSBpby5qd3QuZGVjb2RlX3ZlcmlmeShlbmNvZGVkLCB7InNlY3JldCI6ICJzZWNyZXQifSkKfQoKYWxsb3cgewogICAgaXNfdG9rZW5fdmFsaWQKICAgIGFjdGlvbl9hbGxvd2VkCn0KCmlzX3Rva2VuX3ZhbGlkIHsKICB0b2tlbi52YWxpZAogIG5vdyA6PSB0aW1lLm5vd19ucygpIC8gMTAwMDAwMDAwMAogIHRva2VuLnBheWxvYWQubmJmIDw9IG5vdwogIG5vdyA8IHRva2VuLnBheWxvYWQuZXhwCn0KCmFjdGlvbl9hbGxvd2VkIHsKICBodHRwX3JlcXVlc3QubWV0aG9kID09ICJHRVQiCiAgdG9rZW4ucGF5bG9hZC5yb2xlID09ICJhZG1pbiIKfQoK
    type: system.kuma.io/secret
    
  2. Pass the Secret to MeshOPA:

    apiVersion: kuma.io/v1alpha1
    kind: MeshOPA
    metadata:
      name: mopa-1
      namespace: kong-mesh-system
      labels:
        kuma.io/mesh: default
    spec:
      targetRef:
        kind: Mesh
      default:
        appendPolicies:
          - rego:
              secret: mopa-policy
    
  1. Define a Secret with a policy that’s Base64-encoded:

    type: Secret
    name: sample-secret
    mesh: default
    data: cGFja2FnZSBlbnZveS5hdXRoegoKaW1wb3J0IGlucHV0LmF0dHJpYnV0ZXMucmVxdWVzdC5odHRwIGFzIGh0dHBfcmVxdWVzdAoKZGVmYXVsdCBhbGxvdyA9IGZhbHNlCgp0b2tlbiA9IHsidmFsaWQiOiB2YWxpZCwgInBheWxvYWQiOiBwYXlsb2FkfSB7CiAgICBbXywgZW5jb2RlZF0gOj0gc3BsaXQoaHR0cF9yZXF1ZXN0LmhlYWRlcnMuYXV0aG9yaXphdGlvbiwgIiAiKQogICAgW3ZhbGlkLCBfLCBwYXlsb2FkXSA6PSBpby5qd3QuZGVjb2RlX3ZlcmlmeShlbmNvZGVkLCB7InNlY3JldCI6ICJzZWNyZXQifSkKfQoKYWxsb3cgewogICAgaXNfdG9rZW5fdmFsaWQKICAgIGFjdGlvbl9hbGxvd2VkCn0KCmlzX3Rva2VuX3ZhbGlkIHsKICB0b2tlbi52YWxpZAogIG5vdyA6PSB0aW1lLm5vd19ucygpIC8gMTAwMDAwMDAwMAogIHRva2VuLnBheWxvYWQubmJmIDw9IG5vdwogIG5vdyA8IHRva2VuLnBheWxvYWQuZXhwCn0KCmFjdGlvbl9hbGxvd2VkIHsKICBodHRwX3JlcXVlc3QubWV0aG9kID09ICJHRVQiCiAgdG9rZW4ucGF5bG9hZC5yb2xlID09ICJhZG1pbiIKfQoK
    
  2. Pass the Secret to MeshOPA:

    type: MeshOPA
    mesh: default
    name: mopa-1
    spec:
      targetRef:
        kind: Mesh
      default:
        appendPolicies:
          - rego:
              secret: mopa-policy
    

Configuration

Kong Mesh defines a default configuration for OPA, but you can adjust the configuration to meet your environment’s requirements.

The following environment variables are available:

Variable Type What it configures Default value
KMESH_OPA_ADDR string Address OPA API server listens on localhost:8181
KMESH_OPA_CONFIG_PATH string Path to file of initial config N/A
KMESH_OPA_DIAGNOSTIC_ADDR string Address of OPA diagnostics server 0.0.0.0:8282
KMESH_OPA_ENABLED bool Whether kuma-dp starts embedded OPA true
KMESH_OPA_EXT_AUTHZ_ADDR string Address of Envoy External AuthZ service localhost:9191
KMESH_OPA_CONFIG_OVERRIDES strings Overrides for OPA configuration, in addition to config file(*) nil
kumactl
Helm
Pod
Universal

When you deploy the Mesh control plane, edit the kong-mesh-control-plane-config ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: kong-mesh-control-plane-config
  namespace: kong-mesh-system
data:
  config.yaml: |
    runtime:
      kubernetes:
        injector:
          sidecarContainer:
            envVars:
              KMESH_OPA_ENABLED: "false"
              KMESH_OPA_ADDR: ":8888"
              KMESH_OPA_CONFIG_OVERRIDES: "config1:x,config2:y"

Override the Helm value in values.yaml

kuma:
  controlPlane:
    config: |
      runtime:
        kubernetes:
          injector:
            sidecarContainer:
              envVars:
                KMESH_OPA_ENABLED: "false"
                KMESH_OPA_ADDR: ":8888"
                KMESH_OPA_CONFIG_OVERRIDES: "config1:x,config2:y"

Override the config for individual data plane proxies by placing the appropriate annotations on the Pod:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-app
  namespace: kuma-example
spec:
  ...
  template:
    metadata:
      ...
      annotations:
        # indicate to Kong Mesh that this Pod doesn't need a sidecar
        kuma.io/sidecar-env-vars: "KMESH_OPA_ENABLED=false;KMESH_OPA_ADDR=:8888;KMESH_OPA_CONFIG_OVERRIDES=config1:x,config2:y"

The run command on the data plane proxy accepts the following equivalent parameters if you prefer not to set environment variables:

--opa-addr
--opa-config-path
--opa-diagnostic-addr
--opa-enabled                    
--opa-ext-authz-addr
--opa-set strings

Configuring the authorization filter

You can configure the external authorization filter by adjusting the authConfig section.

Kubernetes
Universal
apiVersion: kuma.io/v1alpha1
kind: MeshOPA
metadata:
  name: mopa-1
  namespace: kong-mesh-system
  labels:
    kuma.io/mesh: default # optional, defaults to `default` if unset
spec:
  targetRef:
    kind: Mesh
  default:
    authConfig: # optional
      statusOnError: 413 # optional: defaults to 403.
      onAgentFailure: allow # optional: one of 'allow' or 'deny', defaults to 'deny' defines the behavior when communication with the agent fails or the policy execution fails.
      requestBody: # optional
          maxSize: 1024 # the max number of bytes to send to the agent, if we exceed this, the request to the agent will have: `x-envoy-auth-partial-body: true`.
          sendRawBody: true # use when the body is not plaintext. The agent request will have `raw_body` instead of `body`
...
type: MeshOPA
mesh: default
name: mopa-1
spec:
  targetRef:
    kind: Mesh
  default:
    authConfig: # optional
      statusOnError: 413 # optional: defaults to 403. http statusCode to use when the connection to the agent failed.
      onAgentFailure: allow # optional: one of 'allow' or 'deny', defaults to 'deny'. defines the behavior when communication with the agent fails or the policy execution fails.
      requestBody: # optional
        maxSize: 1024 # the maximum number of bytes to send to the agent, if we exceed this, the request to the agent will have: `x-envoy-auth-partial-body: true`.
        sendRawBody: true # use when the body is not plaintext. The agent request will have `raw_body` instead of `body`
...

By default, the body will not be sent to the agent. To send it, set authConfig.requestBody.maxSize to the maximum size of your body. If the request body is larger than this parameter, it will be truncated and the header x-envoy-auth-partial-body will be set to true.

Support for external API management servers

The agentConfig field lets you define a custom configuration that points to an external management server:

Kubernetes
Universal
apiVersion: kuma.io/v1alpha1
kind: MeshOPA
metadata:
  name: mopa-1
  namespace: kong-mesh-system
  labels:
    kuma.io/mesh: default
spec:
  targetRef:
    kind: Mesh
  default:
    agentConfig:
      inlineString: |
        services:
          acmecorp:
            url: https://example.com/control-plane-api/v1
            credentials:
              bearer:
                token: "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"

        discovery:
          name: example
          resource: /configuration/example/discovery
type: MeshOPA
mesh: default
name: mopa-1
spec:
  targetRef:
    kind: Mesh
  default:
    agentConfig:
      inlineString: | # one of: inlineString, secret
        services:
          acmecorp:
            url: https://example.com/control-plane-api/v1
            credentials:
              bearer:
                token: "bGFza2RqZmxha3NkamZsa2Fqc2Rsa2ZqYWtsc2RqZmtramRmYWxkc2tm"
        discovery:
          name: example
          resource: /configuration/example/discovery

Composing policies

In your organization, the mesh operator may want to set a policy for subset of proxies in the mesh. At the same time, service owners may want to exercise additional policies.

For example, the mesh operator may want to enable JWT token validation for all proxies in the mesh

apiVersion: kuma.io/v1alpha1
kind: MeshOPA
metadata:
  name: mopa-mesh-operator
  namespace: kong-mesh-system
  labels:
    kuma.io/mesh: default
spec:
  targetRef:
    kind: Mesh
  default:
    appendPolicies:
      - rego:
          inlineString: |
            package operator
            
            import input.attributes.request.http as http_request
            
            default allow = false
            
            token = {"valid": valid, "payload": payload} {
                [_, encoded] := split(http_request.headers.authorization, " ")
                [valid, _, payload] := io.jwt.decode_verify(encoded, {"secret": "secret"})
            }
            
            allow {
                is_token_valid
                action_allowed
            }
            
            is_token_valid {
              token.valid
              now := time.now_ns() / 1000000000
              token.payload.nbf <= now
              now < token.payload.exp
            }
            
            action_allowed {
              http_request.method == "GET"
              token.payload.role == "admin"
            }

Service owner wants to block all requests on path /blocked:

apiVersion: kuma.io/v1alpha1
kind: MeshOPA
metadata:
  name: mopa-service-owner
  namespace: kong-mesh-system
  labels:
    kuma.io/mesh: default
spec:
  targetRef:
    kind: MeshService
    name: test-server_kuma-demo_svc_80
  default:
    appendPolicies:
      - rego:
          inlineString: |
            package serviceowner
            
            default allow = true
            
            deny {
              input.parsed_path == ["blocked"]
            }

appendPolicies is a list you can append, therefore in the case of the data plane proxy test-server_kuma-demo_svc_80 service, both policies will be applied.

Kong Mesh will autogenerate an additional OPA decision policy:

package implicitkmesh
import data.operator
import data.serviceowner

allow {
  data.operator.allow
  not data.operator.deny
  data.serviceowner.allow
  not data.serviceowner.deny
}

It also configures the OPA agent decision path (plugins.envoy_ext_authz_grpc.path) to implicitkmesh/allow.

You can also add a rego policy which is not part of the decision. Set a appendPolicies[*].ignoreDecision to true so the rego policy won’t be added to autogenerated decision policy. This way, the mesh operator can expose utility functions to service owner.

Example

The following example shows how to deploy and test a sample MeshOPA policy on Kubernetes, using the kuma-demo application.

  1. Deploy the example application:

    kubectl apply -f https://bit.ly/demokuma
    
  2. Make a request from the frontend to the backend:

    kubectl exec -i -t $(kubectl get pod -l "app=kuma-demo-frontend" -o jsonpath='{.items[0].metadata.name}' -n kuma-demo) -n kuma-demo -c kuma-fe -- curl backend:3001 -v
    

    The output looks like:

    Defaulting container name to kuma-fe.
    Use 'kubectl describe pod/kuma-demo-app-6787b4f7f5-m428c -n kuma-demo' to see all of the containers in this pod.
    *   Trying 10.111.108.218:3001...
    * TCP_NODELAY set
    * Connected to backend (10.111.108.218) port 3001 (#0)
    > GET / HTTP/1.1
    > Host: backend:3001
    > User-Agent: curl/7.67.0
    > Accept: */*
    >
    * Mark bundle as not supporting multiuse
    < HTTP/1.1 200 OK
    < x-powered-by: Express
    < cache-control: no-store, no-cache, must-revalidate, private
    < access-control-allow-origin: *
    < access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS
    < access-control-allow-headers: *
    < host: backend:3001
    < user-agent: curl/7.67.0
    < accept: */*
    < x-forwarded-proto: http
    < x-request-id: 1717af9c-2587-43b9-897f-f8061bba5ad4
    < content-length: 90
    < content-type: text/html; charset=utf-8
    < date: Tue, 16 Mar 2021 15:33:18 GMT
    < x-envoy-upstream-service-time: 1521
    < server: envoy
    <
    * Connection #0 to host backend left intact
    Hello World! Marketplace with sales and reviews made with <3 by the OCTO team at Kong Inc.
    
  3. Apply a MeshOPA policy that requires a valid JWT token:

    echo "
    apiVersion: kuma.io/v1alpha1
    kind: MeshOPA
    metadata:
      namespace: kong-mesh-system
      name: mopa-1
      labels:
        kuma.io/mesh: default
    spec:
      targetRef:
        kind: Mesh
      default:
        appendPolicies:
          - rego:
              inlineString: |
                package envoy.authz
    
                import input.attributes.request.http as http_request
    
                default allow = false
    
                token = {\"valid\": valid, \"payload\": payload} {
                    [_, encoded] := split(http_request.headers.authorization, \" \")
                    [valid, _, payload] := io.jwt.decode_verify(encoded, {\"secret\": \"secret\"})
                }
    
                allow {
                    is_token_valid
                    action_allowed
                }
    
                is_token_valid {
                  token.valid
                  now := time.now_ns() / 1000000000
                  token.payload.nbf <= now
                  now < token.payload.exp
                }
    
                action_allowed {
                  http_request.method == \"GET\"
                  token.payload.role == \"admin\"
                }
    " | kubectl apply -f -
    
  4. Make an invalid request from the frontend to the backend:

    kubectl exec -i -t $(kubectl get pod -l "app=kuma-demo-frontend" -o jsonpath='{.items[0].metadata.name}' -n kuma-demo) -n kuma-demo -c kuma-fe -- curl backend:3001 -v
    

    The output looks like:

    Defaulting container name to kuma-fe.
    Use 'kubectl describe pod/kuma-demo-app-6787b4f7f5-bwvnb -n kuma-demo' to see all of the containers in this pod.
    *   Trying 10.105.146.164:3001...
    * TCP_NODELAY set
    * Connected to backend (10.105.146.164) port 3001 (#0)
    > GET / HTTP/1.1
    > Host: backend:3001
    > User-Agent: curl/7.67.0
    > Accept: */*
    >
    * Mark bundle as not supporting multiuse
    < HTTP/1.1 403 Forbidden
    < date: Tue, 09 Mar 2021 16:50:40 GMT
    < server: envoy
    < x-envoy-upstream-service-time: 2
    < content-length: 0
    <
    * Connection #0 to host backend left intact
    

    Note the HTTP/1.1 403 Forbidden message. The application doesn’t allow a request without a valid token.

    The policy can take up to 30 seconds to propagate, so if this request succeeds the first time, wait and then try again.

  5. Make a valid request from the frontend to the backend.

    Export the token into an environment variable:

    export ADMIN_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJzdWIiOiJZbTlpIiwibmJmIjoxNTE0ODUxMTM5LCJleHAiOjI1MjQ2MDgwMDB9.H0-42LYzoWyQ_4MXAcED30u6lA5JE087eECV2nxDfXo"
    

    Make the request:

    kubectl exec -i -t $(kubectl get pod -l "app=kuma-demo-frontend" -o jsonpath='{.items[0].metadata.name}' -n kuma-demo) -n kuma-demo -c kuma-fe -- curl -H "Authorization: Bearer $ADMIN_TOKEN" backend:3001
    

    The output looks like:

    Defaulting container name to kuma-fe.
    Use 'kubectl describe pod/kuma-demo-app-6787b4f7f5-m428c -n kuma-demo' to see all of the containers in this pod.
    *   Trying 10.111.108.218:3001...
    * TCP_NODELAY set
    * Connected to backend (10.111.108.218) port 3001 (#0)
    > GET / HTTP/1.1
    > Host: backend:3001
    > User-Agent: curl/7.67.0
    > Accept: */*
    >
    * Mark bundle as not supporting multiuse
    < HTTP/1.1 200 OK
    < x-powered-by: Express
    < cache-control: no-store, no-cache, must-revalidate, private
    < access-control-allow-origin: *
    < access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS
    < access-control-allow-headers: *
    < host: backend:3001
    < user-agent: curl/7.67.0
    < accept: */*
    < x-forwarded-proto: http
    < x-request-id: 8fd7b398-1ba2-4c2e-b229-5159d04d782e
    < content-length: 90
    < content-type: text/html; charset=utf-8
    < date: Tue, 16 Mar 2021 17:26:00 GMT
    < x-envoy-upstream-service-time: 261
    < server: envoy
    <
    * Connection #0 to host backend left intact
    Hello World! Marketplace with sales and reviews made with <3 by the OCTO team at Kong Inc.
    

    The request is valid again because the token is signed with the secret private key, its payload includes the admin role, and it is not expired.

All policy options

Spec is the specification of the Kuma MeshOPA resource.

Type: object

Properties

  • default
    • Type: object
    • Properties
      • agentConfig
        • AgentConfig defines bootstrap OPA agent configuration.
        • Type: object
        • Properties
          • inline
            • Data source is inline bytes.
            • Type: string
            • String format must be a "byte"
          • inlineString
            • Data source is inline string`
            • Type: string
          • secret
            • Data source is a secret with given Secret key.
            • Type: string
      • appendPolicies
        • Policies define OPA policies that will be applied on OPA Agent.
        • Type: array
          • Items
          • Type: object
          • Properties
            • ignoreDecision
              • If true, then policy won't be taken into account when making a decision.
              • Type: boolean
            • rego required
              • OPA Policy written in Rego. Available values: secret, inline, inlineString.
              • Type: object
              • Properties
                • inline
                  • Data source is inline bytes.
                  • Type: string
                  • String format must be a "byte"
                • inlineString
                  • Data source is inline string`
                  • Type: string
                • secret
                  • Data source is a secret with given Secret key.
                  • Type: string
      • authConfig
        • AuthConfig are configurations specific to the filter.
        • Type: object
        • Properties
          • onAgentFailure
            • OnAgentFailure either 'allow' or 'deny' (default to deny) whetherto allow requests when the authorization agent failed.
            • Type: string
            • The value is restricted to the following:
              1. "Allow"
              2. "Deny"
          • requestBody
            • RequestBody configuration to apply on the request body sent to theauthorization agent (if absent, the body is not sent).
            • Type: object
            • Properties
              • maxSize
                • MaxSize defines the maximum payload size sent to authorization agent. If the payloadis larger it will be truncated and there will be a headerx-envoy-auth-partial-body: true. If it is set to 0 no body will besent to the agent.
                • Type: integer
              • sendRawBody
                • SendRawBody enable sending raw body instead of the body encoded into UTF-8
                • Type: boolean
          • statusOnError
            • StatusOnError is the http status to return when there's a connectionfailure between the dataplane and the authorization agent
            • Type: integer
          • timeout
            • Timeout for the single gRPC request from Envoy to OPA Agent.
            • Type: string
  • targetRef
    • TargetRef is a reference to the resource the policy takes an effect on.The resource could be either a real store object or virtual resourcedefined inplace.
    • Type: object
    • Properties
      • kind required
        • Kind of the referenced resource
        • Type: string
        • The value is restricted to the following:
          1. "Mesh"
          2. "MeshSubset"
          3. "MeshGateway"
          4. "MeshService"
          5. "MeshExternalService"
          6. "MeshMultiZoneService"
          7. "MeshServiceSubset"
          8. "MeshHTTPRoute"
          9. "Dataplane"
      • labels
        • Labels are used to select group of MeshServices that match labels. Either Labels orName and Namespace can be used.
        • Type: object
        • This schema accepts additional properties.
        • Properties
      • mesh
        • Mesh is reserved for future use to identify cross mesh resources.
        • Type: string
      • name
        • Name of the referenced resource. Can only be used with kinds: MeshService,MeshServiceSubset and MeshGatewayRoute
        • Type: string
      • namespace
        • Namespace specifies the namespace of target resource. If empty only resources in policy namespacewill be targeted.
        • Type: string
      • proxyTypes
        • ProxyTypes specifies the data plane types that are subject to the policy. When not specified,all data plane types are targeted by the policy.
        • Type: array
          • Items
          • Type: string
          • The value is restricted to the following:
            1. "Sidecar"
            2. "Gateway"
      • sectionName
        • SectionName is used to target specific section of resource.For example, you can target port from MeshService.ports[] by its name. Only traffic to this port will be affected.
        • Type: string
      • tags
        • Tags used to select a subset of proxies by tags. Can only be used with kindsMeshSubset and MeshServiceSubset
        • Type: object
        • This schema accepts additional properties.
        • Properties

Generated with json-schema-md-doc Tue May 20 2025 00:58:07 GMT+0000 (Coordinated Universal Time)

Thank you for your feedback.
Was this page useful?
Too much on your plate? close cta icon
More features, less infrastructure with Kong Konnect. 1M requests per month for free.
Try it for Free
  • Kong
    Powering the API world

    Increase developer productivity, security, and performance at scale with the unified platform for API management, service mesh, and ingress controller.

    • Products
      • Kong Konnect
      • Kong Gateway Enterprise
      • Kong Gateway
      • Kong Mesh
      • Kong Ingress Controller
      • Kong Insomnia
      • Product Updates
      • Get Started
    • Documentation
      • Kong Konnect Docs
      • Kong Gateway Docs
      • Kong Mesh Docs
      • Kong Insomnia Docs
      • Kong Konnect Plugin Hub
    • Open Source
      • Kong Gateway
      • Kuma
      • Insomnia
      • Kong Community
    • Company
      • About Kong
      • Customers
      • Careers
      • Press
      • Events
      • Contact
  • Terms• Privacy• Trust and Compliance
© Kong Inc. 2025