Skip to main content

2. Understand jsPolicy

jsPolicy is a policy engine for Kubernetes that allows you to write policies in JavaScript or TypeScript.

jsPolicy Architecture
jsPolicy - Architecture

JsPolicy CRD#

jsPolicy provides three types of policies:

TriggerRequests to k8s API serverRequests to k8s API serverChanges to k8s object (Events)
Execution Ordersequentialparallelqueued
Expected Resultmutate() request objectallow() or deny() requestanything

Mutating and Validating policies run during a HTTP request to the Kubernetes API server. After Kubernetes performs authentication and authorization (RBAC), it runs the Mutating policies sequentially and then runs all Validating policies in parallel. If any of the Validating policies calls deny(), the request will be aborted and not persisted in etcd.

Controller policies are not part of any Kubernetes API server request. Instead, they are triggered asynchronuously by Events in your Kubernetes cluster. Every CRUD operation on any of the Kubernetes objects in your cluster creates an Event. jsPolicy listens to these events and executes the matching Controller policies which can perform any kind of action in response to an Event, including also executing other CRUD operations in your cluster.

Deny vs Warn

Mutating and validating policies may also use warn() to display warnings to client, i.e. these warnings will not impact the request itself but they are shown in the kubectl output for example.

JsPolicyBundle CRD#

There are two ways to provide policy code to jsPolicy:

  1. Placing raw JavaScript code as a string into the spec.javascript field of a JsPolicy object (see Quickstart example policy)
  2. Creating a PolicyBundle object with the same name as the corresponding JsPolicy object and placing a base64 encoded and gzip compressed version of your JavaScript code in the spec.bundle field of the PolicyBundle object

Creating the PolicyBundle object yourself has the advantage that you can easily generate it automatically from JavaScript or TypeScript code using tools such as webpack which lets you write and test your policy code as part of regular JavaScript or TypeScript projects rather than having to place JavaScript code inside YAML code which will cause issues with auto-completion, type checks, linting and other convenience features of your IDE. Additionally, you can use TypeScript and ES6 language features which are otherwise not supported.

If you choose the trivial option 1 and you place your policy code directly inside the spec.javascript field of a JsPolicy, the Policy Compiler of jsPolicy will detect this and automatically generate a PolicyBundle object out of this JavaScript code using webpack.

JsPolicyViolations CRD#

jsPolicy creates JsPolicyViolations objects with information about denied requests and errors during the execution of policies. These objects can be queried using kubectl and the Kubernetes API server to set up alerting and monitoring for policy exection.