2. Understand jsPolicy
jsPolicy is a policy engine for Kubernetes that allows you to write policies in JavaScript or TypeScript.
JsPolicy CRD#
jsPolicy provides three types of policies:
type: | Mutating | Validating | Controller |
|---|---|---|---|
| Trigger | Requests to k8s API server | Requests to k8s API server | Changes to k8s object (Events) |
| Execution Order | sequential | parallel | queued |
| Expected Result | mutate() request object | allow() or deny() request | anything |
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:
- Placing raw JavaScript code as a string into the
spec.javascriptfield of aJsPolicyobject (see Quickstart example policy) - Creating a
PolicyBundleobject with the same name as the correspondingJsPolicyobject and placing a base64 encoded and gzip compressed version of your JavaScript code in thespec.bundlefield of thePolicyBundleobject
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.