From 01a2dce0f24c96983049a68fb19add93fa30341d Mon Sep 17 00:00:00 2001 From: ci-bot Date: Fri, 3 Jan 2025 09:06:51 +0000 Subject: [PATCH] Deployed a4aa6f2 to main with MkDocs 1.6.1 and mike 2.1.3 --- main/cel-extensions/envoy/index.html | 64 +++-- main/cel-extensions/index.html | 2 +- main/policies/authorization-rules/index.html | 122 ++++----- main/policies/failure-policy/index.html | 20 +- main/policies/index.html | 21 +- main/policies/variables/index.html | 10 +- main/quick-start/authz-server/index.html | 21 +- main/reference/json-schemas/index.html | 43 ++-- main/search/search_index.json | 2 +- main/tutorials/envoy-gateway/index.html | 249 ++++++++++--------- main/tutorials/istio/index.html | 67 ++--- 11 files changed, 306 insertions(+), 315 deletions(-) diff --git a/main/cel-extensions/envoy/index.html b/main/cel-extensions/envoy/index.html index 28458ff..2805e06 100644 --- a/main/cel-extensions/envoy/index.html +++ b/main/cel-extensions/envoy/index.html @@ -1,55 +1,47 @@ - Envoy library - Kyverno Envoy Plugin
Skip to content

Envoy library

The envoy library adds some types and function to simplify the creation of Envoy CheckResponse objects.

Types

<CheckRequest>

CEL Type / Proto: envoy.service.auth.v3.CheckRequest

<CheckResponse>

CEL Type / Proto: envoy.service.auth.v3.CheckResponse

<OkHttpResponse>

CEL Type / Proto: envoy.service.auth.v3.OkHttpResponse

<DeniedHttpResponse>

CEL Type / Proto: envoy.service.auth.v3.DeniedHttpResponse

<Metadata>

CEL Type / Proto: google.protobuf.Struct

<HeaderValueOption>

CEL Type / Proto: envoy.config.core.v3.HeaderValueOption

<QueryParameter>

CEL Type / Proto: envoy.config.core.v3.QueryParameter

Functions

envoy.Allowed

This function creates an <OkHttpResponse> object.

Signature and overloads

envoy.Allowed() -> <OkHttpResponse>
+ Envoy library - Kyverno Envoy Plugin      

Envoy library

The envoy library adds some types and function to simplify the creation of OkResponse and DeniedResponse objects.

Types

<CheckRequest>

CEL Type / Proto: envoy.service.auth.v3.CheckRequest

<OkResponse>

CEL Type / Proto: envoy.OkResponse

Field CEL Type / Proto Docs
status google.rpc.Status Docs
http_response envoy.service.auth.v3.OkHttpResponse Docs
dynamic_metadata google.protobuf.Struct Docs

<DeniedResponse>

CEL Type / Proto: envoy.DeniedResponse

Field CEL Type / Proto Docs
status google.rpc.Status Docs
http_response envoy.service.auth.v3.DeniedHttpResponse Docs
dynamic_metadata google.protobuf.Struct Docs

<OkHttpResponse>

CEL Type / Proto: envoy.service.auth.v3.OkHttpResponse

<DeniedHttpResponse>

CEL Type / Proto: envoy.service.auth.v3.DeniedHttpResponse

<Metadata>

CEL Type / Proto: google.protobuf.Struct

<HeaderValueOption>

CEL Type / Proto: envoy.config.core.v3.HeaderValueOption

<QueryParameter>

CEL Type / Proto: envoy.config.core.v3.QueryParameter

<Status>

CEL Type / Proto: google.rpc.Status

Functions

envoy.Allowed

This function creates an <OkHttpResponse> object.

Signature and overloads

envoy.Allowed() -> <OkHttpResponse>
 

Example

envoy.Allowed()
 

envoy.Denied

This function creates a <DeniedHttpResponse> object.

Signature and overloads

envoy.Denied(<int> code) -> <DeniedHttpResponse>
 

Example

envoy.Denied(401)
-

envoy.Response

This function creates a <CheckResponse> object.

Signature and overloads

envoy.Response(<int> code) -> <CheckResponse>
-
envoy.Response(<OkHttpResponse> ok) -> <CheckResponse>
-
envoy.Response(<DeniedHttpResponse> denied) -> <CheckResponse>
-

Example

// ok
-envoy.Response(0)
-
-// permission denied
-envoy.Response(7)
-
envoy.Response(envoy.Allowed())
-
envoy.Response(envoy.Denied(401))
-

envoy.Header

This function creates an <HeaderValueOption> object.

Signature and overloads

envoy.Header(<string> key, <string> value) -> <HeaderValueOption>
-

Example

envoy.Header("foo", "bar")
-

envoy.QueryParam

This function creates a <QueryParameter> object.

Signature and overloads

envoy.QueryParam(<string> key, <string> value) -> <QueryParameter>
-

Example

envoy.QueryParam("foo", "bar")
-

WithBody

This function sets the body of a <DeniedHttpResponse> object.

Signature and overloads

<DeniedHttpResponse>.WithBody(<string> body) -> <DeniedHttpResponse>
-

Example

envoy.Denied(401).WithBody("Unauthorized Request")
-

WithHeader

This function adds a <HeaderValueOption>:

  • When the request is sent upstream by Envoy, in the case of an <OkHttpResponse>.
  • When the response is sent downstream by Envoy, in the case of a <DeniedHttpResponse>.

Signature and overloads

<OkHttpResponse>.WithHeader(<HeaderValueOption> header) -> <OkHttpResponse>
+

envoy.Header

This function creates an <HeaderValueOption> object.

Signature and overloads

envoy.Header(<string> key, <string> value) -> <HeaderValueOption>
+

Example

envoy.Header("foo", "bar")
+

envoy.QueryParam

This function creates a <QueryParameter> object.

Signature and overloads

envoy.QueryParam(<string> key, <string> value) -> <QueryParameter>
+

Example

envoy.QueryParam("foo", "bar")
+

WithBody

This function sets the body of a <DeniedHttpResponse> object.

Signature and overloads

<DeniedHttpResponse>.WithBody(<string> body) -> <DeniedHttpResponse>
+

Example

envoy.Denied(401).WithBody("Unauthorized Request")
+

WithHeader

This function adds a <HeaderValueOption>:

  • When the request is sent upstream by Envoy, in the case of an <OkHttpResponse>.
  • When the response is sent downstream by Envoy, in the case of a <DeniedHttpResponse>.

Signature and overloads

<OkHttpResponse>.WithHeader(<HeaderValueOption> header) -> <OkHttpResponse>
 
<OkHttpResponse>.WithHeader(<string> key, <string> value) -> <OkHttpResponse>
 
<DeniedHttpResponse>.WithHeader(<HeaderValueOption> header) -> <DeniedHttpResponse>
 
<DeniedHttpResponse>.WithHeader(<string> key, <string> value) -> <DeniedHttpResponse>
-

Example

envoy.Allowed().WithHeader(envoy.Header("foo", "bar"))
+

Example

envoy.Allowed().WithHeader(envoy.Header("foo", "bar"))
 
envoy.Allowed().WithHeader("foo", "bar")
 
envoy.Denied(401).WithHeader(envoy.Header("foo", "bar"))
 
envoy.Denied(401).WithHeader("foo", "bar")
-

WithoutHeader

This function marks a header to be removed when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithoutHeader(<string> header) -> <OkHttpResponse>
-

Example

envoy.Allowed().WithoutHeader("foo")
-

WithResponseHeader

This function adds a <HeaderValueOption> when the response is sent downstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithResponseHeader(<HeaderValueOption> header) -> <OkHttpResponse>
+

WithoutHeader

This function marks a header to be removed when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithoutHeader(<string> header) -> <OkHttpResponse>
+

Example

envoy.Allowed().WithoutHeader("foo")
+

WithResponseHeader

This function adds a <HeaderValueOption> when the response is sent downstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithResponseHeader(<HeaderValueOption> header) -> <OkHttpResponse>
 
<OkHttpResponse>.WithResponseHeader(<string> key, <string> value) -> <OkHttpResponse>
-

Example

envoy.Allowed().WithResponseHeader(envoy.Header("foo", "bar"))
+

Example

envoy.Allowed().WithResponseHeader(envoy.Header("foo", "bar"))
 
envoy.Allowed().WithResponseHeader("foo", "bar")
-

WithQueryParam

This function adds a <QueryParameter> to be added when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithQueryParam(<QueryParameter> param) -> <OkHttpResponse>
+

WithQueryParam

This function adds a <QueryParameter> to be added when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithQueryParam(<QueryParameter> param) -> <OkHttpResponse>
 
<OkHttpResponse>.WithQueryParam(<string> key, <string> value) -> <OkHttpResponse>
-

Example

envoy.Allowed().WithQueryParam(envoy.QueryParam("foo", "bar"))
+

Example

envoy.Allowed().WithQueryParam(envoy.QueryParam("foo", "bar"))
 
envoy.Allowed().WithQueryParam("foo", "bar")
-

WithoutQueryParam

This function marks a query parameter to be removed when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithoutQueryParam(<string> param) -> <OkHttpResponse>
-

Example

envoy.Allowed().WithoutQueryParam("foo")
-

KeepEmptyValue

This function sets the keep_empty_value field of an <HeaderValueOption> object.

Signature and overloads

<HeaderValueOption>.KeepEmptyValue() -> <HeaderValueOption>
+

WithoutQueryParam

This function marks a query parameter to be removed when the request is sent upstream by Envoy.

Signature and overloads

<OkHttpResponse>.WithoutQueryParam(<string> param) -> <OkHttpResponse>
+

Example

envoy.Allowed().WithoutQueryParam("foo")
+

KeepEmptyValue

This function sets the keep_empty_value field of an <HeaderValueOption> object.

Signature and overloads

<HeaderValueOption>.KeepEmptyValue() -> <HeaderValueOption>
 
<HeaderValueOption>.KeepEmptyValue(<bool> keep) -> <HeaderValueOption>
-

Example

envoy.Header("foo", "bar").KeepEmptyValue()
+

Example

envoy.Header("foo", "bar").KeepEmptyValue()
 
envoy.Header("foo", "bar").KeepEmptyValue(true)
-

Response

This function creates a <CheckResponse> object from an <OkHttpResponse> or <DeniedHttpResponse>.

Signature and overloads

<OkHttpResponse>.Response() -> <CheckResponse>
-
<DeniedHttpResponse>.Response() -> <CheckResponse>
-

Example

envoy.Allowed().Response()
+

Response

This function creates a <OkResponse> / DeniedResponse object from an <OkHttpResponse> / <DeniedHttpResponse>.

Signature and overloads

<OkHttpResponse>.Response() -> <OkResponse>
+
<DeniedHttpResponse>.Response() -> <DeniedResponse>
+

Example

envoy.Allowed().Response()
 
envoy.Denied(401).Response()
-

WithMessage

This function sets the status.message field of a <CheckResponse> object.

Signature and overloads

<CheckResponse>.WithMessage(<string> message) -> <CheckResponse>
-

Example

envoy.Allowed().Response().WithMessage("hello world!")
+

WithMessage

This function sets the status.message field of an <OkResponse> / DeniedResponse object.

Signature and overloads

<OkResponse>.WithMessage(<string> message) -> <OkResponse>
+
<DeniedResponse>.WithMessage(<string> message) -> <DeniedResponse>
+

Example

envoy.Allowed().Response().WithMessage("hello world!")
 
envoy.Denied(401).Response().WithMessage("hello world!")
-

WithMetadata

This function sets the dynamic_metadata field of a <CheckResponse> object.

Signature and overloads

<CheckResponse>.WithMetadata(<Metadata> metadata) -> <CheckResponse>
-

Example

envoy.Allowed().Response().WithMetadata({ "foo": "bar" })
+

WithMetadata

This function sets the dynamic_metadata field of an <OkResponse> / DeniedResponse object.

Signature and overloads

<OkResponse>.WithMetadata(<Metadata> metadata) -> <OkResponse>
+
<DeniedResponse>.WithMetadata(<Metadata> metadata) -> <DeniedResponse>
+

Example

envoy.Allowed().Response().WithMetadata({ "foo": "bar" })
 
envoy.Denied(401).Response().WithMetadata({ "foo": "bar" })
 

\ No newline at end of file diff --git a/main/cel-extensions/index.html b/main/cel-extensions/index.html index 017df65..c3df799 100644 --- a/main/cel-extensions/index.html +++ b/main/cel-extensions/index.html @@ -1 +1 @@ - CEL extensions - Kyverno Envoy Plugin

CEL extensions

The CEL engine used to evaluate variables and authorization rules has been extended with libraries to help processing the input CheckRequest and forge the corresponding CheckResponse.

Envoy plugin libraries

Common libraries

The libraries below are common CEL extensions enabled in the Kyverno Authz Server CEL engine:

Kubernetes libraries

The libraries below are imported from Kubernetes:

\ No newline at end of file + CEL extensions - Kyverno Envoy Plugin

CEL extensions

The CEL engine used to evaluate variables and authorization rules has been extended with libraries to help processing the input CheckRequest and forge the corresponding OkResponse and/or DeniedResponse.

Envoy plugin libraries

Common libraries

The libraries below are common CEL extensions enabled in the Kyverno Authz Server CEL engine:

Kubernetes libraries

The libraries below are imported from Kubernetes:

\ No newline at end of file diff --git a/main/policies/authorization-rules/index.html b/main/policies/authorization-rules/index.html index 2234f1f..11819d0 100644 --- a/main/policies/authorization-rules/index.html +++ b/main/policies/authorization-rules/index.html @@ -1,4 +1,4 @@ - Authorization rules - Kyverno Envoy Plugin

Authorization rules

An AuthorizationPolicy main element is the authorization rules defined in authorizations.

Every authorization rule must contain a CEL expression. It is expected to return an Envoy CheckResponse describing the decision made by the rule (or nothing if no decision is made).

Creating the Envoy CheckResponse can be a tedious task, you need to remember the different types names and format.

The CEL engine used to evaluate the authorization rules has been extended with a library to make the creation of CheckResponse easier. Browse the available libraries documentation for details.

Authorization rules

The policy below will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

apiVersion: envoy.kyverno.io/v1alpha1
+ Authorization rules - Kyverno Envoy Plugin      

Authorization rules

An AuthorizationPolicy main concern is to define authorization rules to deny or allow requests.

Every authorization rule is made of an optional match statement and a required response statement. Both statements are written in CEL.

If the match statement is present and evaluates to true, the response statement is used to create the response payload returned to the envoy proxy. Depending on the rule type, the response is expected to be an envoy.OkResponse or envoy.DeniedResponse.

Creating an OkResponse or DeniedResponse can be a tedious task, you need to remember the different types names and format.

The CEL engine used to evaluate the authorization rules has been extended with a library to make the creation of responses easier. Browse the available libraries documentation for details.

Evaluation order

  1. All deny rules are evaluated first, the first matching rule is used to send the deny response to the envoy proxy.
  2. If no deny rule matched, allow rules are evaluated and the first matching rule is used to send the response to the envoy proxy.
  3. If no rule matched, the request is allowed by default.

Info

When multiple policies are present, deny and allow rules are concatenated together in policy name alphabetical order.

Authorization rules

The policy below will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

apiVersion: envoy.kyverno.io/v1alpha1
 kind: AuthorizationPolicy
 metadata:
   name: demo
@@ -9,36 +9,18 @@
     expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("")
   - name: allowed
     expression: variables.force_authorized in ["enabled", "true"]
-  authorizations:
-    # make an authorisation decision based on the value of `variables.allowed`
-    # - allow the request if it is `true`
-    # - deny the request with 403 status code if it is `false`
-  - expression: >
-      variables.allowed
-        ? envoy.Allowed().Response()
-        : envoy.Denied(403).Response()
-

In this simple rule:

  • envoy.Allowed().Response()

    Creates a CheckResponse to allow the request

  • envoy.Denied(403).Response()

    Creates a CheckResponse to deny the request with status code 403

However, we can do a lot more with Envoy's CheckResponse. Envoy can add or remove headers, query parameters, register dynamic metadata passed along the filters chain, and even change the response body.

dynamic metadata

Multiple rules

In the example above, we combined allow and denied response handling in a single expression. However it is possible to use multiple expressions, the first one returning a non null response will be used by the Kyverno Authz Server:

apiVersion: envoy.kyverno.io/v1alpha1
-kind: AuthorizationPolicy
-metadata:
-  name: demo
-spec:
-  failurePolicy: Fail
-  variables:
-  - name: force_authorized
-    expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("")
-  - name: allowed
-    expression: variables.force_authorized in ["enabled", "true"]
-  authorizations:
-    # allow the request if `variables.allowed` is `true`
-    # or delegate the decision to the next rule
-  - expression: >
-      variables.allowed
-        ? envoy.Allowed().Response()
-        : null
-    # deny the request with 403 status code
-  - expression: >
+  # make an authorisation decision based on the value of `variables.allowed`
+  # - deny the request with 403 status code if it is `false`
+  # - else allow the request
+  deny:
+  - match: >
+      !variables.allowed
+    response: >
       envoy.Denied(403).Response()
-

The hard way

Below is the same policy, creating the CheckResponses manually.

apiVersion: envoy.kyverno.io/v1alpha1
+  allow:
+  - response: >
+      envoy.Allowed().Response()
+

In this simple rule:

  • envoy.Allowed().Response()

    Creates an OkResponse to allow the request

  • envoy.Denied(403).Response()

    Creates a DeniedResponse to deny the request with status code 403

However, we can do a lot more. Envoy can add or remove headers, query parameters, register dynamic metadata passed along the filters chain, and even change the response body.

dynamic metadata

The hard way

Below is the same policy, creating the envoy.OkResponse and envoy.DeniedResponse manually.

apiVersion: envoy.kyverno.io/v1alpha1
 kind: AuthorizationPolicy
 metadata:
   name: demo
@@ -49,25 +31,28 @@
     expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("")
   - name: allowed
     expression: variables.force_authorized in ["enabled", "true"]
-  authorizations:
-  - expression: >
-      variables.allowed
-        ? envoy.service.auth.v3.CheckResponse{
-            status: google.rpc.Status{
-              code: 0
-            },
-            ok_response: envoy.service.auth.v3.OkHttpResponse{}
-          }
-        : envoy.service.auth.v3.CheckResponse{
-            status: google.rpc.Status{
-              code: 7
-            },
-            denied_response: envoy.service.auth.v3.DeniedHttpResponse{
-              status: envoy.type.v3.HttpStatus{
-                code: 403
-              }
-            }
+  deny:
+  - match: >
+      !variables.allowed
+    response: >
+      envoy.DeniedResponse{
+        status: google.rpc.Status{
+          code: 7
+        },
+        denied_response: envoy.service.auth.v3.DeniedHttpResponse{
+          status: envoy.type.v3.HttpStatus{
+            code: 403
           }
+        }
+      }
+  allow:
+  - response: >
+      envoy.OkResponse{
+        status: google.rpc.Status{
+          code: 0
+        },
+        ok_response: envoy.service.auth.v3.OkHttpResponse{}
+      }
 

Advanced example

This second policy showcases a more advanced example.

apiVersion: envoy.kyverno.io/v1alpha1
 kind: AuthorizationPolicy
 metadata:
@@ -80,32 +65,31 @@
     expression: object.attributes.request.http.headers[?"x-force-unauthenticated"].orValue("") in ["enabled", "true"]
   - name: metadata
     expression: '{"my-new-metadata": "my-new-value"}'
-  authorizations:
+  deny:
     # if force_unauthenticated -> 401
-  - expression: >
+  - match: >
       variables.force_unauthenticated
-        ? envoy
-            .Denied(401)
-            .WithBody("Authentication Failed")
-            .Response()
-            .WithMetadata(variables.metadata)
-        : null
-    # if force_authorized -> 200
-  - expression: >
-      variables.force_authorized
-        ? envoy
-            .Allowed()
-            .WithHeader("x-validated-by", "my-security-checkpoint")
-            .WithoutHeader("x-force-authorized")
-            .WithResponseHeader("x-add-custom-response-header", "added")
-            .Response()
-            .WithMetadata(variables.metadata)
-        : null
-    # else -> 403
-  - expression: >
+    response: >
+      envoy
+        .Denied(401)
+        .WithBody("Authentication Failed")
+        .Response()
+    # if not force_authorized -> 403
+  - match: >
+      !variables.force_authorized
+    response: >
       envoy
         .Denied(403)
         .WithBody("Unauthorized Request")
         .Response()
+  allow:
+    # else -> 200
+  - response: >
+      envoy
+        .Allowed()
+        .WithHeader("x-validated-by", "my-security-checkpoint")
+        .WithoutHeader("x-force-authorized")
+        .WithResponseHeader("x-add-custom-response-header", "added")
+        .Response()
         .WithMetadata(variables.metadata)
 

Notice this policy uses helper functions:

  • envoy.Allowed

    To create an OK http response

  • envoy.Denied

    To create a DENIED http response

  • Response

    To create a check response from an http response

  • WithHeader

    To add a request header

  • WithoutHeader

    To remove a request header

  • WithResponseHeader

    To add a response header

  • WithBody

    To modify the response body

  • WithMetadata

    To add dynamic metadata in the envoy filter chain (this is useful when you want to pass data to another filter in the chain or you want to print it in the application logs)

Info

The full documentation of the CEL Envoy library is available here.

\ No newline at end of file diff --git a/main/policies/failure-policy/index.html b/main/policies/failure-policy/index.html index 23420a2..0b87ca9 100644 --- a/main/policies/failure-policy/index.html +++ b/main/policies/failure-policy/index.html @@ -10,11 +10,11 @@ expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("") - name: allowed expression: variables.force_authorized in ["enabled", "true"] - authorizations: - - expression: > - variables.allowed - ? envoy.Allowed().Response() - : envoy.Denied(403).Response() + deny: + - match: > + !variables.allowed + response: > + envoy.Denied(403).Response()

Ignore

apiVersion: envoy.kyverno.io/v1alpha1
 kind: AuthorizationPolicy
 metadata:
@@ -27,9 +27,9 @@
     expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("")
   - name: allowed
     expression: variables.force_authorized in ["enabled", "true"]
-  authorizations:
-  - expression: >
-      variables.allowed
-        ? envoy.Allowed().Response()
-        : envoy.Denied(403).Response()
+  deny:
+  - match: >
+      !variables.allowed
+    response: >
+      envoy.Denied(403).Response()
 
\ No newline at end of file diff --git a/main/policies/index.html b/main/policies/index.html index 64e0030..2ec8d8a 100644 --- a/main/policies/index.html +++ b/main/policies/index.html @@ -3,15 +3,24 @@ metadata: name: demo spec: + # if something fails the request will be denied failurePolicy: Fail variables: + # `force_authorized` references the 'x-force-authorized' header + # from the envoy check request (or '' if not present) - name: force_authorized expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("") + # `allowed` will be `true` if `variables.force_authorized` has the + # value 'enabled' or 'true' - name: allowed expression: variables.force_authorized in ["enabled", "true"] - authorizations: - - expression: > - variables.allowed - ? envoy.Allowed().Response() - : envoy.Denied(403).Response() -

Envoy External Authorization

The Kyverno Authz Server implements the Envoy External Authorization API.

A Kyverno AuthorizationPolicy analyses an Envoy CheckRequest and can make a decision by returning an Envoy CheckResponse (or nothing if no decision is made).

CEL language

An AuthorizationPolicy uses the CEL language to process the CheckRequest sent by Envoy.

CEL is an expression language that’s fast, portable, and safe to execute in performance-critical applications.

Policy structure

A Kyverno AuthorizationPolicy is made of:

\ No newline at end of file + deny: + # make an authorisation decision based on the value of `variables.allowed` + - match: > + !variables.allowed + response: > + envoy.Denied(403).Response() + allow: + - response: > + envoy.Allowed().Response() +

Envoy External Authorization

The Kyverno Authz Server implements the Envoy External Authorization API.

A Kyverno AuthorizationPolicy analyses an Envoy CheckRequest and can make a decision by returning an OkResponse or DeniedResponse.

CEL language

An AuthorizationPolicy uses the CEL language to process the CheckRequest sent by Envoy.

CEL is an expression language that’s fast, portable, and safe to execute in performance-critical applications.

Policy structure

A Kyverno AuthorizationPolicy is made of:

\ No newline at end of file diff --git a/main/policies/variables/index.html b/main/policies/variables/index.html index ead050c..8ac122e 100644 --- a/main/policies/variables/index.html +++ b/main/policies/variables/index.html @@ -13,10 +13,10 @@ # value 'enabled' or 'true' - name: allowed expression: variables.force_authorized in ["enabled", "true"] - authorizations: + deny: # make an authorisation decision based on the value of `variables.allowed` - - expression: > - variables.allowed - ? envoy.Allowed().Response() - : envoy.Denied(403).Response() + - match: > + !variables.allowed + response: > + envoy.Denied(403).Response()
\ No newline at end of file diff --git a/main/quick-start/authz-server/index.html b/main/quick-start/authz-server/index.html index 75cb759..ce1f92f 100644 --- a/main/quick-start/authz-server/index.html +++ b/main/quick-start/authz-server/index.html @@ -29,7 +29,9 @@ kubectl label namespace kyverno istio-injection=enabled # deploy the kyverno authz server -helm install kyverno-authz-server --namespace kyverno --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server +helm install kyverno-authz-server --namespace kyverno --wait \ + --repo https://kyverno.github.io/kyverno-envoy-plugin \ + kyverno-authz-server

Deploy a sample application

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace
 kubectl create ns demo
 
@@ -37,7 +39,8 @@
 kubectl label namespace demo istio-injection=enabled
 
 # deploy the httpbin application
-kubectl apply -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml -n demo
+kubectl apply -n demo -f \
+  https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml
 

Deploy an Istio AuthorizationPolicy

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy
 kubectl apply -f - <<EOF
 apiVersion: security.istio.io/v1
@@ -56,7 +59,7 @@
   provider:
     name: kyverno-authz-server.local
 [...]
-

Deploy a Kyverno AuthorizationPolicy

A Kyverno AuthorizationPolicy defines the rules used by the Kyverno authz server to make a decision based on a given Envoy CheckRequest.

It uses the CEL language to analyse the incoming CheckRequest and is expected to produce a CheckResponse in return.

# deploy kyverno authorization policy
+

Deploy a Kyverno AuthorizationPolicy

A Kyverno AuthorizationPolicy defines the rules used by the Kyverno authz server to make a decision based on a given Envoy CheckRequest.

It uses the CEL language to analyse the incoming CheckRequest and is expected to produce an OkResponse or DeniedResponse in return.

# deploy kyverno authorization policy
 kubectl apply -f - <<EOF
 apiVersion: envoy.kyverno.io/v1alpha1
 kind: AuthorizationPolicy
@@ -69,13 +72,13 @@
     expression: object.attributes.request.http.headers[?"x-force-authorized"].orValue("")
   - name: allowed
     expression: variables.force_authorized in ["enabled", "true"]
-  authorizations:
-  - expression: >
-      variables.allowed
-        ? envoy.Allowed().Response()
-        : envoy.Denied(403).Response()
+  deny:
+  - match: >
+      !variables.allowed
+    response: >
+      envoy.Denied(403).Response()
 EOF
-

This simple policy will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

Testing

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

Start an in-cluster shell

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell
+

This simple policy will deny requests if they don't contain the header x-force-authorized with the value enabled or true.

Testing

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

Start an in-cluster shell

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell
 kubectl run -i -t busybox --image=alpine --restart=Never -n demo
 

Install curl

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl
 apk add curl
diff --git a/main/reference/json-schemas/index.html b/main/reference/json-schemas/index.html
index 4949579..533ef70 100644
--- a/main/reference/json-schemas/index.html
+++ b/main/reference/json-schemas/index.html
@@ -11,31 +11,32 @@
     expression: object.attributes.request.http.headers[?"x-force-unauthenticated"].orValue("") in ["enabled", "true"]
   - name: metadata
     expression: '{"my-new-metadata": "my-new-value"}'
-  authorizations:
+  deny:
     # if force_unauthenticated -> 401
-  - expression: >
+  - match: >
       variables.force_unauthenticated
-        ? envoy
-            .Denied(401)
-            .WithBody("Authentication Failed")
-            .Response()
-            .WithMetadata(variables.metadata)
-        : null
-    # if force_authorized -> 200
-  - expression: >
-      variables.force_authorized
-        ? envoy
-            .Allowed()
-            .WithHeader("x-validated-by", "my-security-checkpoint")
-            .WithoutHeader("x-force-authorized")
-            .WithResponseHeader("x-add-custom-response-header", "added")
-            .Response()
-            .WithMetadata(variables.metadata)
-        : null
-    # else -> 403
-  - expression: >
+    response: >
+      envoy
+        .Denied(401)
+        .WithBody("Authentication Failed")
+        .Response()
+        .WithMetadata(variables.metadata)
+    # if not force_authorized -> 403
+  - match: >
+      !variables.force_authorized
+    response: >
       envoy
         .Denied(403)
         .WithBody("Unauthorized Request")
         .Response()
+  allow:
+    # else -> 200
+  - response: >
+      envoy
+        .Allowed()
+        .WithHeader("x-validated-by", "my-security-checkpoint")
+        .WithoutHeader("x-force-authorized")
+        .WithResponseHeader("x-add-custom-response-header", "added")
+        .Response()
+        .WithMetadata(variables.metadata)
 
\ No newline at end of file diff --git a/main/search/search_index.json b/main/search/search_index.json index d8aa83f..2145001 100644 --- a/main/search/search_index.json +++ b/main/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"cel-extensions/","title":"CEL extensions","text":"

The CEL engine used to evaluate variables and authorization rules has been extended with libraries to help processing the input CheckRequest and forge the corresponding CheckResponse.

"},{"location":"cel-extensions/#envoy-plugin-libraries","title":"Envoy plugin libraries","text":""},{"location":"cel-extensions/#common-libraries","title":"Common libraries","text":"

The libraries below are common CEL extensions enabled in the Kyverno Authz Server CEL engine:

"},{"location":"cel-extensions/#kubernetes-libraries","title":"Kubernetes libraries","text":"

The libraries below are imported from Kubernetes:

"},{"location":"cel-extensions/envoy/","title":"Envoy library","text":"

The envoy library adds some types and function to simplify the creation of Envoy CheckResponse objects.

"},{"location":"cel-extensions/envoy/#types","title":"Types","text":""},{"location":"cel-extensions/envoy/#checkrequest","title":"<CheckRequest>","text":"

CEL Type / Proto: envoy.service.auth.v3.CheckRequest

"},{"location":"cel-extensions/envoy/#checkresponse","title":"<CheckResponse>","text":"

CEL Type / Proto: envoy.service.auth.v3.CheckResponse

"},{"location":"cel-extensions/envoy/#okhttpresponse","title":"<OkHttpResponse>","text":"

CEL Type / Proto: envoy.service.auth.v3.OkHttpResponse

"},{"location":"cel-extensions/envoy/#deniedhttpresponse","title":"<DeniedHttpResponse>","text":"

CEL Type / Proto: envoy.service.auth.v3.DeniedHttpResponse

"},{"location":"cel-extensions/envoy/#metadata","title":"<Metadata>","text":"

CEL Type / Proto: google.protobuf.Struct

"},{"location":"cel-extensions/envoy/#headervalueoption","title":"<HeaderValueOption>","text":"

CEL Type / Proto: envoy.config.core.v3.HeaderValueOption

"},{"location":"cel-extensions/envoy/#queryparameter","title":"<QueryParameter>","text":"

CEL Type / Proto: envoy.config.core.v3.QueryParameter

"},{"location":"cel-extensions/envoy/#functions","title":"Functions","text":""},{"location":"cel-extensions/envoy/#envoyallowed","title":"envoy.Allowed","text":"

This function creates an <OkHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads","title":"Signature and overloads","text":"
envoy.Allowed() -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example","title":"Example","text":"
envoy.Allowed()\n
"},{"location":"cel-extensions/envoy/#envoydenied","title":"envoy.Denied","text":"

This function creates a <DeniedHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_1","title":"Signature and overloads","text":"
envoy.Denied(<int> code) -> <DeniedHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_1","title":"Example","text":"
envoy.Denied(401)\n
"},{"location":"cel-extensions/envoy/#envoyresponse","title":"envoy.Response","text":"

This function creates a <CheckResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_2","title":"Signature and overloads","text":"

envoy.Response(<int> code) -> <CheckResponse>\n
envoy.Response(<OkHttpResponse> ok) -> <CheckResponse>\n
envoy.Response(<DeniedHttpResponse> denied) -> <CheckResponse>\n

"},{"location":"cel-extensions/envoy/#example_2","title":"Example","text":"

// ok\nenvoy.Response(0)\n\n// permission denied\nenvoy.Response(7)\n
envoy.Response(envoy.Allowed())\n
envoy.Response(envoy.Denied(401))\n

"},{"location":"cel-extensions/envoy/#envoyheader","title":"envoy.Header","text":"

This function creates an <HeaderValueOption> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_3","title":"Signature and overloads","text":"
envoy.Header(<string> key, <string> value) -> <HeaderValueOption>\n
"},{"location":"cel-extensions/envoy/#example_3","title":"Example","text":"
envoy.Header(\"foo\", \"bar\")\n
"},{"location":"cel-extensions/envoy/#envoyqueryparam","title":"envoy.QueryParam","text":"

This function creates a <QueryParameter> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_4","title":"Signature and overloads","text":"
envoy.QueryParam(<string> key, <string> value) -> <QueryParameter>\n
"},{"location":"cel-extensions/envoy/#example_4","title":"Example","text":"
envoy.QueryParam(\"foo\", \"bar\")\n
"},{"location":"cel-extensions/envoy/#withbody","title":"WithBody","text":"

This function sets the body of a <DeniedHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_5","title":"Signature and overloads","text":"
<DeniedHttpResponse>.WithBody(<string> body) -> <DeniedHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_5","title":"Example","text":"
envoy.Denied(401).WithBody(\"Unauthorized Request\")\n
"},{"location":"cel-extensions/envoy/#withheader","title":"WithHeader","text":"

This function adds a <HeaderValueOption>:

"},{"location":"cel-extensions/envoy/#signature-and-overloads_6","title":"Signature and overloads","text":"

<OkHttpResponse>.WithHeader(<HeaderValueOption> header) -> <OkHttpResponse>\n
<OkHttpResponse>.WithHeader(<string> key, <string> value) -> <OkHttpResponse>\n
<DeniedHttpResponse>.WithHeader(<HeaderValueOption> header) -> <DeniedHttpResponse>\n
<DeniedHttpResponse>.WithHeader(<string> key, <string> value) -> <DeniedHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_6","title":"Example","text":"

envoy.Allowed().WithHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Allowed().WithHeader(\"foo\", \"bar\")\n
envoy.Denied(401).WithHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Denied(401).WithHeader(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withoutheader","title":"WithoutHeader","text":"

This function marks a header to be removed when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_7","title":"Signature and overloads","text":"
<OkHttpResponse>.WithoutHeader(<string> header) -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_7","title":"Example","text":"
envoy.Allowed().WithoutHeader(\"foo\")\n
"},{"location":"cel-extensions/envoy/#withresponseheader","title":"WithResponseHeader","text":"

This function adds a <HeaderValueOption> when the response is sent downstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_8","title":"Signature and overloads","text":"

<OkHttpResponse>.WithResponseHeader(<HeaderValueOption> header) -> <OkHttpResponse>\n
<OkHttpResponse>.WithResponseHeader(<string> key, <string> value) -> <OkHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_8","title":"Example","text":"

envoy.Allowed().WithResponseHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Allowed().WithResponseHeader(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withqueryparam","title":"WithQueryParam","text":"

This function adds a <QueryParameter> to be added when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_9","title":"Signature and overloads","text":"

<OkHttpResponse>.WithQueryParam(<QueryParameter> param) -> <OkHttpResponse>\n
<OkHttpResponse>.WithQueryParam(<string> key, <string> value) -> <OkHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_9","title":"Example","text":"

envoy.Allowed().WithQueryParam(envoy.QueryParam(\"foo\", \"bar\"))\n
envoy.Allowed().WithQueryParam(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withoutqueryparam","title":"WithoutQueryParam","text":"

This function marks a query parameter to be removed when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_10","title":"Signature and overloads","text":"
<OkHttpResponse>.WithoutQueryParam(<string> param) -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_10","title":"Example","text":"
envoy.Allowed().WithoutQueryParam(\"foo\")\n
"},{"location":"cel-extensions/envoy/#keepemptyvalue","title":"KeepEmptyValue","text":"

This function sets the keep_empty_value field of an <HeaderValueOption> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_11","title":"Signature and overloads","text":"

<HeaderValueOption>.KeepEmptyValue() -> <HeaderValueOption>\n
<HeaderValueOption>.KeepEmptyValue(<bool> keep) -> <HeaderValueOption>\n

"},{"location":"cel-extensions/envoy/#example_11","title":"Example","text":"

envoy.Header(\"foo\", \"bar\").KeepEmptyValue()\n
envoy.Header(\"foo\", \"bar\").KeepEmptyValue(true)\n

"},{"location":"cel-extensions/envoy/#response","title":"Response","text":"

This function creates a <CheckResponse> object from an <OkHttpResponse> or <DeniedHttpResponse>.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_12","title":"Signature and overloads","text":"

<OkHttpResponse>.Response() -> <CheckResponse>\n
<DeniedHttpResponse>.Response() -> <CheckResponse>\n

"},{"location":"cel-extensions/envoy/#example_12","title":"Example","text":"

envoy.Allowed().Response()\n
envoy.Denied(401).Response()\n

"},{"location":"cel-extensions/envoy/#withmessage","title":"WithMessage","text":"

This function sets the status.message field of a <CheckResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_13","title":"Signature and overloads","text":"
<CheckResponse>.WithMessage(<string> message) -> <CheckResponse>\n
"},{"location":"cel-extensions/envoy/#example_13","title":"Example","text":"

envoy.Allowed().Response().WithMessage(\"hello world!\")\n
envoy.Denied(401).Response().WithMessage(\"hello world!\")\n

"},{"location":"cel-extensions/envoy/#withmetadata","title":"WithMetadata","text":"

This function sets the dynamic_metadata field of a <CheckResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_14","title":"Signature and overloads","text":"
<CheckResponse>.WithMetadata(<Metadata> metadata) -> <CheckResponse>\n
"},{"location":"cel-extensions/envoy/#example_14","title":"Example","text":"

envoy.Allowed().Response().WithMetadata({ \"foo\": \"bar\" })\n
envoy.Denied(401).Response().WithMetadata({ \"foo\": \"bar\" })\n

"},{"location":"cel-extensions/jwt/","title":"Jwt library","text":"

Policies have native functionality to decode and verify the contents of JWT tokens in order to enforce additional authorization logic on requests.

"},{"location":"cel-extensions/jwt/#types","title":"Types","text":""},{"location":"cel-extensions/jwt/#token","title":"<Token>","text":"

CEL Type / Proto jwt.Token

Field CEL Type / Proto Docs Valid bool Header google.protobuf.Struct Docs Claims google.protobuf.Struct Docs"},{"location":"cel-extensions/jwt/#functions","title":"Functions","text":""},{"location":"cel-extensions/jwt/#jwtdecode","title":"jwt.Decode","text":"

The jwt.Decode function decodes and validates a JWT token. It accepts two arguments: the token and the secret to verify the signature.

"},{"location":"cel-extensions/jwt/#signature-and-overloads","title":"Signature and overloads","text":"
jwt.Decode(<string> token, <string> key) -> <Token>\n
"},{"location":"cel-extensions/jwt/#example","title":"Example","text":"
jwt.Decode(\"eyJhbGciOiJIUzI1NiI....\", \"secret\")\n
"},{"location":"community/","title":"Community","text":"

The Kyverno Envoy Plugin has a growing community and we would definitely love to see you join and contribute.

Everyone is welcome to make suggestions, report bugs, open feature requests, contribute code or docs, participate in discussions, write blogs or anything that can benefit the project.

The Kyverno Envoy Plugin is built and maintained under the Kyverno umbrella but decisions are Community driven Everyone's voice matters

"},{"location":"community/#slack-channel","title":"Slack channel","text":"

Join our slack channel #kyverno to meet with users, contributors and maintainers.

"},{"location":"community/#roadmap","title":"RoadMap","text":"

For detailed information on our planned features and upcoming updates, please view our Roadmap.

"},{"location":"community/#contributing","title":"Contributing","text":"

Please read the contributing guide for details around:

  1. Code of Conduct
  2. Code Culture
  3. Details on how to contribute
"},{"location":"community/#adopters","title":"Adopters","text":"

If you are using the Kyverno Envoy Plugin and want to share it publicly we always appreciate a bit of support. Pull requests to the ADOPTERS LIST will put a smile on our faces

"},{"location":"community/contribute/","title":"Contributing","text":"

Kyverno Envoy Plugin, developed by Kyverno, is an advanced end-to-end testing tool for Kubernetes. Our community plays a crucial role in shaping the project by reporting bugs, suggesting features, and improving documentation.

We aim to make our issue tracker, discussion board, and documentation well-structured and easy to navigate. By following our guidelines, you can help us address your requests efficiently.

"},{"location":"community/contribute/#how-you-can-contribute","title":"How you can contribute","text":"

We appreciate your efforts in reporting bugs, requesting features, and engaging in discussions. Here's how you can contribute:

"},{"location":"community/contribute/#creating-an-issue","title":"Creating an issue","text":""},{"location":"community/contribute/#contributing_1","title":"Contributing","text":""},{"location":"community/contribute/#checklist","title":"Checklist","text":"

Before interacting within the project, please consider the following questions to ensure you're using the correct issue template and providing all necessary information.

Issues, discussions, and comments are forever

Please note that everything you write is permanent and will remain for everyone to read \u2013 forever. Therefore, please always be nice and constructive, follow our contribution guidelines, and comply with our Code of Conduct.

"},{"location":"community/contribute/#before-creating-an-issue","title":"Before creating an issue","text":""},{"location":"community/contribute/#before-asking-a-question","title":"Before asking a question","text":""},{"location":"community/contribute/#before-commenting","title":"Before commenting","text":""},{"location":"community/contribute/#rights-and-responsibilities","title":"Rights and responsibilities","text":"

As maintainers, we are entrusted with the responsibility to moderate communication within our community, including the authority to close, remove, reject, or edit issues, discussions, comments, commits, and to block users who do not align with our contribution guidelines and our Code of Conduct. This role requires us to be actively involved in maintaining the integrity and positive atmosphere of our community. Upholding these standards decisively ensures a respectful and inclusive environment for all members.

"},{"location":"community/contribute/#code-of-conduct","title":"Code of Conduct","text":"

Our Code of Conduct outlines the expectation for all community members to treat one another with respect, employing inclusive and welcoming language. Our commitment is to foster a positive and supportive environment, free of inappropriate, offensive, or harmful behavior.

We take any violations seriously and will take appropriate action in response to uphold these values.1

"},{"location":"community/contribute/#incomplete-issues-and-duplicates","title":"Incomplete issues and duplicates","text":"

We have invested significant time and effort in the setup of our contribution process, ensuring that we assess the essential requirements for reviewing and responding to issues effectively. Each field in our issue templates is thoughtfully designed to help us fully understand your concerns and the nature of your matter. We encourage all members to utilize the search function before submitting new issues or starting discussions to help avoid duplicates. Your cooperation is crucial in keeping our community's discussions constructive and organized.

  1. Warning and blocking policy: Given the increasing popularity of our project and our commitment to a healthy community, we've defined clear guidelines on how we proceed with violations:

    1.1. First warning: Users displaying repeated inappropriate, offensive, or harmful behavior will receive a first warning. This warning serves as a formal notice that their behavior is not in alignment with our community standards and Code of Conduct. The first warning is permanent.

    1.2. Second warning and opportunity for resolution: If the behavior persists, a second warning will be issued. Upon receiving the second warning, the user will be given a 5-day period for reflection, during which they are encouraged to publicly explain or apologize for their actions. This period is designed to offer an opportunity for openly clearing out any misunderstanding.

    1.3. Blocking: Should there be no response or improvement in behavior following the second warning, we reserve the right to block the user from the community and repository. Blocking is considered a last resort, used only when absolutely necessary to protect the community's integrity and positive atmosphere.

    Blocking has been an exceptionally rare necessity in our overwhelmingly positive community, highlighting our preference for constructive dialogue and mutual respect. It aims to protect our community members and team.\u00a0\u21a9

"},{"location":"community/making-a-pull-request/","title":"Pull Requests","text":"

You can contribute by making a pull request that will be reviewed by maintainers and integrated into the main repository when the changes made are approved. You can contribute bug fixes, documentation changes, or new functionalities.

Considering a pull request

Before deciding to spend effort on making changes and creating a pull request, please discuss what you intend to do. If you are responding to what you think might be a bug, please issue a bug report first. If you intend to work on documentation, create a documentation issue. If you want to work on a new feature, please create a change request.

Keep in mind the guidance given and let people advise you. It might be that there are easier solutions to the problem you perceive and want to address. It might be that what you want to achieve can already be done by configuration or [customization].

"},{"location":"community/making-a-pull-request/#learning-about-pull-requests","title":"Learning about pull requests","text":"

Pull requests are a concept layered on top of Git by services that provide Git hosting. Before you consider making a pull request, you should familiarize yourself with the documentation on GitHub, the service we are using. The following articles are of particular importance:

  1. Forking a repository
  2. Creating a pull request from a fork
  3. Creating a pull request

Note that they provide tailored documentation for different operating systems and different ways of interacting with GitHub. We do our best in the documentation here to describe the process as it applies but cannot cover all possible combinations of tools and ways of doing things. It is also important that you understand the concept of a pull-request in general before continuing.

"},{"location":"community/making-a-pull-request/#pull-request-process","title":"Pull request process","text":"

In the following, we describe the general process for making pull requests. The aim here is to provide the 30k ft overview before describing details later on.

"},{"location":"community/making-a-pull-request/#preparing-changes-and-draft-pr","title":"Preparing changes and draft PR","text":"

The diagram below describes what typically happens to repositories in the process or preparing a pull request. We will be discussing the review-revise process below. It is important that you understand the overall process first before you worry about specific commands. This is why we cover this first before providing instructions below.

sequenceDiagram\n  autonumber\n\n  participant upstream\n  participant PR\n  participant fork\n  participant local\n\n  upstream ->> fork: fork on GitHub\n  fork ->> local: clone to local\n  local ->> local: branch\n  loop prepare\n    loop push\n      loop edit\n        local ->> local: commit\n      end\n      local ->> fork: push\n    end\n    upstream ->> fork: merge in any changes\n    fork ->>+ PR: create draft PR\n    PR ->> PR: review your changes\n  end
  1. Fork the Repository: Fork the upstream repository on GitHub to create your own copy.
  2. Clone to Local: Clone your fork to your local machine.
  3. Create a Branch: Create a topic branch for your changes.
  4. Set Up Development Environment: Follow the instructions to set up a development environment.
  5. Iterate and Commit: Make incremental changes and commit them with meaningful messages.
  6. Push Regularly: Push your commits to your fork regularly.
  7. Merge Changes from Upstream: Regularly merge changes from the original upstream repository to avoid conflicts.
  8. Create a Draft Pull Request: Once satisfied with your changes, create a draft pull request for early feedback.
  9. Review and Revise: Review your work critically, address feedback, and refine your changes.
"},{"location":"community/making-a-pull-request/#finalizing","title":"Finalizing","text":"

Once you are happy with your changes, you can move to the next step, finalizing your pull request and asking for a more formal and detailed review. The diagram below shows the process:

sequenceDiagram\n  autonumber\n  participant upstream\n  participant PR\n  participant fork\n  participant local\n\n  activate PR\n  PR ->> PR: finalize PR\n  loop review\n    loop discuss\n      PR ->> PR: request review\n      PR ->> PR: discussion\n      local ->> fork: push further changes\n    end\n    PR ->> upstream: merge (and squash)\n    deactivate PR\n    fork ->> fork: delete branch\n    upstream ->> fork: pull\n    local ->> local: delete branch\n    fork ->> local: pull\n  end\n
  1. Finalize PR: Signal that your changes are ready for review.
  2. Request Review: Ask the maintainer to review your changes.
  3. Discuss and Revise: Engage in discussions, make necessary revisions, and iterate.
  4. Merge and Squash: Once approved, the maintainer will merge and possibly squash your commits.
  5. Clean Up: Delete the branch used for the PR from both your fork and local clone.
"},{"location":"community/reporting-a-bug/","title":"Bug Reports","text":"

If you think you have discovered a bug, you can help us by submitting an issue in our public issue tracker, following this guide.

"},{"location":"community/reporting-a-bug/#before-creating-an-issue","title":"Before Creating an Issue","text":"

With numerous users, issues are created regularly. The maintainers of this project strive to address bugs promptly. By following this guide, you will know exactly what information we need to help you quickly.

Please do the following before creating an issue:

"},{"location":"community/reporting-a-bug/#upgrade-to-latest-version","title":"Upgrade to Latest Version","text":"

Chances are that the bug you discovered was already fixed in a subsequent version. Before reporting an issue, ensure that you're running the latest version.

Bug fixes are not backported

Please understand that only bugs that occur in the latest version will be addressed. Also, to reduce duplicate efforts, fixes cannot always be backported to earlier versions.

"},{"location":"community/reporting-a-bug/#remove-customizations","title":"Remove Customizations","text":"

If you're using customizations like additional configurations, remove them before reporting a bug. We can't offer official support for bugs that might hide in your overrides, so make sure to omit custom settings from your configuration files.

Don't be shy to ask on our discussion board for help if you run into problems.

"},{"location":"community/reporting-a-bug/#search-for-solutions","title":"Search for Solutions","text":"

At this stage, we know that the problem persists in the latest version and is not caused by any of your customizations. However, the problem might result from a small typo or a syntactical error in a configuration file.

Before creating a bug report, save time for us and yourself by doing some research:

  1. Search our documentation for relevant sections related to your problem. Ensure everything is configured correctly.
  2. [Search our issue tracker] as another user might have already reported the same problem.
  3. [Search our discussion board] to see if other users are facing similar issues and find possible solutions.

Keep track of all search terms and relevant links; you'll need them in the bug report.

If you still haven't found a solution to your problem, create an issue. It's now likely that you've encountered something new. Read the following section to learn how to create a complete and helpful bug report.

"},{"location":"community/reporting-a-bug/#issue-template","title":"Issue Template","text":"

We have created a new issue template to make the bug reporting process as simple as possible and more efficient for our community and us. It consists of the following parts:

"},{"location":"community/reporting-a-bug/#title","title":"Title","text":"

A good title is short and descriptive. It should be a one-sentence executive summary of the issue, so the impact and severity of the bug can be inferred from the title.

Example Clear apply command fails with specific CRD Wordy The apply command fails when used with a certain Custom Resource Definition Unclear Command does not work Useless Help"},{"location":"community/reporting-a-bug/#context","title":"Context optional","text":"

Before describing the bug, you can provide additional context to help us understand what you were trying to achieve. Explain the circumstances under which the bug happens, and what you think might be relevant. Don't describe the bug here.

"},{"location":"community/reporting-a-bug/#bug-description","title":"Bug Description","text":"

Provide a clear, focused, specific, and concise summary of the bug you encountered. Explain why you think this is a bug that should be reported, and not to one of its dependencies. Follow these principles:

"},{"location":"community/reporting-a-bug/#related-links","title":"Related Links","text":"

Share links to relevant sections of our documentation and any related issues or discussions. This helps us improve our documentation and understand the problem better.

"},{"location":"community/reporting-a-bug/#reproduction","title":"Reproduction","text":"

A minimal reproduction is essential for a well-written bug report, as it allows us to recreate the conditions necessary to inspect the bug. Follow the guide to create a reproduction:

[ Create reproduction][Create reproduction]{ .md-button .md-button--primary }

After creating the reproduction, you should have a .zip file, ideally not larger than 1 MB. Drag and drop the .zip file into the issue field, which will automatically upload it to GitHub.

Don't share links to repositories

While linking to a repository is a common practice, we currently don't support this. The reproduction, created using the built-in info plugin, contains all necessary environment information.

"},{"location":"community/reporting-a-bug/#steps-to-reproduce","title":"Steps to Reproduce","text":"

List specific steps to follow when running your reproduction to observe the bug. Keep the steps concise and ensure nothing is left out. Use simple language and focus on continuity.

"},{"location":"community/reporting-a-bug/#browser","title":"Browser optional","text":"

If the bug only occurs in specific browsers, let us know which ones are affected. This field is optional, as it is only relevant for bugs that do not involve a crash when previewing or building your site.

Incognito Mode

Verify that the bug is not caused by a browser extension by switching to incognito mode. If the bug disappears, it is likely caused by an extension.

"},{"location":"community/reporting-a-bug/#checklist","title":"Checklist","text":"

Before submitting, ensure you have:

Thanks for following the guide and creating a high-quality bug report. We will take it from here.

"},{"location":"community/reporting-a-docs-issue/","title":"Documentation Issues","text":"

The documentation includes extensive information on features, configurations, customizations, and more. If you have found an inconsistency or see room for improvement, please follow this guide to submit an issue on our issue tracker.

"},{"location":"community/reporting-a-docs-issue/#issue-template","title":"Issue Template","text":"

Reporting a documentation issue is usually less involved than reporting a bug, as we don't need a [reproduction]. Please thoroughly read this guide before creating a new documentation issue, and provide the following information as part of the issue:

"},{"location":"community/reporting-a-docs-issue/#title","title":"Title","text":"

A good title should be a short, one-sentence description of the issue, containing all relevant information and keywords to simplify the search in our issue tracker.

Example Clear Clarify resource templating setup Unclear Missing information in the docs Useless Help"},{"location":"community/reporting-a-docs-issue/#description","title":"Description","text":"

Provide a clear and concise summary of the inconsistency or issue you encountered in the documentation or the documentation section that needs improvement. Explain why you think the documentation should be adjusted and describe the severity of the issue:

Why we need this: describing the problem clearly and concisely is a prerequisite for improving our documentation \u2013 we need to understand what's wrong so we can fix it.

"},{"location":"community/reporting-a-docs-issue/#related-links","title":"Related Links","text":"

After you describe the documentation section that needs to be adjusted, share the link to this specific documentation section and other possibly related sections. Use anchor links (permanent links) where possible, as it simplifies discovery.

Why we need this: providing the links to the documentation helps us understand which sections of our documentation need to be adjusted, extended, or overhauled.

"},{"location":"community/reporting-a-docs-issue/#proposed-change","title":"Proposed Change optional","text":"

Now that you have provided us with the description and links to the documentation sections, you can help us, maintainers, and the community by proposing an improvement. You can sketch out rough ideas or write a concrete proposal. This field is optional but very helpful.

Why we need this: an improvement proposal can be beneficial for other users who encounter the same issue, as they offer solutions before we maintainers can update the documentation.

"},{"location":"community/reporting-a-docs-issue/#checklist","title":"Checklist","text":"

Thanks for following the guide and providing valuable feedback for our documentation \u2013 you are almost done. The checklist ensures that you have read this guide and have worked to your best knowledge to provide us with every piece of information we need to improve it.

We'll take it from here.

"},{"location":"community/requesting-a-change/","title":"Change Requests","text":"

We value every idea or contribution from our community. Please follow this guide before submitting your change request in our public issue tracker. This helps us better understand the proposed change and how it will benefit our community.

"},{"location":"community/requesting-a-change/#before-creating-an-issue","title":"Before Creating an Issue","text":"

Before you invest time in submitting a change request, answer these questions to determine if your idea is a good fit and matches the project's philosophy and tone.

"},{"location":"community/requesting-a-change/#its-not-a-bug-its-a-feature","title":"It's Not a Bug, It's a Feature","text":"

Change requests suggest minor adjustments, new features, or influence the project's direction. They are not intended for reporting bugs. Refer to our bug reporting guide for that.

"},{"location":"community/requesting-a-change/#look-for-sources-of-inspiration","title":"Look for Sources of Inspiration","text":"

If your idea is implemented in another tool or framework, collect information on its implementation. This helps us evaluate its fit more quickly.

"},{"location":"community/requesting-a-change/#connect-with-our-community","title":"Connect with Our Community","text":"

Our discussion board is the best place to connect with our community. Seeking input from other users helps implement features that benefit a larger number of users.

Start a discussion

"},{"location":"community/requesting-a-change/#issue-template","title":"Issue Template","text":"

After doing the preliminary work, create a change request. Follow these steps:

"},{"location":"community/requesting-a-change/#title","title":"Title","text":"

A good title is short and descriptive, summarizing the idea so the potential impact and benefit can be inferred.

Example Clear Support for resource templating Wordy Add support for templating resources for easier testing Unclear Improve templating Useless Help"},{"location":"community/requesting-a-change/#context","title":"Context optional","text":"

Provide additional context to help us understand what you are trying to achieve. Explain the circumstances and relevant settings without describing the change request itself.

"},{"location":"community/requesting-a-change/#description","title":"Description","text":"

Provide a detailed and clear description of your idea. Explain why your idea is relevant and should be implemented here, not in one of its dependencies.

"},{"location":"community/requesting-a-change/#related-links","title":"Related Links","text":"

Provide any relevant links to issues, discussions, or documentation sections related to your change request. This helps us gain additional context.

"},{"location":"community/requesting-a-change/#use-cases","title":"Use Cases","text":"

Explain how your change request would work from an author's and user's perspective. What is the expected impact, and why does it benefit other users? Would it potentially break existing functionality?

"},{"location":"community/requesting-a-change/#visuals","title":"Visuals optional","text":"

If you have any visuals, such as sketches, screenshots, mockups, or external assets, present them in this section. If you have seen this change used in other tools, showcase and describe its implementation.

"},{"location":"community/requesting-a-change/#checklist","title":"Checklist","text":"

Thanks for following the guide and creating a high-quality change request. The checklist ensures that you have read this guide and provided all necessary information for us to review your idea.

We'll take it from here.

"},{"location":"community/requesting-a-change/#rejected-requests","title":"Rejected Requests","text":"

Your change request got rejected? We're sorry for that. We understand it can be frustrating, but we always need to consider the needs of our entire community. If you're unsure why your change request was rejected, please ask for clarification.

We consider the following principles when evaluating change requests:

If your idea was rejected, you can always implement it via [customization]. If you're unsure how or want to know if someone has already done it, get in touch with our community on the discussion board.

"},{"location":"performance/","title":"Performance","text":"

This page offers guidance and best practices for benchmarking the performance of the Kyverno Authz Server, helping users understand the associated overhead. It outlines an example setup for conducting benchmarks, various benchmarking scenarios, and key metrics to capture for assessing the impact of the Kyverno Authz Server.

"},{"location":"performance/#benchmark-setup","title":"Benchmark Setup","text":"

The benchmark setup consists of the following components:

"},{"location":"performance/#sample-application","title":"Sample Application","text":"

The first component is a simple Go application that provides information of books in the library books collection and exposes APIs to get, create and delete books collection. Check this out for more information about the Go test application .

"},{"location":"performance/#envoy","title":"Envoy","text":"

The second component is the Envoy proxy, which runs alongside the example application. The Envoy configuration defines an external authorization filter envoy.ext_authz for a gRPC authorization server.

The config uses Envoy's in-built gRPC client to make external gRPC calls.

static_resources:\n  listeners:\n  - address:\n      socket_address:\n        address: 0.0.0.0\n        port_value: 8000\n    filter_chains:\n    - filters:\n      - name: envoy.filters.network.http_connection_manager\n        typed_config:\n          \"@type\": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager\n          codec_type: auto\n          stat_prefix: ingress_http\n          route_config:\n            name: local_route\n            virtual_hosts:\n            - name: backend\n              domains:\n              - \"*\"\n              routes:\n              - match:\n                  prefix: \"/\"\n                route:\n                  cluster: service\n          http_filters:\n          - name: envoy.ext_authz\n            typed_config:\n              \"@type\": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz\n              transport_api_version: V3\n              with_request_body:\n                max_request_bytes: 8192\n                allow_partial_message: true\n              failure_mode_allow: false\n              grpc_service:\n                google_grpc:\n                  target_uri: 127.0.0.1:9191\n                  stat_prefix: ext_authz\n                timeout: 0.5s\n          - name: envoy.filters.http.router\n            typed_config:\n              \"@type\": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router\n  clusters:\n  - name: service\n    connect_timeout: 0.25s\n    type: strict_dns\n    lb_policy: round_robin\n    load_assignment:\n      cluster_name: service\n      endpoints:\n      - lb_endpoints:\n        - endpoint:\n            address:\n              socket_address:\n                address: 127.0.0.1\n                port_value: 8080\nadmin:\n  access_log_path: \"/dev/null\"\n  address:\n    socket_address:\n      address: 0.0.0.0\n      port_value: 8001\nlayered_runtime:\n  layers:\n    - name: static_layer_0\n      static_layer:\n        envoy:\n          resource_limits:\n            listener:\n              example_listener_name:\n                connection_limit: 10000\n        overload:\n          global_downstream_max_connections: 50000\n
"},{"location":"performance/#kyverno-authz-server","title":"Kyverno Authz Server","text":"

The third component is the Kyverno Authz Server itself, which is configured to load and enforce Kyverno policies on incoming requests.

"},{"location":"performance/#benchmark-scenarios","title":"Benchmark Scenarios","text":"

The following scenarios should be tested to compare the performance of the Kyverno Authz Server under different conditions:

  1. App Only: Requests are sent directly to the application, without Envoy or the Kyverno Authz Server.
  2. App and Envoy: Envoy is included in the request path, but the Kyverno Authz Server is not (i.e., Envoy External Authorization API is disabled).
  3. App, Envoy, and Kyverno: Envoy External Authorization API is enabled, and a sample real-world policy is loaded into the Kyverno Authz Server.
"},{"location":"performance/#load-testing-with-k6","title":"Load Testing with k6","text":"

To perform load testing, we'll use the k6 tool. Follow these steps:

  1. Install k6: Install k6 on your machine by following the instructions on the official website.

  2. Write the k6 script: Below is the example k6 script.

import http from 'k6/http';\nimport { check, group, sleep } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 100 }, // Ramp-up to 100 virtual users over 30 seconds\n    { duration: '1m', target: 100 }, // Stay at 100 virtual users for 1 minute\n    { duration: '30s', target: 0 }, // Ramp-down to 0 virtual users over 30 seconds\n  ],\n};\n\n/*\nReplace ip for every scenerio\nexport SERVICE_PORT=$(kubectl -n demo get service testapp -o jsonpath='{.spec.ports[?(@.port==8080)].nodePort}')\nexport SERVICE_HOST=$(minikube ip)\nexport SERVICE_URL=$SERVICE_HOST:$SERVICE_PORT\necho $SERVICE_URL\n\nhttp://192.168.49.2:31541\n\n*/\nconst BASE_URL = 'http://192.168.49.2:31541'; \n\nexport default function () {\n  group('GET /book with guest token', () => {\n    const res = http.get(`${BASE_URL}/book`, {\n      headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk' },\n    });\n    check(res, {\n      'is status 200': (r) => r.status === 200,\n    });\n  });\n\n  sleep(1); // Sleep for 1 second between iterations\n}\n
  1. Run the k6 test: Run the load test with the following command:
$ k6 run -f - <<EOF\nimport http from 'k6/http';\nimport { check, group, sleep } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 100 }, // Ramp-up to 100 virtual users over 30 seconds\n    { duration: '1m', target: 100 }, // Stay at 100 virtual users for 1 minute\n    { duration: '30s', target: 0 }, // Ramp-down to 0 virtual users over 30 seconds\n  ],\n};\n\n\nconst BASE_URL = 'http://192.168.49.2:31700'; // Replace with your application URL \n\nexport default function () {\n  group('GET /book with guest token', () => {\n    const res = http.get(`${BASE_URL}/book`, {\n      headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk' },\n    });\n    check(res, {\n      'is status 200': (r) => r.status === 200,\n    });\n  });\n\n  sleep(1); // Sleep for 1 second between iterations\n}\nEOF\n
  1. Analyze the results: Generate an json report with detailed insight by running:

k6 run --out json=report.json k6-script.js\n
5. Repeat for different scenarios:

"},{"location":"performance/#measuring-performance","title":"Measuring Performance","text":"

The following metrics should be measured to evaluate the performance impact of the Kyverno Authz Server:

Observations:

Correlation with k6 results:

"},{"location":"policies/","title":"Policies","text":"

A Kyverno AuthorizationPolicy is a custom Kubernetes resources and can be easily managed via Kubernetes APIs, GitOps workflows, and other existing tools.

"},{"location":"policies/#resource-scope","title":"Resource Scope","text":"

A Kyverno AuthorizationPolicy is a cluster-wide resource.

"},{"location":"policies/#api-group-and-kind","title":"API Group and Kind","text":"

An AuthorizationPolicy belongs to the envoy.kyverno.io/v1alpha1 group and can only be of kind AuthorizationPolicy.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\n
"},{"location":"policies/#envoy-external-authorization","title":"Envoy External Authorization","text":"

The Kyverno Authz Server implements the Envoy External Authorization API.

A Kyverno AuthorizationPolicy analyses an Envoy CheckRequest and can make a decision by returning an Envoy CheckResponse (or nothing if no decision is made).

"},{"location":"policies/#cel-language","title":"CEL language","text":"

An AuthorizationPolicy uses the CEL language to process the CheckRequest sent by Envoy.

CEL is an expression language that\u2019s fast, portable, and safe to execute in performance-critical applications.

"},{"location":"policies/#policy-structure","title":"Policy structure","text":"

A Kyverno AuthorizationPolicy is made of:

"},{"location":"policies/authorization-rules/","title":"Authorization rules","text":"

An AuthorizationPolicy main element is the authorization rules defined in authorizations.

Every authorization rule must contain a CEL expression. It is expected to return an Envoy CheckResponse describing the decision made by the rule (or nothing if no decision is made).

Creating the Envoy CheckResponse can be a tedious task, you need to remember the different types names and format.

The CEL engine used to evaluate the authorization rules has been extended with a library to make the creation of CheckResponse easier. Browse the available libraries documentation for details.

"},{"location":"policies/authorization-rules/#authorization-rules_1","title":"Authorization rules","text":"

The policy below will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n    # make an authorisation decision based on the value of `variables.allowed`\n    # - allow the request if it is `true`\n    # - deny the request with 403 status code if it is `false`\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\n

In this simple rule:

However, we can do a lot more with Envoy's CheckResponse. Envoy can add or remove headers, query parameters, register dynamic metadata passed along the filters chain, and even change the response body.

"},{"location":"policies/authorization-rules/#multiple-rules","title":"Multiple rules","text":"

In the example above, we combined allow and denied response handling in a single expression. However it is possible to use multiple expressions, the first one returning a non null response will be used by the Kyverno Authz Server:

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n    # allow the request if `variables.allowed` is `true`\n    # or delegate the decision to the next rule\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : null\n    # deny the request with 403 status code\n  - expression: >\n      envoy.Denied(403).Response()\n
"},{"location":"policies/authorization-rules/#the-hard-way","title":"The hard way","text":"

Below is the same policy, creating the CheckResponses manually.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n  - expression: >\n      variables.allowed\n        ? envoy.service.auth.v3.CheckResponse{\n            status: google.rpc.Status{\n              code: 0\n            },\n            ok_response: envoy.service.auth.v3.OkHttpResponse{}\n          }\n        : envoy.service.auth.v3.CheckResponse{\n            status: google.rpc.Status{\n              code: 7\n            },\n            denied_response: envoy.service.auth.v3.DeniedHttpResponse{\n              status: envoy.type.v3.HttpStatus{\n                code: 403\n              }\n            }\n          }\n
"},{"location":"policies/authorization-rules/#advanced-example","title":"Advanced example","text":"

This second policy showcases a more advanced example.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo-policy.example.com\nspec:\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: force_unauthenticated\n    expression: object.attributes.request.http.headers[?\"x-force-unauthenticated\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: metadata\n    expression: '{\"my-new-metadata\": \"my-new-value\"}'\n  authorizations:\n    # if force_unauthenticated -> 401\n  - expression: >\n      variables.force_unauthenticated\n        ? envoy\n            .Denied(401)\n            .WithBody(\"Authentication Failed\")\n            .Response()\n            .WithMetadata(variables.metadata)\n        : null\n    # if force_authorized -> 200\n  - expression: >\n      variables.force_authorized\n        ? envoy\n            .Allowed()\n            .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n            .WithoutHeader(\"x-force-authorized\")\n            .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n            .Response()\n            .WithMetadata(variables.metadata)\n        : null\n    # else -> 403\n  - expression: >\n      envoy\n        .Denied(403)\n        .WithBody(\"Unauthorized Request\")\n        .Response()\n        .WithMetadata(variables.metadata)\n

Notice this policy uses helper functions:

Info

The full documentation of the CEL Envoy library is available here.

"},{"location":"policies/failure-policy/","title":"Failure policy","text":"

FailurePolicy defines how to handle failures for the policy.

Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions.

Allowed values are:

If not set, the failure policy defaults to Fail.

Info

FailurePolicy does not define how validations that evaluate to false are handled.

"},{"location":"policies/failure-policy/#fail","title":"Fail","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  # if something fails the request will be denied\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\n
"},{"location":"policies/failure-policy/#ignore","title":"Ignore","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  # if something fails the failure will be ignored and the request will be allowed\n  failurePolicy: Ignore\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\n
"},{"location":"policies/variables/","title":"Variables","text":"

A Kyverno AuthorizationPolicy can define variables that will be made available to all authorization rules.

Variables can be used in composition of other expressions. Each variable is defined as a named CEL expression. The will be available under variables in other expressions of the policy.

The expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, variables must be sorted by the order of first appearance and acyclic.

Info

The incoming CheckRequest from Envoy is made available to the policy under the object identifier.

"},{"location":"policies/variables/#variables_1","title":"Variables","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n    # `force_authorized` references the 'x-force-authorized' header\n    # from the envoy check request (or '' if not present)\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n    # `allowed` will be `true` if `variables.force_authorized` has the\n    # value 'enabled' or 'true'\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n    # make an authorisation decision based on the value of `variables.allowed`\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\n
"},{"location":"quick-start/","title":"Quick start","text":"

The Kyverno Envoy Plugin is a powerful tool that integrates with the Envoy proxy.

It allows you to enforce Kyverno policies on incoming and outgoing traffic in a service mesh environment, providing an additional layer of security and control over your applications.

"},{"location":"quick-start/#overview","title":"Overview","text":"

Envoy is a Layer 7 proxy and communication bus tailored for large-scale, modern service-oriented architectures. Starting from version 1.7.0, Envoy includes an External Authorization filter that interfaces with an authorization service to determine the legitimacy of incoming requests.

This functionality allows authorization decisions to be offloaded to an external service, which can access the request context. The request context includes details such as the origin and destination of the network activity, as well as specifics of the network request (e.g., HTTP request). This information enables the external service to make a well-informed decision regarding the authorization of the incoming request processed by Envoy.

"},{"location":"quick-start/#what-is-the-kyverno-envoy-plugin","title":"What is the Kyverno Envoy Plugin?","text":"

The Kyverno Envoy Plugin is gRPC server that implements Envoy External Authorization API.

This allows you to enforce Kyverno policies on incoming and outgoing traffic in a service mesh environment, providing an additional layer of security and control over your applications. You can use this version of Kyverno to enforce fine-grained, context-aware access control policies with Envoy without modifying your microservice.

"},{"location":"quick-start/#how-does-this-work","title":"How does this work?","text":"

In addition to the Envoy sidecar, your application pods will include a Kyverno Authz Server component, either as a sidecar or as a separate pod. When Envoy receives an API request intended for your microservice, it consults the Kyverno Authz Server to determine whether the request should be permitted or not.

Performing policy evaluations locally with Envoy is advantageous, as it eliminates the need for an additional network hop for authorization checks, thus enhancing both performance and availability.

Info

The Kyverno Envoy Plugin is frequently deployed in Kubernetes environments as a sidecar container or as a separate pod. Additionally, it can be used in other environments as a standalone process running alongside Envoy.

"},{"location":"quick-start/#additional-resources","title":"Additional Resources","text":"

See the following pages on envoyproxy.io for more information on external authorization:

"},{"location":"quick-start/authz-server/","title":"Authz server","text":""},{"location":"quick-start/authz-server/#setup","title":"Setup","text":"

In this quick start guide we will deploy the Kyverno Authz Server inside a cluster.

Then you will interface Istio, an open source service mesh with the Kyverno Authz Server to delegate the request authorisation based on policies installed in the cluster.

"},{"location":"quick-start/authz-server/#prerequisites","title":"Prerequisites","text":""},{"location":"quick-start/authz-server/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"quick-start/authz-server/#configure-the-mesh","title":"Configure the mesh","text":"

We need to register the Kyverno Authz Server with Istio.

# configure the mesh\nistioctl install -y -f - <<EOF\napiVersion: install.istio.io/v1alpha1\nkind: IstioOperator\nspec:\n  meshConfig:\n    accessLogFile: /dev/stdout\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\nEOF\n

Notice that in the configuration, we define an extensionProviders section that points to the Kyverno Authz Server we will install in the next step:

[...]\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\n[...]\n
"},{"location":"quick-start/authz-server/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

The first step is to deploy the Kyverno Authz Server.

# create the kyverno namespace\nkubectl create ns kyverno\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace kyverno istio-injection=enabled\n\n# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server\n
"},{"location":"quick-start/authz-server/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace demo istio-injection=enabled\n\n# deploy the httpbin application\nkubectl apply -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml -n demo\n
"},{"location":"quick-start/authz-server/#deploy-an-istio-authorizationpolicy","title":"Deploy an Istio AuthorizationPolicy","text":"

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy\nkubectl apply -f - <<EOF\napiVersion: security.istio.io/v1\nkind: AuthorizationPolicy\nmetadata:\n  name: kyverno-authz-server\n  namespace: demo\nspec:\n  action: CUSTOM\n  provider:\n    name: kyverno-authz-server.local\n  rules:\n  - {} # empty rules, it will apply to all requests\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server extensionProvider you set in the Istio configuration:

[...]\n  provider:\n    name: kyverno-authz-server.local\n[...]\n
"},{"location":"quick-start/authz-server/#deploy-a-kyverno-authorizationpolicy","title":"Deploy a Kyverno AuthorizationPolicy","text":"

A Kyverno AuthorizationPolicy defines the rules used by the Kyverno authz server to make a decision based on a given Envoy CheckRequest.

It uses the CEL language to analyse the incoming CheckRequest and is expected to produce a CheckResponse in return.

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  authorizations:\n  - expression: >\n      variables.allowed\n        ? envoy.Allowed().Response()\n        : envoy.Denied(403).Response()\nEOF\n

This simple policy will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

"},{"location":"quick-start/authz-server/#testing","title":"Testing","text":"

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

"},{"location":"quick-start/authz-server/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"quick-start/authz-server/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"quick-start/authz-server/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send requests to the sample application and verify the result.

The following request will return 403 (denied by our policy):

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get\n

The following request will return 200 (allowed by our policy):

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"x-force-authorized: true\"\n
"},{"location":"quick-start/authz-server/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the quick start guide!

This tutorial demonstrated how to configure Istio\u2019s EnvoyFilter to utilize the Kyverno Authz Server as an external authorization service.

"},{"location":"quick-start/next-steps/","title":"Next steps","text":"

We covered the main components of the Kyverno Envoy Plugin.

Tip

If there's anything you would like to be improved, please reach out, we will be happy to discuss and improve as much as we can.

To continue exploring and learn more about the Kyverno Envoy Plugin:

"},{"location":"quick-start/sidecar-injector/","title":"Sidecar injector","text":"

This is not ready yet, hopefully it will be available soon!

"},{"location":"reference/","title":"Reference documentation","text":"

Info

Select an item in the navigation menu to browse a specific page.

"},{"location":"reference/json-schemas/","title":"JSON schemas","text":"

JSON schemas for the Kyverno Envoy Plugin are available:

They can be used to enable validation and autocompletion in your IDE.

"},{"location":"reference/json-schemas/#vs-code","title":"VS code","text":"

In VS code, simply add a comment on top of your YAML resources.

"},{"location":"reference/json-schemas/#authorizationpolicy","title":"AuthorizationPolicy","text":"
# yaml-language-server: $schema=https://raw.githubusercontent.com/kyverno/kyverno-envoy-plugin/main/.schemas/json/authorizationpolicy-envoy-v1alpha1.json\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo-policy.example.com\nspec:\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: force_unauthenticated\n    expression: object.attributes.request.http.headers[?\"x-force-unauthenticated\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: metadata\n    expression: '{\"my-new-metadata\": \"my-new-value\"}'\n  authorizations:\n    # if force_unauthenticated -> 401\n  - expression: >\n      variables.force_unauthenticated\n        ? envoy\n            .Denied(401)\n            .WithBody(\"Authentication Failed\")\n            .Response()\n            .WithMetadata(variables.metadata)\n        : null\n    # if force_authorized -> 200\n  - expression: >\n      variables.force_authorized\n        ? envoy\n            .Allowed()\n            .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n            .WithoutHeader(\"x-force-authorized\")\n            .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n            .Response()\n            .WithMetadata(variables.metadata)\n        : null\n    # else -> 403\n  - expression: >\n      envoy\n        .Denied(403)\n        .WithBody(\"Unauthorized Request\")\n        .Response()\n
"},{"location":"reference/apis/policy.v1alpha1/","title":"policy (v1alpha1)","text":""},{"location":"reference/apis/policy.v1alpha1/#resource-types","title":"Resource Types","text":""},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-AuthorizationPolicy","title":"AuthorizationPolicy","text":"

AuthorizationPolicy defines an authorization policy resource

Field Type Required Inline Description apiVersion string envoy.kyverno.io/v1alpha1 kind string AuthorizationPolicy metadata meta/v1.ObjectMeta No description provided. spec AuthorizationPolicySpec No description provided."},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-Authorization","title":"Authorization","text":"

Appears in:

Authorization defines an authorization policy rule

Field Type Required Inline Description match string

Match represents the match condition which will be evaluated by CEL. Must evaluate to bool.

response string

Response represents the response expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to CEL variables as well as some other useful variables: - 'object' - The object from the incoming request. (https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto#service-auth-v3-checkrequest) CEL expressions are expected to return an envoy CheckResponse (https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto#service-auth-v3-checkresponse).

"},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-AuthorizationPolicySpec","title":"AuthorizationPolicySpec","text":"

Appears in:

AuthorizationPolicySpec defines the spec of an authorization policy

Field Type Required Inline Description failurePolicy admissionregistration/v1.FailurePolicyType

FailurePolicy defines how to handle failures for the policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions. FailurePolicy does not define how validations that evaluate to false are handled. Allowed values are Ignore or Fail. Defaults to Fail.

matchConditions []admissionregistration/v1.MatchCondition

MatchConditions is a list of conditions that must be met for a request to be validated. An empty list of matchConditions matches all requests. The exact matching logic is (in order): 1. If ANY matchCondition evaluates to FALSE, the policy is skipped. 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated. 3. If any matchCondition evaluates to an error (but none are FALSE): - If failurePolicy=Fail, reject the request - If failurePolicy=Ignore, the policy is skipped

variables []admissionregistration/v1.Variable

Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under variables in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy. The expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.

deny []Authorization

Deny contain CEL expressions which is used to deny a request.

allow []Authorization

Allow contain CEL expressions which is used to allow a request.

"},{"location":"tutorials/","title":"Tutorials","text":"

If you didn't read the Quick start section yet, we really recommend giving it a try to discover and familiarise with the Kyverno Envoy Plugin components first.

"},{"location":"tutorials/envoy-gateway/","title":"Envoy Gateway","text":"

Envoy Gateway is an open source project for managing Envoy Proxy as a standalone or Kubernetes-based application gateway. Gateway API resources are used to dynamically provision and configure the managed Envoy Proxies.

This tutorial shows how Envoy Gateway can be configured to delegate authorization decisions to the Kyverno Authz Server.

"},{"location":"tutorials/envoy-gateway/#setup","title":"Setup","text":""},{"location":"tutorials/envoy-gateway/#prerequisites","title":"Prerequisites","text":""},{"location":"tutorials/envoy-gateway/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"tutorials/envoy-gateway/#install-envoy-gateway","title":"Install Envoy Gateway","text":"

First we need to install Envoy Gateway in the cluster.

# install envoy gateway\nhelm install envoy-gateway -n envoy-gateway-system --create-namespace --wait --version v1.2.2 oci://docker.io/envoyproxy/gateway-helm\n
"},{"location":"tutorials/envoy-gateway/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# deploy the httpbin application\nkubectl apply -n demo -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml\n
"},{"location":"tutorials/envoy-gateway/#create-a-gatewayclass-and-a-gateway","title":"Create a GatewayClass and a Gateway","text":"

With Envoy Gateway installed we can now create a Gateway. To do so we will also create a dedicated GatewayClass.

Depending on your setup you will potentially need to create an EnvoyProxy resource to customize the way Envoy Gateway will create the underlying Service. The script below creates one to set the name and type of the service because the kind cluster created in the first step doesn't come with load balancer support.

# create a gateway\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.envoyproxy.io/v1alpha1\nkind: EnvoyProxy\nmetadata:\n  name: demo\nspec:\n  provider:\n    type: Kubernetes\n    kubernetes:\n      envoyService:\n        name: internet   # use a known name for the created service\n        type: ClusterIP  # because a kind cluster has no support for LB\n---\napiVersion: gateway.networking.k8s.io/v1\nkind: GatewayClass\nmetadata:\n  name: demo\nspec:\n  controllerName: gateway.envoyproxy.io/gatewayclass-controller\n---\napiVersion: gateway.networking.k8s.io/v1\nkind: Gateway\nmetadata:\n  name: demo\nspec:\n  gatewayClassName: demo\n  infrastructure:\n    parametersRef:\n      group: gateway.envoyproxy.io\n      kind: EnvoyProxy\n      name: demo\n  listeners:\n    - name: http\n      protocol: HTTP\n      port: 80\nEOF\n
"},{"location":"tutorials/envoy-gateway/#create-an-httproute-to-the-sample-application","title":"Create an HTTPRoute to the sample application","text":"

Next, we need to link the Gateway to our sample applicate with an HTTPRoute.

# create an http route to the sample app\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.networking.k8s.io/v1\nkind: HTTPRoute\nmetadata:\n  name: demo\nspec:\n  parentRefs:\n  - name: demo\n  rules:\n    - matches:\n        - path:\n            type: PathPrefix\n            value: /\n      backendRefs:\n        - group: ''\n          kind: Service\n          name: httpbin\n          port: 8000\n          weight: 1\nEOF\n
"},{"location":"tutorials/envoy-gateway/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

Now deploy the Kyverno Authz Server.

# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --create-namespace --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server\n
"},{"location":"tutorials/envoy-gateway/#create-a-kyverno-authorizationpolicy","title":"Create a Kyverno AuthorizationPolicy","text":"

In summary the policy below does the following:

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: authorization\n    expression: object.attributes.request.http.headers[?\"authorization\"].orValue(\"\").split(\" \")\n  - name: token\n    expression: >\n      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == \"bearer\"\n        ? jwt.Decode(variables.authorization[1], \"secret\")\n        : null\n  authorizations:\n    # request not authenticated -> 401\n  - expression: >\n      variables.token == null || !variables.token.Valid\n        ? envoy.Denied(401).Response()\n        : null\n    # request authenticated but not admin role -> 403\n  - expression: >\n      variables.token.Claims.?role.orValue(\"\") != \"admin\"\n        ? envoy.Denied(403).Response()\n        : null\n    # request authenticated and admin role -> 200\n  - expression: >\n      envoy\n        .Allowed()\n        .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n        .WithoutHeader(\"x-force-authorized\")\n        .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n        .Response()\nEOF\n
"},{"location":"tutorials/envoy-gateway/#deploy-an-envoy-gateway-securitypolicy","title":"Deploy an Envoy Gateway SecurityPolicy","text":"

A SecurityPolicy is the custom Envoy Gateway resource to configure underlying Envoy Proxy to use an external auth server (the Kyverno Authz Server we installed in a prior step).

# deploy envoy gateway security policy\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.envoyproxy.io/v1alpha1\nkind: SecurityPolicy\nmetadata:\n  name: demo\nspec:\n  targetRefs:\n    - group: gateway.networking.k8s.io\n      kind: HTTPRoute\n      name: demo\n  extAuth:\n    grpc:\n      backendRef:\n        group: ''\n        kind: Service\n        name: kyverno-authz-server\n        namespace: kyverno\n        port: 9081\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server service as the GRPC backend:

[...]\n  extAuth:\n    grpc:\n      backendRef:\n        group: ''\n        kind: Service\n        name: kyverno-authz-server\n        namespace: kyverno\n        port: 9081\n[...]\n

Also notice that the security policy applies to the demo HTTPRoute:

[...]\n  targetRefs:\n    - group: gateway.networking.k8s.io\n      kind: HTTPRoute\n      name: demo\n[...]\n
"},{"location":"tutorials/envoy-gateway/#grant-access-to-the-kyverno-authz-server-service","title":"Grant access to the Kyverno Authz Server service","text":"

Last thing we need to configure is to grant access to the Kyverno Authz Server service for our SecurityPolicy to take effect.

# grant access\nkubectl apply -n kyverno -f - <<EOF\napiVersion: gateway.networking.k8s.io/v1beta1\nkind: ReferenceGrant\nmetadata:\n  name: demo\nspec:\n  from:\n  - group: gateway.envoyproxy.io\n    kind: SecurityPolicy\n    namespace: demo\n  to:\n  - group: ''\n    kind: Service\nEOF\n
"},{"location":"tutorials/envoy-gateway/#testing","title":"Testing","text":"

At this we have deployed and configured Envoy Gateway, the Kyverno Authz Server, a sample application, and the authorization and security policies.

"},{"location":"tutorials/envoy-gateway/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"tutorials/envoy-gateway/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"tutorials/envoy-gateway/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send request to the sample application and verify the result.

For convenience, we will store Alice\u2019s and Bob\u2019s tokens in environment variables.

Here Bob is assigned the admin role and Alice is assigned the guest role.

export ALICE_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk\"\nexport BOB_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6ImFkbWluIiwic3ViIjoiWVd4cFkyVT0ifQ.veMeVDYlulTdieeX-jxFZ_tCmqQ_K8rwx2OktUHv5Z0\"\n

Calling without a JWT token will return 401:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get\n

Calling with Alice\u2019s JWT token will return 403:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get -H \"authorization: Bearer $ALICE_TOKEN\"\n

Calling with Bob\u2019s JWT token will return 200:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get -H \"authorization: Bearer $BOB_TOKEN\"\n
"},{"location":"tutorials/envoy-gateway/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the tutorial!

This tutorial demonstrated how to configure Envoy Gateway to utilize the Kyverno Authz Server as an external authorization service.

Additionally, the tutorial provided an example policy to decode a JWT token and make a decision based on it.

"},{"location":"tutorials/istio/","title":"Istio","text":"

Istio is an open source service mesh for managing the different microservices that make up a cloud-native application. Istio provides a mechanism to use a service as an external authorizer with the AuthorizationPolicy API.

This tutorial shows how Istio\u2019s AuthorizationPolicy can be configured to delegate authorization decisions to the Kyverno Authz Server.

"},{"location":"tutorials/istio/#setup","title":"Setup","text":""},{"location":"tutorials/istio/#prerequisites","title":"Prerequisites","text":""},{"location":"tutorials/istio/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"tutorials/istio/#configure-the-mesh","title":"Configure the mesh","text":"

We need to register the Kyverno Authz Server with Istio.

# configure the mesh\nistioctl install -y -f - <<EOF\napiVersion: install.istio.io/v1alpha1\nkind: IstioOperator\nspec:\n  meshConfig:\n    accessLogFile: /dev/stdout\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\nEOF\n

Notice that in the configuration, we define an extensionProviders section that points to the Kyverno Authz Server we will install in the next step:

[...]\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\n[...]\n
"},{"location":"tutorials/istio/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

The first step is to deploy the Kyverno Authz Server.

# create the kyverno namespace\nkubectl create ns kyverno\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace kyverno istio-injection=enabled\n\n# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server\n
"},{"location":"tutorials/istio/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace demo istio-injection=enabled\n\n# deploy the httpbin application\nkubectl apply -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml -n demo\n
"},{"location":"tutorials/istio/#deploy-an-istio-authorizationpolicy","title":"Deploy an Istio AuthorizationPolicy","text":"

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy\nkubectl apply -f - <<EOF\napiVersion: security.istio.io/v1\nkind: AuthorizationPolicy\nmetadata:\n  name: kyverno-authz-server\n  namespace: demo\nspec:\n  action: CUSTOM\n  provider:\n    name: kyverno-authz-server.local\n  rules:\n  - {} # empty rules, it will apply to all requests\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server extensionProvider you set in the Istio configuration:

[...]\n  provider:\n    name: kyverno-authz-server.local\n[...]\n
"},{"location":"tutorials/istio/#create-a-kyverno-authorizationpolicy","title":"Create a Kyverno AuthorizationPolicy","text":"

In summary the policy below does the following:

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: authorization\n    expression: object.attributes.request.http.headers[?\"authorization\"].orValue(\"\").split(\" \")\n  - name: token\n    expression: >\n      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == \"bearer\"\n        ? jwt.Decode(variables.authorization[1], \"secret\")\n        : null\n  authorizations:\n    # request not authenticated -> 401\n  - expression: >\n      variables.token == null || !variables.token.Valid\n        ? envoy.Denied(401).Response()\n        : null\n    # request authenticated but not admin role -> 403\n  - expression: >\n      variables.token.Claims.?role.orValue(\"\") != \"admin\"\n        ? envoy.Denied(403).Response()\n        : null\n    # request authenticated and admin role -> 200\n  - expression: >\n      envoy.Allowed().Response()\nEOF\n
"},{"location":"tutorials/istio/#testing","title":"Testing","text":"

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

"},{"location":"tutorials/istio/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"tutorials/istio/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"tutorials/istio/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send request to the sample application and verify the result.

For convenience, we will store Alice\u2019s and Bob\u2019s tokens in environment variables.

Here Bob is assigned the admin role and Alice is assigned the guest role.

export ALICE_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk\"\nexport BOB_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6ImFkbWluIiwic3ViIjoiWVd4cFkyVT0ifQ.veMeVDYlulTdieeX-jxFZ_tCmqQ_K8rwx2OktUHv5Z0\"\n

Calling without a JWT token will return 401:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get\n

Calling with Alice\u2019s JWT token will return 403:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"authorization: Bearer $ALICE_TOKEN\"\n

Calling with Bob\u2019s JWT token will return 200:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"authorization: Bearer $BOB_TOKEN\"\n
"},{"location":"tutorials/istio/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the tutorial!

This tutorial demonstrated how to configure Istio\u2019s EnvoyFilter to utilize the Kyverno Authz Server as an external authorization service.

Additionally, the tutorial provided an example policy to decode a JWT token and make a decision based on it.

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"cel-extensions/","title":"CEL extensions","text":"

The CEL engine used to evaluate variables and authorization rules has been extended with libraries to help processing the input CheckRequest and forge the corresponding OkResponse and/or DeniedResponse.

"},{"location":"cel-extensions/#envoy-plugin-libraries","title":"Envoy plugin libraries","text":""},{"location":"cel-extensions/#common-libraries","title":"Common libraries","text":"

The libraries below are common CEL extensions enabled in the Kyverno Authz Server CEL engine:

"},{"location":"cel-extensions/#kubernetes-libraries","title":"Kubernetes libraries","text":"

The libraries below are imported from Kubernetes:

"},{"location":"cel-extensions/envoy/","title":"Envoy library","text":"

The envoy library adds some types and function to simplify the creation of OkResponse and DeniedResponse objects.

"},{"location":"cel-extensions/envoy/#types","title":"Types","text":""},{"location":"cel-extensions/envoy/#checkrequest","title":"<CheckRequest>","text":"

CEL Type / Proto: envoy.service.auth.v3.CheckRequest

"},{"location":"cel-extensions/envoy/#okresponse","title":"<OkResponse>","text":"

CEL Type / Proto: envoy.OkResponse

Field CEL Type / Proto Docs status google.rpc.Status Docs http_response envoy.service.auth.v3.OkHttpResponse Docs dynamic_metadata google.protobuf.Struct Docs"},{"location":"cel-extensions/envoy/#deniedresponse","title":"<DeniedResponse>","text":"

CEL Type / Proto: envoy.DeniedResponse

Field CEL Type / Proto Docs status google.rpc.Status Docs http_response envoy.service.auth.v3.DeniedHttpResponse Docs dynamic_metadata google.protobuf.Struct Docs"},{"location":"cel-extensions/envoy/#okhttpresponse","title":"<OkHttpResponse>","text":"

CEL Type / Proto: envoy.service.auth.v3.OkHttpResponse

"},{"location":"cel-extensions/envoy/#deniedhttpresponse","title":"<DeniedHttpResponse>","text":"

CEL Type / Proto: envoy.service.auth.v3.DeniedHttpResponse

"},{"location":"cel-extensions/envoy/#metadata","title":"<Metadata>","text":"

CEL Type / Proto: google.protobuf.Struct

"},{"location":"cel-extensions/envoy/#headervalueoption","title":"<HeaderValueOption>","text":"

CEL Type / Proto: envoy.config.core.v3.HeaderValueOption

"},{"location":"cel-extensions/envoy/#queryparameter","title":"<QueryParameter>","text":"

CEL Type / Proto: envoy.config.core.v3.QueryParameter

"},{"location":"cel-extensions/envoy/#status","title":"<Status>","text":"

CEL Type / Proto: google.rpc.Status

"},{"location":"cel-extensions/envoy/#functions","title":"Functions","text":""},{"location":"cel-extensions/envoy/#envoyallowed","title":"envoy.Allowed","text":"

This function creates an <OkHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads","title":"Signature and overloads","text":"
envoy.Allowed() -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example","title":"Example","text":"
envoy.Allowed()\n
"},{"location":"cel-extensions/envoy/#envoydenied","title":"envoy.Denied","text":"

This function creates a <DeniedHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_1","title":"Signature and overloads","text":"
envoy.Denied(<int> code) -> <DeniedHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_1","title":"Example","text":"
envoy.Denied(401)\n
"},{"location":"cel-extensions/envoy/#envoyheader","title":"envoy.Header","text":"

This function creates an <HeaderValueOption> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_2","title":"Signature and overloads","text":"
envoy.Header(<string> key, <string> value) -> <HeaderValueOption>\n
"},{"location":"cel-extensions/envoy/#example_2","title":"Example","text":"
envoy.Header(\"foo\", \"bar\")\n
"},{"location":"cel-extensions/envoy/#envoyqueryparam","title":"envoy.QueryParam","text":"

This function creates a <QueryParameter> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_3","title":"Signature and overloads","text":"
envoy.QueryParam(<string> key, <string> value) -> <QueryParameter>\n
"},{"location":"cel-extensions/envoy/#example_3","title":"Example","text":"
envoy.QueryParam(\"foo\", \"bar\")\n
"},{"location":"cel-extensions/envoy/#withbody","title":"WithBody","text":"

This function sets the body of a <DeniedHttpResponse> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_4","title":"Signature and overloads","text":"
<DeniedHttpResponse>.WithBody(<string> body) -> <DeniedHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_4","title":"Example","text":"
envoy.Denied(401).WithBody(\"Unauthorized Request\")\n
"},{"location":"cel-extensions/envoy/#withheader","title":"WithHeader","text":"

This function adds a <HeaderValueOption>:

"},{"location":"cel-extensions/envoy/#signature-and-overloads_5","title":"Signature and overloads","text":"

<OkHttpResponse>.WithHeader(<HeaderValueOption> header) -> <OkHttpResponse>\n
<OkHttpResponse>.WithHeader(<string> key, <string> value) -> <OkHttpResponse>\n
<DeniedHttpResponse>.WithHeader(<HeaderValueOption> header) -> <DeniedHttpResponse>\n
<DeniedHttpResponse>.WithHeader(<string> key, <string> value) -> <DeniedHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_5","title":"Example","text":"

envoy.Allowed().WithHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Allowed().WithHeader(\"foo\", \"bar\")\n
envoy.Denied(401).WithHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Denied(401).WithHeader(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withoutheader","title":"WithoutHeader","text":"

This function marks a header to be removed when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_6","title":"Signature and overloads","text":"
<OkHttpResponse>.WithoutHeader(<string> header) -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_6","title":"Example","text":"
envoy.Allowed().WithoutHeader(\"foo\")\n
"},{"location":"cel-extensions/envoy/#withresponseheader","title":"WithResponseHeader","text":"

This function adds a <HeaderValueOption> when the response is sent downstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_7","title":"Signature and overloads","text":"

<OkHttpResponse>.WithResponseHeader(<HeaderValueOption> header) -> <OkHttpResponse>\n
<OkHttpResponse>.WithResponseHeader(<string> key, <string> value) -> <OkHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_7","title":"Example","text":"

envoy.Allowed().WithResponseHeader(envoy.Header(\"foo\", \"bar\"))\n
envoy.Allowed().WithResponseHeader(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withqueryparam","title":"WithQueryParam","text":"

This function adds a <QueryParameter> to be added when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_8","title":"Signature and overloads","text":"

<OkHttpResponse>.WithQueryParam(<QueryParameter> param) -> <OkHttpResponse>\n
<OkHttpResponse>.WithQueryParam(<string> key, <string> value) -> <OkHttpResponse>\n

"},{"location":"cel-extensions/envoy/#example_8","title":"Example","text":"

envoy.Allowed().WithQueryParam(envoy.QueryParam(\"foo\", \"bar\"))\n
envoy.Allowed().WithQueryParam(\"foo\", \"bar\")\n

"},{"location":"cel-extensions/envoy/#withoutqueryparam","title":"WithoutQueryParam","text":"

This function marks a query parameter to be removed when the request is sent upstream by Envoy.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_9","title":"Signature and overloads","text":"
<OkHttpResponse>.WithoutQueryParam(<string> param) -> <OkHttpResponse>\n
"},{"location":"cel-extensions/envoy/#example_9","title":"Example","text":"
envoy.Allowed().WithoutQueryParam(\"foo\")\n
"},{"location":"cel-extensions/envoy/#keepemptyvalue","title":"KeepEmptyValue","text":"

This function sets the keep_empty_value field of an <HeaderValueOption> object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_10","title":"Signature and overloads","text":"

<HeaderValueOption>.KeepEmptyValue() -> <HeaderValueOption>\n
<HeaderValueOption>.KeepEmptyValue(<bool> keep) -> <HeaderValueOption>\n

"},{"location":"cel-extensions/envoy/#example_10","title":"Example","text":"

envoy.Header(\"foo\", \"bar\").KeepEmptyValue()\n
envoy.Header(\"foo\", \"bar\").KeepEmptyValue(true)\n

"},{"location":"cel-extensions/envoy/#response","title":"Response","text":"

This function creates a <OkResponse> / DeniedResponse object from an <OkHttpResponse> / <DeniedHttpResponse>.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_11","title":"Signature and overloads","text":"

<OkHttpResponse>.Response() -> <OkResponse>\n
<DeniedHttpResponse>.Response() -> <DeniedResponse>\n

"},{"location":"cel-extensions/envoy/#example_11","title":"Example","text":"

envoy.Allowed().Response()\n
envoy.Denied(401).Response()\n

"},{"location":"cel-extensions/envoy/#withmessage","title":"WithMessage","text":"

This function sets the status.message field of an <OkResponse> / DeniedResponse object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_12","title":"Signature and overloads","text":"

<OkResponse>.WithMessage(<string> message) -> <OkResponse>\n
<DeniedResponse>.WithMessage(<string> message) -> <DeniedResponse>\n

"},{"location":"cel-extensions/envoy/#example_12","title":"Example","text":"

envoy.Allowed().Response().WithMessage(\"hello world!\")\n
envoy.Denied(401).Response().WithMessage(\"hello world!\")\n

"},{"location":"cel-extensions/envoy/#withmetadata","title":"WithMetadata","text":"

This function sets the dynamic_metadata field of an <OkResponse> / DeniedResponse object.

"},{"location":"cel-extensions/envoy/#signature-and-overloads_13","title":"Signature and overloads","text":"

<OkResponse>.WithMetadata(<Metadata> metadata) -> <OkResponse>\n
<DeniedResponse>.WithMetadata(<Metadata> metadata) -> <DeniedResponse>\n

"},{"location":"cel-extensions/envoy/#example_13","title":"Example","text":"

envoy.Allowed().Response().WithMetadata({ \"foo\": \"bar\" })\n
envoy.Denied(401).Response().WithMetadata({ \"foo\": \"bar\" })\n

"},{"location":"cel-extensions/jwt/","title":"Jwt library","text":"

Policies have native functionality to decode and verify the contents of JWT tokens in order to enforce additional authorization logic on requests.

"},{"location":"cel-extensions/jwt/#types","title":"Types","text":""},{"location":"cel-extensions/jwt/#token","title":"<Token>","text":"

CEL Type / Proto jwt.Token

Field CEL Type / Proto Docs Valid bool Header google.protobuf.Struct Docs Claims google.protobuf.Struct Docs"},{"location":"cel-extensions/jwt/#functions","title":"Functions","text":""},{"location":"cel-extensions/jwt/#jwtdecode","title":"jwt.Decode","text":"

The jwt.Decode function decodes and validates a JWT token. It accepts two arguments: the token and the secret to verify the signature.

"},{"location":"cel-extensions/jwt/#signature-and-overloads","title":"Signature and overloads","text":"
jwt.Decode(<string> token, <string> key) -> <Token>\n
"},{"location":"cel-extensions/jwt/#example","title":"Example","text":"
jwt.Decode(\"eyJhbGciOiJIUzI1NiI....\", \"secret\")\n
"},{"location":"community/","title":"Community","text":"

The Kyverno Envoy Plugin has a growing community and we would definitely love to see you join and contribute.

Everyone is welcome to make suggestions, report bugs, open feature requests, contribute code or docs, participate in discussions, write blogs or anything that can benefit the project.

The Kyverno Envoy Plugin is built and maintained under the Kyverno umbrella but decisions are Community driven Everyone's voice matters

"},{"location":"community/#slack-channel","title":"Slack channel","text":"

Join our slack channel #kyverno to meet with users, contributors and maintainers.

"},{"location":"community/#roadmap","title":"RoadMap","text":"

For detailed information on our planned features and upcoming updates, please view our Roadmap.

"},{"location":"community/#contributing","title":"Contributing","text":"

Please read the contributing guide for details around:

  1. Code of Conduct
  2. Code Culture
  3. Details on how to contribute
"},{"location":"community/#adopters","title":"Adopters","text":"

If you are using the Kyverno Envoy Plugin and want to share it publicly we always appreciate a bit of support. Pull requests to the ADOPTERS LIST will put a smile on our faces

"},{"location":"community/contribute/","title":"Contributing","text":"

Kyverno Envoy Plugin, developed by Kyverno, is an advanced end-to-end testing tool for Kubernetes. Our community plays a crucial role in shaping the project by reporting bugs, suggesting features, and improving documentation.

We aim to make our issue tracker, discussion board, and documentation well-structured and easy to navigate. By following our guidelines, you can help us address your requests efficiently.

"},{"location":"community/contribute/#how-you-can-contribute","title":"How you can contribute","text":"

We appreciate your efforts in reporting bugs, requesting features, and engaging in discussions. Here's how you can contribute:

"},{"location":"community/contribute/#creating-an-issue","title":"Creating an issue","text":""},{"location":"community/contribute/#contributing_1","title":"Contributing","text":""},{"location":"community/contribute/#checklist","title":"Checklist","text":"

Before interacting within the project, please consider the following questions to ensure you're using the correct issue template and providing all necessary information.

Issues, discussions, and comments are forever

Please note that everything you write is permanent and will remain for everyone to read \u2013 forever. Therefore, please always be nice and constructive, follow our contribution guidelines, and comply with our Code of Conduct.

"},{"location":"community/contribute/#before-creating-an-issue","title":"Before creating an issue","text":""},{"location":"community/contribute/#before-asking-a-question","title":"Before asking a question","text":""},{"location":"community/contribute/#before-commenting","title":"Before commenting","text":""},{"location":"community/contribute/#rights-and-responsibilities","title":"Rights and responsibilities","text":"

As maintainers, we are entrusted with the responsibility to moderate communication within our community, including the authority to close, remove, reject, or edit issues, discussions, comments, commits, and to block users who do not align with our contribution guidelines and our Code of Conduct. This role requires us to be actively involved in maintaining the integrity and positive atmosphere of our community. Upholding these standards decisively ensures a respectful and inclusive environment for all members.

"},{"location":"community/contribute/#code-of-conduct","title":"Code of Conduct","text":"

Our Code of Conduct outlines the expectation for all community members to treat one another with respect, employing inclusive and welcoming language. Our commitment is to foster a positive and supportive environment, free of inappropriate, offensive, or harmful behavior.

We take any violations seriously and will take appropriate action in response to uphold these values.1

"},{"location":"community/contribute/#incomplete-issues-and-duplicates","title":"Incomplete issues and duplicates","text":"

We have invested significant time and effort in the setup of our contribution process, ensuring that we assess the essential requirements for reviewing and responding to issues effectively. Each field in our issue templates is thoughtfully designed to help us fully understand your concerns and the nature of your matter. We encourage all members to utilize the search function before submitting new issues or starting discussions to help avoid duplicates. Your cooperation is crucial in keeping our community's discussions constructive and organized.

  1. Warning and blocking policy: Given the increasing popularity of our project and our commitment to a healthy community, we've defined clear guidelines on how we proceed with violations:

    1.1. First warning: Users displaying repeated inappropriate, offensive, or harmful behavior will receive a first warning. This warning serves as a formal notice that their behavior is not in alignment with our community standards and Code of Conduct. The first warning is permanent.

    1.2. Second warning and opportunity for resolution: If the behavior persists, a second warning will be issued. Upon receiving the second warning, the user will be given a 5-day period for reflection, during which they are encouraged to publicly explain or apologize for their actions. This period is designed to offer an opportunity for openly clearing out any misunderstanding.

    1.3. Blocking: Should there be no response or improvement in behavior following the second warning, we reserve the right to block the user from the community and repository. Blocking is considered a last resort, used only when absolutely necessary to protect the community's integrity and positive atmosphere.

    Blocking has been an exceptionally rare necessity in our overwhelmingly positive community, highlighting our preference for constructive dialogue and mutual respect. It aims to protect our community members and team.\u00a0\u21a9

"},{"location":"community/making-a-pull-request/","title":"Pull Requests","text":"

You can contribute by making a pull request that will be reviewed by maintainers and integrated into the main repository when the changes made are approved. You can contribute bug fixes, documentation changes, or new functionalities.

Considering a pull request

Before deciding to spend effort on making changes and creating a pull request, please discuss what you intend to do. If you are responding to what you think might be a bug, please issue a bug report first. If you intend to work on documentation, create a documentation issue. If you want to work on a new feature, please create a change request.

Keep in mind the guidance given and let people advise you. It might be that there are easier solutions to the problem you perceive and want to address. It might be that what you want to achieve can already be done by configuration or [customization].

"},{"location":"community/making-a-pull-request/#learning-about-pull-requests","title":"Learning about pull requests","text":"

Pull requests are a concept layered on top of Git by services that provide Git hosting. Before you consider making a pull request, you should familiarize yourself with the documentation on GitHub, the service we are using. The following articles are of particular importance:

  1. Forking a repository
  2. Creating a pull request from a fork
  3. Creating a pull request

Note that they provide tailored documentation for different operating systems and different ways of interacting with GitHub. We do our best in the documentation here to describe the process as it applies but cannot cover all possible combinations of tools and ways of doing things. It is also important that you understand the concept of a pull-request in general before continuing.

"},{"location":"community/making-a-pull-request/#pull-request-process","title":"Pull request process","text":"

In the following, we describe the general process for making pull requests. The aim here is to provide the 30k ft overview before describing details later on.

"},{"location":"community/making-a-pull-request/#preparing-changes-and-draft-pr","title":"Preparing changes and draft PR","text":"

The diagram below describes what typically happens to repositories in the process or preparing a pull request. We will be discussing the review-revise process below. It is important that you understand the overall process first before you worry about specific commands. This is why we cover this first before providing instructions below.

sequenceDiagram\n  autonumber\n\n  participant upstream\n  participant PR\n  participant fork\n  participant local\n\n  upstream ->> fork: fork on GitHub\n  fork ->> local: clone to local\n  local ->> local: branch\n  loop prepare\n    loop push\n      loop edit\n        local ->> local: commit\n      end\n      local ->> fork: push\n    end\n    upstream ->> fork: merge in any changes\n    fork ->>+ PR: create draft PR\n    PR ->> PR: review your changes\n  end
  1. Fork the Repository: Fork the upstream repository on GitHub to create your own copy.
  2. Clone to Local: Clone your fork to your local machine.
  3. Create a Branch: Create a topic branch for your changes.
  4. Set Up Development Environment: Follow the instructions to set up a development environment.
  5. Iterate and Commit: Make incremental changes and commit them with meaningful messages.
  6. Push Regularly: Push your commits to your fork regularly.
  7. Merge Changes from Upstream: Regularly merge changes from the original upstream repository to avoid conflicts.
  8. Create a Draft Pull Request: Once satisfied with your changes, create a draft pull request for early feedback.
  9. Review and Revise: Review your work critically, address feedback, and refine your changes.
"},{"location":"community/making-a-pull-request/#finalizing","title":"Finalizing","text":"

Once you are happy with your changes, you can move to the next step, finalizing your pull request and asking for a more formal and detailed review. The diagram below shows the process:

sequenceDiagram\n  autonumber\n  participant upstream\n  participant PR\n  participant fork\n  participant local\n\n  activate PR\n  PR ->> PR: finalize PR\n  loop review\n    loop discuss\n      PR ->> PR: request review\n      PR ->> PR: discussion\n      local ->> fork: push further changes\n    end\n    PR ->> upstream: merge (and squash)\n    deactivate PR\n    fork ->> fork: delete branch\n    upstream ->> fork: pull\n    local ->> local: delete branch\n    fork ->> local: pull\n  end\n
  1. Finalize PR: Signal that your changes are ready for review.
  2. Request Review: Ask the maintainer to review your changes.
  3. Discuss and Revise: Engage in discussions, make necessary revisions, and iterate.
  4. Merge and Squash: Once approved, the maintainer will merge and possibly squash your commits.
  5. Clean Up: Delete the branch used for the PR from both your fork and local clone.
"},{"location":"community/reporting-a-bug/","title":"Bug Reports","text":"

If you think you have discovered a bug, you can help us by submitting an issue in our public issue tracker, following this guide.

"},{"location":"community/reporting-a-bug/#before-creating-an-issue","title":"Before Creating an Issue","text":"

With numerous users, issues are created regularly. The maintainers of this project strive to address bugs promptly. By following this guide, you will know exactly what information we need to help you quickly.

Please do the following before creating an issue:

"},{"location":"community/reporting-a-bug/#upgrade-to-latest-version","title":"Upgrade to Latest Version","text":"

Chances are that the bug you discovered was already fixed in a subsequent version. Before reporting an issue, ensure that you're running the latest version.

Bug fixes are not backported

Please understand that only bugs that occur in the latest version will be addressed. Also, to reduce duplicate efforts, fixes cannot always be backported to earlier versions.

"},{"location":"community/reporting-a-bug/#remove-customizations","title":"Remove Customizations","text":"

If you're using customizations like additional configurations, remove them before reporting a bug. We can't offer official support for bugs that might hide in your overrides, so make sure to omit custom settings from your configuration files.

Don't be shy to ask on our discussion board for help if you run into problems.

"},{"location":"community/reporting-a-bug/#search-for-solutions","title":"Search for Solutions","text":"

At this stage, we know that the problem persists in the latest version and is not caused by any of your customizations. However, the problem might result from a small typo or a syntactical error in a configuration file.

Before creating a bug report, save time for us and yourself by doing some research:

  1. Search our documentation for relevant sections related to your problem. Ensure everything is configured correctly.
  2. [Search our issue tracker] as another user might have already reported the same problem.
  3. [Search our discussion board] to see if other users are facing similar issues and find possible solutions.

Keep track of all search terms and relevant links; you'll need them in the bug report.

If you still haven't found a solution to your problem, create an issue. It's now likely that you've encountered something new. Read the following section to learn how to create a complete and helpful bug report.

"},{"location":"community/reporting-a-bug/#issue-template","title":"Issue Template","text":"

We have created a new issue template to make the bug reporting process as simple as possible and more efficient for our community and us. It consists of the following parts:

"},{"location":"community/reporting-a-bug/#title","title":"Title","text":"

A good title is short and descriptive. It should be a one-sentence executive summary of the issue, so the impact and severity of the bug can be inferred from the title.

Example Clear apply command fails with specific CRD Wordy The apply command fails when used with a certain Custom Resource Definition Unclear Command does not work Useless Help"},{"location":"community/reporting-a-bug/#context","title":"Context optional","text":"

Before describing the bug, you can provide additional context to help us understand what you were trying to achieve. Explain the circumstances under which the bug happens, and what you think might be relevant. Don't describe the bug here.

"},{"location":"community/reporting-a-bug/#bug-description","title":"Bug Description","text":"

Provide a clear, focused, specific, and concise summary of the bug you encountered. Explain why you think this is a bug that should be reported, and not to one of its dependencies. Follow these principles:

"},{"location":"community/reporting-a-bug/#related-links","title":"Related Links","text":"

Share links to relevant sections of our documentation and any related issues or discussions. This helps us improve our documentation and understand the problem better.

"},{"location":"community/reporting-a-bug/#reproduction","title":"Reproduction","text":"

A minimal reproduction is essential for a well-written bug report, as it allows us to recreate the conditions necessary to inspect the bug. Follow the guide to create a reproduction:

[ Create reproduction][Create reproduction]{ .md-button .md-button--primary }

After creating the reproduction, you should have a .zip file, ideally not larger than 1 MB. Drag and drop the .zip file into the issue field, which will automatically upload it to GitHub.

Don't share links to repositories

While linking to a repository is a common practice, we currently don't support this. The reproduction, created using the built-in info plugin, contains all necessary environment information.

"},{"location":"community/reporting-a-bug/#steps-to-reproduce","title":"Steps to Reproduce","text":"

List specific steps to follow when running your reproduction to observe the bug. Keep the steps concise and ensure nothing is left out. Use simple language and focus on continuity.

"},{"location":"community/reporting-a-bug/#browser","title":"Browser optional","text":"

If the bug only occurs in specific browsers, let us know which ones are affected. This field is optional, as it is only relevant for bugs that do not involve a crash when previewing or building your site.

Incognito Mode

Verify that the bug is not caused by a browser extension by switching to incognito mode. If the bug disappears, it is likely caused by an extension.

"},{"location":"community/reporting-a-bug/#checklist","title":"Checklist","text":"

Before submitting, ensure you have:

Thanks for following the guide and creating a high-quality bug report. We will take it from here.

"},{"location":"community/reporting-a-docs-issue/","title":"Documentation Issues","text":"

The documentation includes extensive information on features, configurations, customizations, and more. If you have found an inconsistency or see room for improvement, please follow this guide to submit an issue on our issue tracker.

"},{"location":"community/reporting-a-docs-issue/#issue-template","title":"Issue Template","text":"

Reporting a documentation issue is usually less involved than reporting a bug, as we don't need a [reproduction]. Please thoroughly read this guide before creating a new documentation issue, and provide the following information as part of the issue:

"},{"location":"community/reporting-a-docs-issue/#title","title":"Title","text":"

A good title should be a short, one-sentence description of the issue, containing all relevant information and keywords to simplify the search in our issue tracker.

Example Clear Clarify resource templating setup Unclear Missing information in the docs Useless Help"},{"location":"community/reporting-a-docs-issue/#description","title":"Description","text":"

Provide a clear and concise summary of the inconsistency or issue you encountered in the documentation or the documentation section that needs improvement. Explain why you think the documentation should be adjusted and describe the severity of the issue:

Why we need this: describing the problem clearly and concisely is a prerequisite for improving our documentation \u2013 we need to understand what's wrong so we can fix it.

"},{"location":"community/reporting-a-docs-issue/#related-links","title":"Related Links","text":"

After you describe the documentation section that needs to be adjusted, share the link to this specific documentation section and other possibly related sections. Use anchor links (permanent links) where possible, as it simplifies discovery.

Why we need this: providing the links to the documentation helps us understand which sections of our documentation need to be adjusted, extended, or overhauled.

"},{"location":"community/reporting-a-docs-issue/#proposed-change","title":"Proposed Change optional","text":"

Now that you have provided us with the description and links to the documentation sections, you can help us, maintainers, and the community by proposing an improvement. You can sketch out rough ideas or write a concrete proposal. This field is optional but very helpful.

Why we need this: an improvement proposal can be beneficial for other users who encounter the same issue, as they offer solutions before we maintainers can update the documentation.

"},{"location":"community/reporting-a-docs-issue/#checklist","title":"Checklist","text":"

Thanks for following the guide and providing valuable feedback for our documentation \u2013 you are almost done. The checklist ensures that you have read this guide and have worked to your best knowledge to provide us with every piece of information we need to improve it.

We'll take it from here.

"},{"location":"community/requesting-a-change/","title":"Change Requests","text":"

We value every idea or contribution from our community. Please follow this guide before submitting your change request in our public issue tracker. This helps us better understand the proposed change and how it will benefit our community.

"},{"location":"community/requesting-a-change/#before-creating-an-issue","title":"Before Creating an Issue","text":"

Before you invest time in submitting a change request, answer these questions to determine if your idea is a good fit and matches the project's philosophy and tone.

"},{"location":"community/requesting-a-change/#its-not-a-bug-its-a-feature","title":"It's Not a Bug, It's a Feature","text":"

Change requests suggest minor adjustments, new features, or influence the project's direction. They are not intended for reporting bugs. Refer to our bug reporting guide for that.

"},{"location":"community/requesting-a-change/#look-for-sources-of-inspiration","title":"Look for Sources of Inspiration","text":"

If your idea is implemented in another tool or framework, collect information on its implementation. This helps us evaluate its fit more quickly.

"},{"location":"community/requesting-a-change/#connect-with-our-community","title":"Connect with Our Community","text":"

Our discussion board is the best place to connect with our community. Seeking input from other users helps implement features that benefit a larger number of users.

Start a discussion

"},{"location":"community/requesting-a-change/#issue-template","title":"Issue Template","text":"

After doing the preliminary work, create a change request. Follow these steps:

"},{"location":"community/requesting-a-change/#title","title":"Title","text":"

A good title is short and descriptive, summarizing the idea so the potential impact and benefit can be inferred.

Example Clear Support for resource templating Wordy Add support for templating resources for easier testing Unclear Improve templating Useless Help"},{"location":"community/requesting-a-change/#context","title":"Context optional","text":"

Provide additional context to help us understand what you are trying to achieve. Explain the circumstances and relevant settings without describing the change request itself.

"},{"location":"community/requesting-a-change/#description","title":"Description","text":"

Provide a detailed and clear description of your idea. Explain why your idea is relevant and should be implemented here, not in one of its dependencies.

"},{"location":"community/requesting-a-change/#related-links","title":"Related Links","text":"

Provide any relevant links to issues, discussions, or documentation sections related to your change request. This helps us gain additional context.

"},{"location":"community/requesting-a-change/#use-cases","title":"Use Cases","text":"

Explain how your change request would work from an author's and user's perspective. What is the expected impact, and why does it benefit other users? Would it potentially break existing functionality?

"},{"location":"community/requesting-a-change/#visuals","title":"Visuals optional","text":"

If you have any visuals, such as sketches, screenshots, mockups, or external assets, present them in this section. If you have seen this change used in other tools, showcase and describe its implementation.

"},{"location":"community/requesting-a-change/#checklist","title":"Checklist","text":"

Thanks for following the guide and creating a high-quality change request. The checklist ensures that you have read this guide and provided all necessary information for us to review your idea.

We'll take it from here.

"},{"location":"community/requesting-a-change/#rejected-requests","title":"Rejected Requests","text":"

Your change request got rejected? We're sorry for that. We understand it can be frustrating, but we always need to consider the needs of our entire community. If you're unsure why your change request was rejected, please ask for clarification.

We consider the following principles when evaluating change requests:

If your idea was rejected, you can always implement it via [customization]. If you're unsure how or want to know if someone has already done it, get in touch with our community on the discussion board.

"},{"location":"performance/","title":"Performance","text":"

This page offers guidance and best practices for benchmarking the performance of the Kyverno Authz Server, helping users understand the associated overhead. It outlines an example setup for conducting benchmarks, various benchmarking scenarios, and key metrics to capture for assessing the impact of the Kyverno Authz Server.

"},{"location":"performance/#benchmark-setup","title":"Benchmark Setup","text":"

The benchmark setup consists of the following components:

"},{"location":"performance/#sample-application","title":"Sample Application","text":"

The first component is a simple Go application that provides information of books in the library books collection and exposes APIs to get, create and delete books collection. Check this out for more information about the Go test application .

"},{"location":"performance/#envoy","title":"Envoy","text":"

The second component is the Envoy proxy, which runs alongside the example application. The Envoy configuration defines an external authorization filter envoy.ext_authz for a gRPC authorization server.

The config uses Envoy's in-built gRPC client to make external gRPC calls.

static_resources:\n  listeners:\n  - address:\n      socket_address:\n        address: 0.0.0.0\n        port_value: 8000\n    filter_chains:\n    - filters:\n      - name: envoy.filters.network.http_connection_manager\n        typed_config:\n          \"@type\": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager\n          codec_type: auto\n          stat_prefix: ingress_http\n          route_config:\n            name: local_route\n            virtual_hosts:\n            - name: backend\n              domains:\n              - \"*\"\n              routes:\n              - match:\n                  prefix: \"/\"\n                route:\n                  cluster: service\n          http_filters:\n          - name: envoy.ext_authz\n            typed_config:\n              \"@type\": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz\n              transport_api_version: V3\n              with_request_body:\n                max_request_bytes: 8192\n                allow_partial_message: true\n              failure_mode_allow: false\n              grpc_service:\n                google_grpc:\n                  target_uri: 127.0.0.1:9191\n                  stat_prefix: ext_authz\n                timeout: 0.5s\n          - name: envoy.filters.http.router\n            typed_config:\n              \"@type\": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router\n  clusters:\n  - name: service\n    connect_timeout: 0.25s\n    type: strict_dns\n    lb_policy: round_robin\n    load_assignment:\n      cluster_name: service\n      endpoints:\n      - lb_endpoints:\n        - endpoint:\n            address:\n              socket_address:\n                address: 127.0.0.1\n                port_value: 8080\nadmin:\n  access_log_path: \"/dev/null\"\n  address:\n    socket_address:\n      address: 0.0.0.0\n      port_value: 8001\nlayered_runtime:\n  layers:\n    - name: static_layer_0\n      static_layer:\n        envoy:\n          resource_limits:\n            listener:\n              example_listener_name:\n                connection_limit: 10000\n        overload:\n          global_downstream_max_connections: 50000\n
"},{"location":"performance/#kyverno-authz-server","title":"Kyverno Authz Server","text":"

The third component is the Kyverno Authz Server itself, which is configured to load and enforce Kyverno policies on incoming requests.

"},{"location":"performance/#benchmark-scenarios","title":"Benchmark Scenarios","text":"

The following scenarios should be tested to compare the performance of the Kyverno Authz Server under different conditions:

  1. App Only: Requests are sent directly to the application, without Envoy or the Kyverno Authz Server.
  2. App and Envoy: Envoy is included in the request path, but the Kyverno Authz Server is not (i.e., Envoy External Authorization API is disabled).
  3. App, Envoy, and Kyverno: Envoy External Authorization API is enabled, and a sample real-world policy is loaded into the Kyverno Authz Server.
"},{"location":"performance/#load-testing-with-k6","title":"Load Testing with k6","text":"

To perform load testing, we'll use the k6 tool. Follow these steps:

  1. Install k6: Install k6 on your machine by following the instructions on the official website.

  2. Write the k6 script: Below is the example k6 script.

import http from 'k6/http';\nimport { check, group, sleep } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 100 }, // Ramp-up to 100 virtual users over 30 seconds\n    { duration: '1m', target: 100 }, // Stay at 100 virtual users for 1 minute\n    { duration: '30s', target: 0 }, // Ramp-down to 0 virtual users over 30 seconds\n  ],\n};\n\n/*\nReplace ip for every scenerio\nexport SERVICE_PORT=$(kubectl -n demo get service testapp -o jsonpath='{.spec.ports[?(@.port==8080)].nodePort}')\nexport SERVICE_HOST=$(minikube ip)\nexport SERVICE_URL=$SERVICE_HOST:$SERVICE_PORT\necho $SERVICE_URL\n\nhttp://192.168.49.2:31541\n\n*/\nconst BASE_URL = 'http://192.168.49.2:31541'; \n\nexport default function () {\n  group('GET /book with guest token', () => {\n    const res = http.get(`${BASE_URL}/book`, {\n      headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk' },\n    });\n    check(res, {\n      'is status 200': (r) => r.status === 200,\n    });\n  });\n\n  sleep(1); // Sleep for 1 second between iterations\n}\n
  1. Run the k6 test: Run the load test with the following command:
$ k6 run -f - <<EOF\nimport http from 'k6/http';\nimport { check, group, sleep } from 'k6';\n\nexport const options = {\n  stages: [\n    { duration: '30s', target: 100 }, // Ramp-up to 100 virtual users over 30 seconds\n    { duration: '1m', target: 100 }, // Stay at 100 virtual users for 1 minute\n    { duration: '30s', target: 0 }, // Ramp-down to 0 virtual users over 30 seconds\n  ],\n};\n\n\nconst BASE_URL = 'http://192.168.49.2:31700'; // Replace with your application URL \n\nexport default function () {\n  group('GET /book with guest token', () => {\n    const res = http.get(`${BASE_URL}/book`, {\n      headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk' },\n    });\n    check(res, {\n      'is status 200': (r) => r.status === 200,\n    });\n  });\n\n  sleep(1); // Sleep for 1 second between iterations\n}\nEOF\n
  1. Analyze the results: Generate an json report with detailed insight by running:

k6 run --out json=report.json k6-script.js\n
5. Repeat for different scenarios:

"},{"location":"performance/#measuring-performance","title":"Measuring Performance","text":"

The following metrics should be measured to evaluate the performance impact of the Kyverno Authz Server:

Observations:

Correlation with k6 results:

"},{"location":"policies/","title":"Policies","text":"

A Kyverno AuthorizationPolicy is a custom Kubernetes resources and can be easily managed via Kubernetes APIs, GitOps workflows, and other existing tools.

"},{"location":"policies/#resource-scope","title":"Resource Scope","text":"

A Kyverno AuthorizationPolicy is a cluster-wide resource.

"},{"location":"policies/#api-group-and-kind","title":"API Group and Kind","text":"

An AuthorizationPolicy belongs to the envoy.kyverno.io/v1alpha1 group and can only be of kind AuthorizationPolicy.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  # if something fails the request will be denied\n  failurePolicy: Fail\n  variables:\n    # `force_authorized` references the 'x-force-authorized' header\n    # from the envoy check request (or '' if not present)\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n    # `allowed` will be `true` if `variables.force_authorized` has the\n    # value 'enabled' or 'true'\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n    # make an authorisation decision based on the value of `variables.allowed`\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\n  allow:\n  - response: >\n      envoy.Allowed().Response()\n
"},{"location":"policies/#envoy-external-authorization","title":"Envoy External Authorization","text":"

The Kyverno Authz Server implements the Envoy External Authorization API.

A Kyverno AuthorizationPolicy analyses an Envoy CheckRequest and can make a decision by returning an OkResponse or DeniedResponse.

"},{"location":"policies/#cel-language","title":"CEL language","text":"

An AuthorizationPolicy uses the CEL language to process the CheckRequest sent by Envoy.

CEL is an expression language that\u2019s fast, portable, and safe to execute in performance-critical applications.

"},{"location":"policies/#policy-structure","title":"Policy structure","text":"

A Kyverno AuthorizationPolicy is made of:

"},{"location":"policies/authorization-rules/","title":"Authorization rules","text":"

An AuthorizationPolicy main concern is to define authorization rules to deny or allow requests.

Every authorization rule is made of an optional match statement and a required response statement. Both statements are written in CEL.

If the match statement is present and evaluates to true, the response statement is used to create the response payload returned to the envoy proxy. Depending on the rule type, the response is expected to be an envoy.OkResponse or envoy.DeniedResponse.

Creating an OkResponse or DeniedResponse can be a tedious task, you need to remember the different types names and format.

The CEL engine used to evaluate the authorization rules has been extended with a library to make the creation of responses easier. Browse the available libraries documentation for details.

"},{"location":"policies/authorization-rules/#evaluation-order","title":"Evaluation order","text":"
  1. All deny rules are evaluated first, the first matching rule is used to send the deny response to the envoy proxy.
  2. If no deny rule matched, allow rules are evaluated and the first matching rule is used to send the response to the envoy proxy.
  3. If no rule matched, the request is allowed by default.

Info

When multiple policies are present, deny and allow rules are concatenated together in policy name alphabetical order.

"},{"location":"policies/authorization-rules/#authorization-rules_1","title":"Authorization rules","text":"

The policy below will allow requests if they contain the header x-force-authorized with the value enabled or true. If the header is not present or has a different value, the request will be denied.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  # make an authorisation decision based on the value of `variables.allowed`\n  # - deny the request with 403 status code if it is `false`\n  # - else allow the request\n  deny:\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\n  allow:\n  - response: >\n      envoy.Allowed().Response()\n

In this simple rule:

However, we can do a lot more. Envoy can add or remove headers, query parameters, register dynamic metadata passed along the filters chain, and even change the response body.

"},{"location":"policies/authorization-rules/#the-hard-way","title":"The hard way","text":"

Below is the same policy, creating the envoy.OkResponse and envoy.DeniedResponse manually.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.DeniedResponse{\n        status: google.rpc.Status{\n          code: 7\n        },\n        denied_response: envoy.service.auth.v3.DeniedHttpResponse{\n          status: envoy.type.v3.HttpStatus{\n            code: 403\n          }\n        }\n      }\n  allow:\n  - response: >\n      envoy.OkResponse{\n        status: google.rpc.Status{\n          code: 0\n        },\n        ok_response: envoy.service.auth.v3.OkHttpResponse{}\n      }\n
"},{"location":"policies/authorization-rules/#advanced-example","title":"Advanced example","text":"

This second policy showcases a more advanced example.

apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo-policy.example.com\nspec:\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: force_unauthenticated\n    expression: object.attributes.request.http.headers[?\"x-force-unauthenticated\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: metadata\n    expression: '{\"my-new-metadata\": \"my-new-value\"}'\n  deny:\n    # if force_unauthenticated -> 401\n  - match: >\n      variables.force_unauthenticated\n    response: >\n      envoy\n        .Denied(401)\n        .WithBody(\"Authentication Failed\")\n        .Response()\n    # if not force_authorized -> 403\n  - match: >\n      !variables.force_authorized\n    response: >\n      envoy\n        .Denied(403)\n        .WithBody(\"Unauthorized Request\")\n        .Response()\n  allow:\n    # else -> 200\n  - response: >\n      envoy\n        .Allowed()\n        .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n        .WithoutHeader(\"x-force-authorized\")\n        .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n        .Response()\n        .WithMetadata(variables.metadata)\n

Notice this policy uses helper functions:

Info

The full documentation of the CEL Envoy library is available here.

"},{"location":"policies/failure-policy/","title":"Failure policy","text":"

FailurePolicy defines how to handle failures for the policy.

Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions.

Allowed values are:

If not set, the failure policy defaults to Fail.

Info

FailurePolicy does not define how validations that evaluate to false are handled.

"},{"location":"policies/failure-policy/#fail","title":"Fail","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  # if something fails the request will be denied\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\n
"},{"location":"policies/failure-policy/#ignore","title":"Ignore","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  # if something fails the failure will be ignored and the request will be allowed\n  failurePolicy: Ignore\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\n
"},{"location":"policies/variables/","title":"Variables","text":"

A Kyverno AuthorizationPolicy can define variables that will be made available to all authorization rules.

Variables can be used in composition of other expressions. Each variable is defined as a named CEL expression. The will be available under variables in other expressions of the policy.

The expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, variables must be sorted by the order of first appearance and acyclic.

Info

The incoming CheckRequest from Envoy is made available to the policy under the object identifier.

"},{"location":"policies/variables/#variables_1","title":"Variables","text":"
apiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n    # `force_authorized` references the 'x-force-authorized' header\n    # from the envoy check request (or '' if not present)\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n    # `allowed` will be `true` if `variables.force_authorized` has the\n    # value 'enabled' or 'true'\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n    # make an authorisation decision based on the value of `variables.allowed`\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\n
"},{"location":"quick-start/","title":"Quick start","text":"

The Kyverno Envoy Plugin is a powerful tool that integrates with the Envoy proxy.

It allows you to enforce Kyverno policies on incoming and outgoing traffic in a service mesh environment, providing an additional layer of security and control over your applications.

"},{"location":"quick-start/#overview","title":"Overview","text":"

Envoy is a Layer 7 proxy and communication bus tailored for large-scale, modern service-oriented architectures. Starting from version 1.7.0, Envoy includes an External Authorization filter that interfaces with an authorization service to determine the legitimacy of incoming requests.

This functionality allows authorization decisions to be offloaded to an external service, which can access the request context. The request context includes details such as the origin and destination of the network activity, as well as specifics of the network request (e.g., HTTP request). This information enables the external service to make a well-informed decision regarding the authorization of the incoming request processed by Envoy.

"},{"location":"quick-start/#what-is-the-kyverno-envoy-plugin","title":"What is the Kyverno Envoy Plugin?","text":"

The Kyverno Envoy Plugin is gRPC server that implements Envoy External Authorization API.

This allows you to enforce Kyverno policies on incoming and outgoing traffic in a service mesh environment, providing an additional layer of security and control over your applications. You can use this version of Kyverno to enforce fine-grained, context-aware access control policies with Envoy without modifying your microservice.

"},{"location":"quick-start/#how-does-this-work","title":"How does this work?","text":"

In addition to the Envoy sidecar, your application pods will include a Kyverno Authz Server component, either as a sidecar or as a separate pod. When Envoy receives an API request intended for your microservice, it consults the Kyverno Authz Server to determine whether the request should be permitted or not.

Performing policy evaluations locally with Envoy is advantageous, as it eliminates the need for an additional network hop for authorization checks, thus enhancing both performance and availability.

Info

The Kyverno Envoy Plugin is frequently deployed in Kubernetes environments as a sidecar container or as a separate pod. Additionally, it can be used in other environments as a standalone process running alongside Envoy.

"},{"location":"quick-start/#additional-resources","title":"Additional Resources","text":"

See the following pages on envoyproxy.io for more information on external authorization:

"},{"location":"quick-start/authz-server/","title":"Authz server","text":""},{"location":"quick-start/authz-server/#setup","title":"Setup","text":"

In this quick start guide we will deploy the Kyverno Authz Server inside a cluster.

Then you will interface Istio, an open source service mesh with the Kyverno Authz Server to delegate the request authorisation based on policies installed in the cluster.

"},{"location":"quick-start/authz-server/#prerequisites","title":"Prerequisites","text":""},{"location":"quick-start/authz-server/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"quick-start/authz-server/#configure-the-mesh","title":"Configure the mesh","text":"

We need to register the Kyverno Authz Server with Istio.

# configure the mesh\nistioctl install -y -f - <<EOF\napiVersion: install.istio.io/v1alpha1\nkind: IstioOperator\nspec:\n  meshConfig:\n    accessLogFile: /dev/stdout\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\nEOF\n

Notice that in the configuration, we define an extensionProviders section that points to the Kyverno Authz Server we will install in the next step:

[...]\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\n[...]\n
"},{"location":"quick-start/authz-server/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

The first step is to deploy the Kyverno Authz Server.

# create the kyverno namespace\nkubectl create ns kyverno\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace kyverno istio-injection=enabled\n\n# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --wait  \\\n  --repo https://kyverno.github.io/kyverno-envoy-plugin       \\\n  kyverno-authz-server\n
"},{"location":"quick-start/authz-server/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace demo istio-injection=enabled\n\n# deploy the httpbin application\nkubectl apply -n demo -f \\\n  https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml\n
"},{"location":"quick-start/authz-server/#deploy-an-istio-authorizationpolicy","title":"Deploy an Istio AuthorizationPolicy","text":"

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy\nkubectl apply -f - <<EOF\napiVersion: security.istio.io/v1\nkind: AuthorizationPolicy\nmetadata:\n  name: kyverno-authz-server\n  namespace: demo\nspec:\n  action: CUSTOM\n  provider:\n    name: kyverno-authz-server.local\n  rules:\n  - {} # empty rules, it will apply to all requests\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server extensionProvider you set in the Istio configuration:

[...]\n  provider:\n    name: kyverno-authz-server.local\n[...]\n
"},{"location":"quick-start/authz-server/#deploy-a-kyverno-authorizationpolicy","title":"Deploy a Kyverno AuthorizationPolicy","text":"

A Kyverno AuthorizationPolicy defines the rules used by the Kyverno authz server to make a decision based on a given Envoy CheckRequest.

It uses the CEL language to analyse the incoming CheckRequest and is expected to produce an OkResponse or DeniedResponse in return.

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\")\n  - name: allowed\n    expression: variables.force_authorized in [\"enabled\", \"true\"]\n  deny:\n  - match: >\n      !variables.allowed\n    response: >\n      envoy.Denied(403).Response()\nEOF\n

This simple policy will deny requests if they don't contain the header x-force-authorized with the value enabled or true.

"},{"location":"quick-start/authz-server/#testing","title":"Testing","text":"

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

"},{"location":"quick-start/authz-server/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"quick-start/authz-server/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"quick-start/authz-server/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send requests to the sample application and verify the result.

The following request will return 403 (denied by our policy):

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get\n

The following request will return 200 (allowed by our policy):

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"x-force-authorized: true\"\n
"},{"location":"quick-start/authz-server/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the quick start guide!

This tutorial demonstrated how to configure Istio\u2019s EnvoyFilter to utilize the Kyverno Authz Server as an external authorization service.

"},{"location":"quick-start/next-steps/","title":"Next steps","text":"

We covered the main components of the Kyverno Envoy Plugin.

Tip

If there's anything you would like to be improved, please reach out, we will be happy to discuss and improve as much as we can.

To continue exploring and learn more about the Kyverno Envoy Plugin:

"},{"location":"quick-start/sidecar-injector/","title":"Sidecar injector","text":"

This is not ready yet, hopefully it will be available soon!

"},{"location":"reference/","title":"Reference documentation","text":"

Info

Select an item in the navigation menu to browse a specific page.

"},{"location":"reference/json-schemas/","title":"JSON schemas","text":"

JSON schemas for the Kyverno Envoy Plugin are available:

They can be used to enable validation and autocompletion in your IDE.

"},{"location":"reference/json-schemas/#vs-code","title":"VS code","text":"

In VS code, simply add a comment on top of your YAML resources.

"},{"location":"reference/json-schemas/#authorizationpolicy","title":"AuthorizationPolicy","text":"
# yaml-language-server: $schema=https://raw.githubusercontent.com/kyverno/kyverno-envoy-plugin/main/.schemas/json/authorizationpolicy-envoy-v1alpha1.json\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo-policy.example.com\nspec:\n  variables:\n  - name: force_authorized\n    expression: object.attributes.request.http.headers[?\"x-force-authorized\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: force_unauthenticated\n    expression: object.attributes.request.http.headers[?\"x-force-unauthenticated\"].orValue(\"\") in [\"enabled\", \"true\"]\n  - name: metadata\n    expression: '{\"my-new-metadata\": \"my-new-value\"}'\n  deny:\n    # if force_unauthenticated -> 401\n  - match: >\n      variables.force_unauthenticated\n    response: >\n      envoy\n        .Denied(401)\n        .WithBody(\"Authentication Failed\")\n        .Response()\n        .WithMetadata(variables.metadata)\n    # if not force_authorized -> 403\n  - match: >\n      !variables.force_authorized\n    response: >\n      envoy\n        .Denied(403)\n        .WithBody(\"Unauthorized Request\")\n        .Response()\n  allow:\n    # else -> 200\n  - response: >\n      envoy\n        .Allowed()\n        .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n        .WithoutHeader(\"x-force-authorized\")\n        .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n        .Response()\n        .WithMetadata(variables.metadata)\n
"},{"location":"reference/apis/policy.v1alpha1/","title":"policy (v1alpha1)","text":""},{"location":"reference/apis/policy.v1alpha1/#resource-types","title":"Resource Types","text":""},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-AuthorizationPolicy","title":"AuthorizationPolicy","text":"

AuthorizationPolicy defines an authorization policy resource

Field Type Required Inline Description apiVersion string envoy.kyverno.io/v1alpha1 kind string AuthorizationPolicy metadata meta/v1.ObjectMeta No description provided. spec AuthorizationPolicySpec No description provided."},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-Authorization","title":"Authorization","text":"

Appears in:

Authorization defines an authorization policy rule

Field Type Required Inline Description match string

Match represents the match condition which will be evaluated by CEL. Must evaluate to bool.

response string

Response represents the response expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to CEL variables as well as some other useful variables: - 'object' - The object from the incoming request. (https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto#service-auth-v3-checkrequest) CEL expressions are expected to return an envoy CheckResponse (https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto#service-auth-v3-checkresponse).

"},{"location":"reference/apis/policy.v1alpha1/#envoy-kyverno-io-v1alpha1-AuthorizationPolicySpec","title":"AuthorizationPolicySpec","text":"

Appears in:

AuthorizationPolicySpec defines the spec of an authorization policy

Field Type Required Inline Description failurePolicy admissionregistration/v1.FailurePolicyType

FailurePolicy defines how to handle failures for the policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions. FailurePolicy does not define how validations that evaluate to false are handled. Allowed values are Ignore or Fail. Defaults to Fail.

matchConditions []admissionregistration/v1.MatchCondition

MatchConditions is a list of conditions that must be met for a request to be validated. An empty list of matchConditions matches all requests. The exact matching logic is (in order): 1. If ANY matchCondition evaluates to FALSE, the policy is skipped. 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated. 3. If any matchCondition evaluates to an error (but none are FALSE): - If failurePolicy=Fail, reject the request - If failurePolicy=Ignore, the policy is skipped

variables []admissionregistration/v1.Variable

Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under variables in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy. The expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.

deny []Authorization

Deny contain CEL expressions which is used to deny a request.

allow []Authorization

Allow contain CEL expressions which is used to allow a request.

"},{"location":"tutorials/","title":"Tutorials","text":"

If you didn't read the Quick start section yet, we really recommend giving it a try to discover and familiarise with the Kyverno Envoy Plugin components first.

"},{"location":"tutorials/envoy-gateway/","title":"Envoy Gateway","text":"

Envoy Gateway is an open source project for managing Envoy Proxy as a standalone or Kubernetes-based application gateway. Gateway API resources are used to dynamically provision and configure the managed Envoy Proxies.

This tutorial shows how Envoy Gateway can be configured to delegate authorization decisions to the Kyverno Authz Server.

"},{"location":"tutorials/envoy-gateway/#setup","title":"Setup","text":""},{"location":"tutorials/envoy-gateway/#prerequisites","title":"Prerequisites","text":""},{"location":"tutorials/envoy-gateway/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"tutorials/envoy-gateway/#install-envoy-gateway","title":"Install Envoy Gateway","text":"

First we need to install Envoy Gateway in the cluster.

# install envoy gateway\nhelm install envoy-gateway -n envoy-gateway-system --create-namespace --wait --version v1.2.2 oci://docker.io/envoyproxy/gateway-helm\n
"},{"location":"tutorials/envoy-gateway/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# deploy the httpbin application\nkubectl apply -n demo -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml\n
"},{"location":"tutorials/envoy-gateway/#create-a-gatewayclass-and-a-gateway","title":"Create a GatewayClass and a Gateway","text":"

With Envoy Gateway installed we can now create a Gateway. To do so we will also create a dedicated GatewayClass.

Depending on your setup you will potentially need to create an EnvoyProxy resource to customize the way Envoy Gateway will create the underlying Service. The script below creates one to set the name and type of the service because the kind cluster created in the first step doesn't come with load balancer support.

# create a gateway\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.envoyproxy.io/v1alpha1\nkind: EnvoyProxy\nmetadata:\n  name: demo\nspec:\n  provider:\n    type: Kubernetes\n    kubernetes:\n      envoyService:\n        name: internet   # use a known name for the created service\n        type: ClusterIP  # because a kind cluster has no support for LB\n---\napiVersion: gateway.networking.k8s.io/v1\nkind: GatewayClass\nmetadata:\n  name: demo\nspec:\n  controllerName: gateway.envoyproxy.io/gatewayclass-controller\n---\napiVersion: gateway.networking.k8s.io/v1\nkind: Gateway\nmetadata:\n  name: demo\nspec:\n  gatewayClassName: demo\n  infrastructure:\n    parametersRef:\n      group: gateway.envoyproxy.io\n      kind: EnvoyProxy\n      name: demo\n  listeners:\n  - name: http\n    protocol: HTTP\n    port: 80\nEOF\n
"},{"location":"tutorials/envoy-gateway/#create-an-httproute-to-the-sample-application","title":"Create an HTTPRoute to the sample application","text":"

Next, we need to link the Gateway to our sample applicate with an HTTPRoute.

# create an http route to the sample app\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.networking.k8s.io/v1\nkind: HTTPRoute\nmetadata:\n  name: demo\nspec:\n  parentRefs:\n  - name: demo\n  rules:\n  - matches:\n    - path:\n        type: PathPrefix\n        value: /\n    backendRefs:\n    - group: ''\n      kind: Service\n      name: httpbin\n      port: 8000\n      weight: 1\nEOF\n
"},{"location":"tutorials/envoy-gateway/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

Now deploy the Kyverno Authz Server.

# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --create-namespace --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server\n
"},{"location":"tutorials/envoy-gateway/#create-a-kyverno-authorizationpolicy","title":"Create a Kyverno AuthorizationPolicy","text":"

In summary the policy below does the following:

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: authorization\n    expression: object.attributes.request.http.headers[?\"authorization\"].orValue(\"\").split(\" \")\n  - name: token\n    expression: >\n      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == \"bearer\"\n        ? jwt.Decode(variables.authorization[1], \"secret\")\n        : null\n  deny:\n    # request not authenticated -> 401\n  - match: >\n      variables.token == null || !variables.token.Valid\n    response: >\n      envoy.Denied(401).Response()\n    # request authenticated but not admin role -> 403\n  - match: >\n      variables.token.Claims.?role.orValue(\"\") != \"admin\"\n    response: >\n      envoy.Denied(403).Response()\n  allow:\n    # request authenticated and admin role -> 200\n  - response: >\n      envoy\n        .Allowed()\n        .WithHeader(\"x-validated-by\", \"my-security-checkpoint\")\n        .WithoutHeader(\"x-force-authorized\")\n        .WithResponseHeader(\"x-add-custom-response-header\", \"added\")\n        .Response()\nEOF\n
"},{"location":"tutorials/envoy-gateway/#deploy-an-envoy-gateway-securitypolicy","title":"Deploy an Envoy Gateway SecurityPolicy","text":"

A SecurityPolicy is the custom Envoy Gateway resource to configure underlying Envoy Proxy to use an external auth server (the Kyverno Authz Server we installed in a prior step).

# deploy envoy gateway security policy\nkubectl apply -n demo -f - <<EOF\napiVersion: gateway.envoyproxy.io/v1alpha1\nkind: SecurityPolicy\nmetadata:\n  name: demo\nspec:\n  targetRefs:\n  - group: gateway.networking.k8s.io\n    kind: HTTPRoute\n    name: demo\n  extAuth:\n    grpc:\n      backendRef:\n        group: ''\n        kind: Service\n        name: kyverno-authz-server\n        namespace: kyverno\n        port: 9081\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server service as the GRPC backend:

[...]\n  extAuth:\n    grpc:\n      backendRef:\n        group: ''\n        kind: Service\n        name: kyverno-authz-server\n        namespace: kyverno\n        port: 9081\n[...]\n

Also notice that the security policy applies to the demo HTTPRoute:

[...]\n  targetRefs:\n    - group: gateway.networking.k8s.io\n      kind: HTTPRoute\n      name: demo\n[...]\n
"},{"location":"tutorials/envoy-gateway/#grant-access-to-the-kyverno-authz-server-service","title":"Grant access to the Kyverno Authz Server service","text":"

Last thing we need to configure is to grant access to the Kyverno Authz Server service for our SecurityPolicy to take effect.

# grant access\nkubectl apply -n kyverno -f - <<EOF\napiVersion: gateway.networking.k8s.io/v1beta1\nkind: ReferenceGrant\nmetadata:\n  name: demo\nspec:\n  from:\n  - group: gateway.envoyproxy.io\n    kind: SecurityPolicy\n    namespace: demo\n  to:\n  - group: ''\n    kind: Service\nEOF\n
"},{"location":"tutorials/envoy-gateway/#testing","title":"Testing","text":"

At this we have deployed and configured Envoy Gateway, the Kyverno Authz Server, a sample application, and the authorization and security policies.

"},{"location":"tutorials/envoy-gateway/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"tutorials/envoy-gateway/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"tutorials/envoy-gateway/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send request to the sample application and verify the result.

For convenience, we will store Alice\u2019s and Bob\u2019s tokens in environment variables.

Here Bob is assigned the admin role and Alice is assigned the guest role.

export ALICE_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk\"\nexport BOB_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6ImFkbWluIiwic3ViIjoiWVd4cFkyVT0ifQ.veMeVDYlulTdieeX-jxFZ_tCmqQ_K8rwx2OktUHv5Z0\"\n

Calling without a JWT token will return 401:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get\n

Calling with Alice\u2019s JWT token will return 403:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get -H \"authorization: Bearer $ALICE_TOKEN\"\n

Calling with Bob\u2019s JWT token will return 200:

curl -s -w \"\\nhttp_code=%{http_code}\" internet.envoy-gateway-system/get -H \"authorization: Bearer $BOB_TOKEN\"\n
"},{"location":"tutorials/envoy-gateway/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the tutorial!

This tutorial demonstrated how to configure Envoy Gateway to utilize the Kyverno Authz Server as an external authorization service.

Additionally, the tutorial provided an example policy to decode a JWT token and make a decision based on it.

"},{"location":"tutorials/istio/","title":"Istio","text":"

Istio is an open source service mesh for managing the different microservices that make up a cloud-native application. Istio provides a mechanism to use a service as an external authorizer with the AuthorizationPolicy API.

This tutorial shows how Istio\u2019s AuthorizationPolicy can be configured to delegate authorization decisions to the Kyverno Authz Server.

"},{"location":"tutorials/istio/#setup","title":"Setup","text":""},{"location":"tutorials/istio/#prerequisites","title":"Prerequisites","text":""},{"location":"tutorials/istio/#setup-a-cluster-optional","title":"Setup a cluster (optional)","text":"

If you don't have a cluster at hand, you can create a local one with kind.

KIND_IMAGE=kindest/node:v1.31.1\n\n# create cluster\nkind create cluster --image $KIND_IMAGE --wait 1m\n
"},{"location":"tutorials/istio/#configure-the-mesh","title":"Configure the mesh","text":"

We need to register the Kyverno Authz Server with Istio.

# configure the mesh\nistioctl install -y -f - <<EOF\napiVersion: install.istio.io/v1alpha1\nkind: IstioOperator\nspec:\n  meshConfig:\n    accessLogFile: /dev/stdout\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\nEOF\n

Notice that in the configuration, we define an extensionProviders section that points to the Kyverno Authz Server we will install in the next step:

[...]\n    extensionProviders:\n    - name: kyverno-authz-server.local\n      envoyExtAuthzGrpc:\n        service: kyverno-authz-server.kyverno.svc.cluster.local\n        port: '9081'\n[...]\n
"},{"location":"tutorials/istio/#deploy-the-kyverno-authz-server","title":"Deploy the Kyverno Authz Server","text":"

The first step is to deploy the Kyverno Authz Server.

# create the kyverno namespace\nkubectl create ns kyverno\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace kyverno istio-injection=enabled\n\n# deploy the kyverno authz server\nhelm install kyverno-authz-server --namespace kyverno --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server\n
"},{"location":"tutorials/istio/#deploy-a-sample-application","title":"Deploy a sample application","text":"

Httpbin is a well-known application that can be used to test HTTP requests and helps to show quickly how we can play with the request and response attributes.

# create the demo namespace\nkubectl create ns demo\n\n# label the namespace to inject the envoy proxy\nkubectl label namespace demo istio-injection=enabled\n\n# deploy the httpbin application\nkubectl apply -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml -n demo\n
"},{"location":"tutorials/istio/#deploy-an-istio-authorizationpolicy","title":"Deploy an Istio AuthorizationPolicy","text":"

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy\nkubectl apply -f - <<EOF\napiVersion: security.istio.io/v1\nkind: AuthorizationPolicy\nmetadata:\n  name: kyverno-authz-server\n  namespace: demo\nspec:\n  action: CUSTOM\n  provider:\n    name: kyverno-authz-server.local\n  rules:\n  - {} # empty rules, it will apply to all requests\nEOF\n

Notice that in this resource, we define the Kyverno Authz Server extensionProvider you set in the Istio configuration:

[...]\n  provider:\n    name: kyverno-authz-server.local\n[...]\n
"},{"location":"tutorials/istio/#create-a-kyverno-authorizationpolicy","title":"Create a Kyverno AuthorizationPolicy","text":"

In summary the policy below does the following:

# deploy kyverno authorization policy\nkubectl apply -f - <<EOF\napiVersion: envoy.kyverno.io/v1alpha1\nkind: AuthorizationPolicy\nmetadata:\n  name: demo\nspec:\n  failurePolicy: Fail\n  variables:\n  - name: authorization\n    expression: object.attributes.request.http.headers[?\"authorization\"].orValue(\"\").split(\" \")\n  - name: token\n    expression: >\n      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == \"bearer\"\n        ? jwt.Decode(variables.authorization[1], \"secret\")\n        : null\n  deny:\n    # request not authenticated -> 401\n  - match: >\n      variables.token == null || !variables.token.Valid\n    response: >\n      envoy.Denied(401).Response()\n    # request authenticated but not admin role -> 403\n  - match: >\n      variables.token.Claims.?role.orValue(\"\") != \"admin\"\n    response: >\n      envoy.Denied(403).Response()\n  allow:\n    # request authenticated and admin role -> 200\n  - response: >\n      envoy.Allowed().Response()\nEOF\n
"},{"location":"tutorials/istio/#testing","title":"Testing","text":"

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

"},{"location":"tutorials/istio/#start-an-in-cluster-shell","title":"Start an in-cluster shell","text":"

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell\nkubectl run -i -t busybox --image=alpine --restart=Never -n demo\n
"},{"location":"tutorials/istio/#install-curl","title":"Install curl","text":"

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl\napk add curl\n
"},{"location":"tutorials/istio/#call-into-the-sample-application","title":"Call into the sample application","text":"

Now we can send request to the sample application and verify the result.

For convenience, we will store Alice\u2019s and Bob\u2019s tokens in environment variables.

Here Bob is assigned the admin role and Alice is assigned the guest role.

export ALICE_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk\"\nexport BOB_TOKEN=\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6ImFkbWluIiwic3ViIjoiWVd4cFkyVT0ifQ.veMeVDYlulTdieeX-jxFZ_tCmqQ_K8rwx2OktUHv5Z0\"\n

Calling without a JWT token will return 401:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get\n

Calling with Alice\u2019s JWT token will return 403:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"authorization: Bearer $ALICE_TOKEN\"\n

Calling with Bob\u2019s JWT token will return 200:

curl -s -w \"\\nhttp_code=%{http_code}\" httpbin:8000/get -H \"authorization: Bearer $BOB_TOKEN\"\n
"},{"location":"tutorials/istio/#wrap-up","title":"Wrap Up","text":"

Congratulations on completing the tutorial!

This tutorial demonstrated how to configure Istio\u2019s EnvoyFilter to utilize the Kyverno Authz Server as an external authorization service.

Additionally, the tutorial provided an example policy to decode a JWT token and make a decision based on it.

"}]} \ No newline at end of file diff --git a/main/tutorials/envoy-gateway/index.html b/main/tutorials/envoy-gateway/index.html index 02f4792..d0e6942 100644 --- a/main/tutorials/envoy-gateway/index.html +++ b/main/tutorials/envoy-gateway/index.html @@ -10,121 +10,122 @@ # deploy the httpbin application kubectl apply -n demo -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml

Create a GatewayClass and a Gateway

With Envoy Gateway installed we can now create a Gateway. To do so we will also create a dedicated GatewayClass.

Depending on your setup you will potentially need to create an EnvoyProxy resource to customize the way Envoy Gateway will create the underlying Service. The script below creates one to set the name and type of the service because the kind cluster created in the first step doesn't come with load balancer support.

# create a gateway
-kubectl apply -n demo -f - <<EOF
-apiVersion: gateway.envoyproxy.io/v1alpha1
-kind: EnvoyProxy
-metadata:
-  name: demo
-spec:
-  provider:
-    type: Kubernetes
-    kubernetes:
-      envoyService:
-        name: internet   # use a known name for the created service
-        type: ClusterIP  # because a kind cluster has no support for LB
----
-apiVersion: gateway.networking.k8s.io/v1
-kind: GatewayClass
-metadata:
-  name: demo
-spec:
-  controllerName: gateway.envoyproxy.io/gatewayclass-controller
----
-apiVersion: gateway.networking.k8s.io/v1
-kind: Gateway
-metadata:
-  name: demo
-spec:
-  gatewayClassName: demo
-  infrastructure:
-    parametersRef:
-      group: gateway.envoyproxy.io
-      kind: EnvoyProxy
-      name: demo
-  listeners:
-    - name: http
-      protocol: HTTP
-      port: 80
-EOF
+kubectl apply -n demo -f - <<EOF
+apiVersion: gateway.envoyproxy.io/v1alpha1
+kind: EnvoyProxy
+metadata:
+  name: demo
+spec:
+  provider:
+    type: Kubernetes
+    kubernetes:
+      envoyService:
+        name: internet   # use a known name for the created service
+        type: ClusterIP  # because a kind cluster has no support for LB
+---
+apiVersion: gateway.networking.k8s.io/v1
+kind: GatewayClass
+metadata:
+  name: demo
+spec:
+  controllerName: gateway.envoyproxy.io/gatewayclass-controller
+---
+apiVersion: gateway.networking.k8s.io/v1
+kind: Gateway
+metadata:
+  name: demo
+spec:
+  gatewayClassName: demo
+  infrastructure:
+    parametersRef:
+      group: gateway.envoyproxy.io
+      kind: EnvoyProxy
+      name: demo
+  listeners:
+  - name: http
+    protocol: HTTP
+    port: 80
+EOF
 

Create an HTTPRoute to the sample application

Next, we need to link the Gateway to our sample applicate with an HTTPRoute.

# create an http route to the sample app
-kubectl apply -n demo -f - <<EOF
-apiVersion: gateway.networking.k8s.io/v1
-kind: HTTPRoute
-metadata:
-  name: demo
-spec:
-  parentRefs:
-  - name: demo
-  rules:
-    - matches:
-        - path:
-            type: PathPrefix
-            value: /
-      backendRefs:
-        - group: ''
-          kind: Service
-          name: httpbin
-          port: 8000
-          weight: 1
-EOF
+kubectl apply -n demo -f - <<EOF
+apiVersion: gateway.networking.k8s.io/v1
+kind: HTTPRoute
+metadata:
+  name: demo
+spec:
+  parentRefs:
+  - name: demo
+  rules:
+  - matches:
+    - path:
+        type: PathPrefix
+        value: /
+    backendRefs:
+    - group: ''
+      kind: Service
+      name: httpbin
+      port: 8000
+      weight: 1
+EOF
 

Deploy the Kyverno Authz Server

Now deploy the Kyverno Authz Server.

# deploy the kyverno authz server
 helm install kyverno-authz-server --namespace kyverno --create-namespace --wait --repo https://kyverno.github.io/kyverno-envoy-plugin kyverno-authz-server
 

Create a Kyverno AuthorizationPolicy

In summary the policy below does the following:

# deploy kyverno authorization policy
-kubectl apply -f - <<EOF
-apiVersion: envoy.kyverno.io/v1alpha1
-kind: AuthorizationPolicy
-metadata:
-  name: demo
-spec:
-  failurePolicy: Fail
-  variables:
-  - name: authorization
-    expression: object.attributes.request.http.headers[?"authorization"].orValue("").split(" ")
-  - name: token
-    expression: >
-      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == "bearer"
-        ? jwt.Decode(variables.authorization[1], "secret")
-        : null
-  authorizations:
-    # request not authenticated -> 401
-  - expression: >
-      variables.token == null || !variables.token.Valid
-        ? envoy.Denied(401).Response()
-        : null
-    # request authenticated but not admin role -> 403
-  - expression: >
-      variables.token.Claims.?role.orValue("") != "admin"
-        ? envoy.Denied(403).Response()
-        : null
-    # request authenticated and admin role -> 200
-  - expression: >
-      envoy
-        .Allowed()
-        .WithHeader("x-validated-by", "my-security-checkpoint")
-        .WithoutHeader("x-force-authorized")
-        .WithResponseHeader("x-add-custom-response-header", "added")
-        .Response()
-EOF
+kubectl apply -f - <<EOF
+apiVersion: envoy.kyverno.io/v1alpha1
+kind: AuthorizationPolicy
+metadata:
+  name: demo
+spec:
+  failurePolicy: Fail
+  variables:
+  - name: authorization
+    expression: object.attributes.request.http.headers[?"authorization"].orValue("").split(" ")
+  - name: token
+    expression: >
+      size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == "bearer"
+        ? jwt.Decode(variables.authorization[1], "secret")
+        : null
+  deny:
+    # request not authenticated -> 401
+  - match: >
+      variables.token == null || !variables.token.Valid
+    response: >
+      envoy.Denied(401).Response()
+    # request authenticated but not admin role -> 403
+  - match: >
+      variables.token.Claims.?role.orValue("") != "admin"
+    response: >
+      envoy.Denied(403).Response()
+  allow:
+    # request authenticated and admin role -> 200
+  - response: >
+      envoy
+        .Allowed()
+        .WithHeader("x-validated-by", "my-security-checkpoint")
+        .WithoutHeader("x-force-authorized")
+        .WithResponseHeader("x-add-custom-response-header", "added")
+        .Response()
+EOF
 

Deploy an Envoy Gateway SecurityPolicy

A SecurityPolicy is the custom Envoy Gateway resource to configure underlying Envoy Proxy to use an external auth server (the Kyverno Authz Server we installed in a prior step).

# deploy envoy gateway security policy
-kubectl apply -n demo -f - <<EOF
-apiVersion: gateway.envoyproxy.io/v1alpha1
-kind: SecurityPolicy
-metadata:
-  name: demo
-spec:
-  targetRefs:
-    - group: gateway.networking.k8s.io
-      kind: HTTPRoute
-      name: demo
-  extAuth:
-    grpc:
-      backendRef:
-        group: ''
-        kind: Service
-        name: kyverno-authz-server
-        namespace: kyverno
-        port: 9081
-EOF
+kubectl apply -n demo -f - <<EOF
+apiVersion: gateway.envoyproxy.io/v1alpha1
+kind: SecurityPolicy
+metadata:
+  name: demo
+spec:
+  targetRefs:
+  - group: gateway.networking.k8s.io
+    kind: HTTPRoute
+    name: demo
+  extAuth:
+    grpc:
+      backendRef:
+        group: ''
+        kind: Service
+        name: kyverno-authz-server
+        namespace: kyverno
+        port: 9081
+EOF
 

Notice that in this resource, we define the Kyverno Authz Server service as the GRPC backend:

[...]
   extAuth:
     grpc:
@@ -142,20 +143,20 @@
       name: demo
 [...]
 

Grant access to the Kyverno Authz Server service

Last thing we need to configure is to grant access to the Kyverno Authz Server service for our SecurityPolicy to take effect.

# grant access
-kubectl apply -n kyverno -f - <<EOF
-apiVersion: gateway.networking.k8s.io/v1beta1
-kind: ReferenceGrant
-metadata:
-  name: demo
-spec:
-  from:
-  - group: gateway.envoyproxy.io
-    kind: SecurityPolicy
-    namespace: demo
-  to:
-  - group: ''
-    kind: Service
-EOF
+kubectl apply -n kyverno -f - <<EOF
+apiVersion: gateway.networking.k8s.io/v1beta1
+kind: ReferenceGrant
+metadata:
+  name: demo
+spec:
+  from:
+  - group: gateway.envoyproxy.io
+    kind: SecurityPolicy
+    namespace: demo
+  to:
+  - group: ''
+    kind: Service
+EOF
 

Testing

At this we have deployed and configured Envoy Gateway, the Kyverno Authz Server, a sample application, and the authorization and security policies.

Start an in-cluster shell

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell
 kubectl run -i -t busybox --image=alpine --restart=Never -n demo
 

Install curl

We will use curl to call into the sample application but it's not installed in our shell, let's install it in the pod.

# install curl
diff --git a/main/tutorials/istio/index.html b/main/tutorials/istio/index.html
index 39bf516..2a3d791 100644
--- a/main/tutorials/istio/index.html
+++ b/main/tutorials/istio/index.html
@@ -3,18 +3,18 @@
 # create cluster
 kind create cluster --image $KIND_IMAGE --wait 1m
 

Configure the mesh

We need to register the Kyverno Authz Server with Istio.

# configure the mesh
-istioctl install -y -f - <<EOF
-apiVersion: install.istio.io/v1alpha1
-kind: IstioOperator
-spec:
-  meshConfig:
-    accessLogFile: /dev/stdout
-    extensionProviders:
-    - name: kyverno-authz-server.local
-      envoyExtAuthzGrpc:
-        service: kyverno-authz-server.kyverno.svc.cluster.local
-        port: '9081'
-EOF
+istioctl install -y -f - <<EOF
+apiVersion: install.istio.io/v1alpha1
+kind: IstioOperator
+spec:
+  meshConfig:
+    accessLogFile: /dev/stdout
+    extensionProviders:
+    - name: kyverno-authz-server.local
+      envoyExtAuthzGrpc:
+        service: kyverno-authz-server.kyverno.svc.cluster.local
+        port: '9081'
+EOF
 

Notice that in the configuration, we define an extensionProviders section that points to the Kyverno Authz Server we will install in the next step:

[...]
     extensionProviders:
     - name: kyverno-authz-server.local
@@ -39,19 +39,19 @@
 # deploy the httpbin application
 kubectl apply -f https://raw.githubusercontent.com/istio/istio/master/samples/httpbin/httpbin.yaml -n demo
 

Deploy an Istio AuthorizationPolicy

An AuthorizationPolicy is the custom Istio resource that defines the services that will be protected by the Kyverno Authz Server.

# deploy istio authorization policy
-kubectl apply -f - <<EOF
-apiVersion: security.istio.io/v1
-kind: AuthorizationPolicy
-metadata:
-  name: kyverno-authz-server
-  namespace: demo
-spec:
-  action: CUSTOM
-  provider:
-    name: kyverno-authz-server.local
-  rules:
-  - {} # empty rules, it will apply to all requests
-EOF
+kubectl apply -f - <<EOF
+apiVersion: security.istio.io/v1
+kind: AuthorizationPolicy
+metadata:
+  name: kyverno-authz-server
+  namespace: demo
+spec:
+  action: CUSTOM
+  provider:
+    name: kyverno-authz-server.local
+  rules:
+  - {} # empty rules, it will apply to all requests
+EOF
 

Notice that in this resource, we define the Kyverno Authz Server extensionProvider you set in the Istio configuration:

[...]
   provider:
     name: kyverno-authz-server.local
@@ -72,19 +72,20 @@
       size(variables.authorization) == 2 && variables.authorization[0].lowerAscii() == "bearer"
         ? jwt.Decode(variables.authorization[1], "secret")
         : null
-  authorizations:
+  deny:
     # request not authenticated -> 401
-  - expression: >
+  - match: >
       variables.token == null || !variables.token.Valid
-        ? envoy.Denied(401).Response()
-        : null
+    response: >
+      envoy.Denied(401).Response()
     # request authenticated but not admin role -> 403
-  - expression: >
+  - match: >
       variables.token.Claims.?role.orValue("") != "admin"
-        ? envoy.Denied(403).Response()
-        : null
+    response: >
+      envoy.Denied(403).Response()
+  allow:
     # request authenticated and admin role -> 200
-  - expression: >
+  - response: >
       envoy.Allowed().Response()
 EOF
 

Testing

At this we have deployed and configured Istio, the Kyverno Authz Server, a sample application, and the authorization policies.

Start an in-cluster shell

Let's start a pod in the cluster with a shell to call into the sample application.

# run an in-cluster shell