Skip to main content

Writing Policy Logic

Writing policies for jsPolicy generally means that you need to define two things:

  1. Policy Settings: JsPolicy specifies the type of policy and defines when this policy should apply
  2. Policy Logic: Put the logic into the spec.javascript of a JsPolicy or use a separate JsPolicyBundle that contains the policy logic in the form of base64 encoded, compressed JavaScript code

Write Policy Logic#

There are different ways to write policy logic for JsPolicy. The following table compares three common workflows:

Embedded spec.javascriptSeparate JavaScriptTypeScript
LanguageJavaScriptJavaScriptTypeScript (modern)
Type Safetynonoyes
IDE Supportbad (JavaScript in YAML)goodgreat (auto-completion, warnings, types)
Testingonly end-to-end via test kubectl requestsunit, functional and end-to-end testsunit, functional and end-to-end tests
Publishingonly via JsPolicy YAML filesvia npm packagesvia npm packages
JsBundle Generationautomatic by jsPolicymanual or via dev tools (SDK)manual or via dev tools (SDK)
SDK-jsPolicy SDKjsPolicy SDK

Inline JavaScript Policies#

Use the spec.javascript option of the JsPolicy CRD to write policy code inline as embedded JavaScript ES5 (vanilla JS):

kind: JsPolicy
name: ""
operations: ["CREATE"]
resources: ["*"]
scope: Namespaced
javascript: |
if (request.namespace === "default") {
deny("Creation of resources within the default namespace is not allowed!");

Dependencies For Embedded JavaScript Policies#

Use the spec.dependencies option to define dependencies that you want to load for this policy. You can specify any CommonJS package from the npm registry here or import your own packages.

Separate JavaScript or TypeScript#

You can use a separate JavaScript project to build, test and deploy your policies. Any language that can get cross-compiled to Javascript is supported. Please take a look at our Policy SDK or TypeScript example on how to write policies and compile them to JsPolicy and JsPolicyBundle objects.