We recommend to get familiar with the Policy concept before writing your first policy.

Write your first custom policy

Chainloop platform comes with a set of built-in policies that can be used out of the box but in some cases you may want to write your own. Writing a policy in Chainloop usually involves
1

Initialize and scaffold your policy

2

Write the policy logic in Rego

3

Lint and validate the policy

4

Test the policy with sample materials

Quickstart

Getting Started with Policy Development CLI Tools

Chainloop provides a complete set of CLI tools to streamline your policy development workflow. These tools help you create, validate, and test policies locally before deploying them. Let’s walk through creating a policy that validates SBOM freshness: Step 1: Initialize the policy
chainloop policy develop init --embedded --name cdx-fresh --description "Checks that SBOM is maximum of 30 days old"
Step 2: Download the working example Instead of editing from scratch, let’s use a complete working example:
# Download the complete policy example
curl -O https://raw.githubusercontent.com/chainloop-dev/chainloop/refs/heads/main/docs/examples/policies/quickstart/cdx-fresh.yaml

# Download sample materials for testing
curl -O https://raw.githubusercontent.com/chainloop-dev/chainloop/refs/heads/main/docs/examples/policies/quickstart/cdx-old.json
curl -O https://raw.githubusercontent.com/chainloop-dev/chainloop/refs/heads/main/docs/examples/policies/quickstart/cdx-fresh.json
Step 3: Lint the policy
chainloop policy develop lint --policy cdx-fresh.yaml --format
Step 4: Test the policy
# Test with old SBOM (should fail)
chainloop policy develop eval --policy cdx-fresh.yaml --material cdx-old.json --kind SBOM_CYCLONEDX_JSON

# Test with fresh SBOM (should pass)
chainloop policy develop eval --policy cdx-fresh.yaml --material cdx-fresh.json --kind SBOM_CYCLONEDX_JSON
For a complete step-by-step guide with working examples, see our quickstart examples and other policies in our repository.

CLI Commands Reference

For detailed CLI usage and all available flags, see the CLI help.

Development Workflow Overview

The Chainloop CLI provides a structured, iterative workflow for developing high-quality policies. Whether you’re validating security rules, SBOM compliance, or custom attestations, this development loop ensures accuracy and maintainability.

Workflow Phases

  1. Initialize your policy project - Start by generating a new policy using the init command. This ensures a consistent file structure and reduces manual setup.
  2. Develop and refine your Rego logic - Within the generated policy.yaml, add Rego code tailored to your use case. You can begin with common patterns, then incrementally build more complex logic.
  3. Validate syntax and structure early and often - Use the lint command to detect issues. This ensures both the YAML structure and Rego code are valid, enforcing best practices via Open Policy Agent (OPA) and Regal.
  4. Evaluate policy logic with real inputs - Use sample SBOMs, attestations, or other artifacts to test your policy’s behavior with the eval command. Violations or pass/fail results will be shown clearly, helping you quickly spot logic issues or edge cases.
  5. Iterate and refine until policy behaves as expected - Use the feedback from eval to adjust your Rego rules. Re-run lint and eval until you’re confident in the policy behavior.
  6. Deploy to production - Once your policy is stable and validated, it’s ready to be versioned and rolled out into Chainloop and your CI/CD pipelines.
This iterative approach helps catch issues early and ensures your policies work correctly before deployment.

In-Depth Policy Structure

Chainloop Policy YAML

A policy can be defined in a YAML document, like this:
cyclonedx-licenses.yaml
apiVersion: workflowcontract.chainloop.dev/v1
kind: Policy
metadata:
  name: cyclonedx-licenses
  description: Checks for components without licenses
  annotations:
    category: sbom
spec:
  policies:
  - kind: SBOM_CYCLONEDX_JSON
    embedded: |
      package main
  
      import rego.v1
      
      # Global result object
      result := {
        "skipped": skipped,
        "violations": violations,
        "skip_reason": skip_reason,
      }
  
      default skip_reason := ""
      
      skip_reason := m if {
        not valid_input
        m := "the file content is not recognized"
      }
      
      default skipped := true
      
      skipped := false if valid_input
      
      valid_input if {
        # expect at least 1 component in the SBOM
        count(input.components) > 0
      }
  
      violations contains msg if {
        count(without_license) > 0
        msg := sprintf("Missing licenses for %s", [components_str])
      }
  
      components_str := concat(", ", [comp.purl | some comp in without_license])
  
      without_license contains comp if {
        some comp in input.components
        not comp.licenses
      }

In this particular example, we see:
  • policies have a name (cyclonedx-licenses)
  • they can be optionally applied to a specific type of material (check the documentation for the supported types). If no type is specified, a material name will need to be explicitly set in the contract, through selectors.
  • they have a policy script that it’s evaluated against the material (in this case a CycloneDX SBOM report). Currently, only Rego language is supported.
  • there can be multiple scripts, each associated with a different material type.
Policy scripts could also be specified in a detached form:
...
spec:
  policies:
  - kind: SBOM_CYCLONEDX_JSON
    path: my-script.rego

Supporting multiple material types

Policies can accept multiple material types. This is specially useful when a material can be specified in multiple format types, but from the user perspective, we still want to maintain one single policy. For example, this policy would check for vulnerabilities in SARIF, CycloneDX and CSAF formats:
...
apiVersion: workflowcontract.chainloop.dev/v1
kind: Policy
metadata:
  name: cve-policy
spec:
  policies:
    - kind: SBOM_CYCLONEDX_JSON
      path: cves-cyclonedx.rego
    - kind: CSAF_SECURITY_ADVISORY
      path: cves-csaf-sa.rego
    - kind: SARIF
      path: cves-sarif.rego
In these cases, Chainloop will choose the right script to execute, but externally it would be seen as a single policy. If more than one path is executed (because they might have the same kind), the evaluation result will be the sum of all evaluations.

Policy arguments

Policies may accept arguments to customize its behavior. If defined, the inputs section, will be used by Chainloop to know with inputs arguments are supported by the policy For example, this policy matches a “quality” score against a “threshold” argument:
# quality.yaml
apiVersion: workflowcontract.chainloop.dev/v1
kind: Policy
metadata:
  name: quality
  description: Checks for components without licenses
  annotations:
    category: sbom
spec:
  inputs: #(1)
    - name: threshold
      description: quality threshold
      required: true
  policies:
    - kind: SBOM_CYCLONEDX_JSON
      embedded: |
        package main

        import rego.v1

        result := {
          "skipped": false,
          "violations": violations,
        }

        default threshold := 5
        threshold := to_number(input.args.threshold) # (2)

        violations contains msg if {
          input.score < threshold
          msg := sprintf("quality threshold not met %d < %d", [input.score, threshold])
        }
  • (1) the input section tells Chainloop which parameters should be expected. If missing, the argument will be ignored (an no value will be passed to the policy)
  • (2) input parametes are available in the input.args rego input field.
The above example can be instantiated with a custom threshold parameter, by adding a with property in the policy attachment in the contract:
policies:
  materials:
    - ref: file://quality.yaml
      with:
        threshold: 6 (1)
(1) This is interpreted as a string, that’s why we need to add to_number in the policy script

Writing Rego Policy Logic

Rego language, from Open Policy Agent initiative, has become the de-facto standard for writing software supply chain policies. It’s a rule-oriented language, suitable for non-programmers that want to communicate and enforce business and security requirements in their pipelines.

Using Chainloop Template

Chainloop expects the rego scripts to expose a predefined set of rules so a good starting point is to use the following template:
package main

import rego.v1

# (1)
################################
# Common section do NOT change #
################################

# (2)
result := {
	"skipped": skipped,
	"violations": violations,
	"skip_reason": skip_reason,
}

default skip_reason := ""

skip_reason := m if {
	not valid_input
	m := "invalid input"
}

default skipped := true

skipped := false if valid_input

########################################
# EO Common section, custom code below #
########################################

# Validates if the input is valid and can be understood by this policy (3)
valid_input if {
    # insert code here
}

# If the input is valid, check for any policy violation here (4)
violations contains msg if {
    valid_input
    # insert code here
}
In the above template we can see there is a common section (1). Chainloop will look for the main rule result, if present. Older versions of Chainloop will only check for a violations rule. result object has essentially three fields:
  • skipped: whether the policy evaluation was skipped. This property would be set to true when the input, for whatever reason, cannot be evaluated (unexpected format, etc.). This property is useful to avoid false positives.
  • skip_reason: if the policy evaluation was skipped, this property will contain some informative explanation of why this policy wasn’t evaluated.
  • violations: will hold the list of policy violations for a given input. Note that in this case, skipped will be set false, denoting that the input was evaluated against the policy, and it didn’t pass.
Note that there is no need to modify the common section. Policy developers will only need to fill in the valid_input and violations rules:
  • valid_input would fail if some preconditions were not met, like the input format.

Writing the policy logic

Let’s say we want to write a policy that checks our SBOM in CycloneDX format to match a specific version. A valid_input rule would look like this:
# It's a valid input if format is CycloneDX and has specVersion field that we can check later
valid_input if {
    input.bomFormat == "CycloneDX"
    input.specVersion
}
violations rule would return the list of policy violations, given that valid_input evaluates to true. If we wanted the CycloneDX report to be version 1.5:
violations contains msg if {
    valid_input
    input.specVersion != "1.5"
    msg := sprintf("wrong CycloneDX version. Expected 1.5, but it was %s", [input.specVersion])
}
When evaluated against an attestation, The policy will generate an output similar to this:
{
    "result": {
        "skipped": false,
        "violations": [
            "wrong CycloneDX version. Expected 1.5, but it was 1.4"
        ]
    }
}
Make sure you test your policies in the Rego Playground.

Attaching it to the policy YAML spec

Once we have our Rego logic for our policy, we can create a Chainloop policy like this:
# cyclonedx-version.yaml
apiVersion: workflowcontract.chainloop.dev/v1
kind: Policy
metadata:
  name: cyclonedx-version
spec:
  policies:
    - kind: SBOM_CYCLONEDX_JSON
      name: cyclonedx-version.rego

Contract Attachment

Once your policy is developed and tested, you can attach it to a contract:
schemaVersion: v1
policies:
  materials:
    - ref: file://cyclonedx-version.yaml
Check our policies reference for more information on how to attach policies to contracts.

Configuring Policy Inputs

As we can see in the above examples, Rego policies will receive and inputs variable with all the payload to be evaluated. Chainloop will inject the evidence payload into that variable, for example a CycloneDX JSON document. This way, input.specVersion will denote the version of the CycloneDX document. Additionally, Chainloop will inject the following fields:
  • input.args: the list of arguments passed to the policy from the contract or the policy group. Each argument becomes a field in the args input:
      // input.args
      {
        "severity": "MEDIUM",
        "foo": "bar",
        "licenses": ["AGPL-1.0-only", "AGPL-1.0-or-later"]
      }
    
    All arguments are passed as String type. So if you expect a numeric value you’ll need to convert it with the to_number Rego builtin. Also, for convenience, comma-separated values are parsed and injected as arrays, as in the above example.
  • input.chainloop_metadata: This is an In-toto descriptor JSON representation of the evidence, which Chainloop generates and stores in the attestation. Developers can create policies that check for specific fields in this payload. A typical chainloop_metadata field will look like this:
    {
      "chainloop_metadata" : {
        "name" : "registry-1.docker.io/bitnamicharts/chainloop",
        "digest" : {
          "sha256" : "2af5745f843476bd781663eea84d3bd6bcd7a9cb9fcd54ce10cf48142bed2151"
        },
        "annotations" : {
          "chainloop.material.image.tag" : "2.0.21",
          "chainloop.material.name" : "material-1731339792439159000",
          "chainloop.material.signature" : "eyJzY2hlbWFWZXJzaW9uIjoyLCJtZWRpYVR5cGUiOiJhcHBsaWNhdGlvbi92bmQub2NpLmltYWdlLm1hbmlmZXN0LnYxK2pzb24iLCJjb25maWciOnsibWVkaWFUeXBlIjoiYXBwbGljYXRpb24vdm5kLmNuY2Yubm90YXJ5LnNpZ25hdHVyZSIsImRpZ2VzdCI6InNoYTI1Njo0NDEzNmZhMzU1YjM2NzhhMTE0NmFkMTZmN2U4NjQ5ZTk0ZmI0ZmMyMWZlNzdlODMxMGMwNjBmNjFjYWFmZjhhIiwic2l6ZSI6Mn0sImxheWVycyI6W3sibWVkaWFUeXBlIjoiYXBwbGljYXRpb24vam9zZStqc29uIiwiZGlnZXN0Ijoic2hhMjU2OmMwYWFlMzc5ODE4Zjk2NDQ5Nzk1OGMzNGM4NWZhYzU0MWFiZjgyZDlhMTUxZDBlZDg2MmM4ODE0OWE3ZjQxNmUiLCJzaXplIjo3OTQ3fV0sInN1YmplY3QiOnsibWVkaWFUeXBlIjoiYXBwbGljYXRpb24vdm5kLm9jaS5pbWFnZS5tYW5pZmVzdC52MStqc29uIiwiZGlnZXN0Ijoic2hhMjU2OjJhZjU3NDVmODQzNDc2YmQ3ODE2NjNlZWE4NGQzYmQ2YmNkN2E5Y2I5ZmNkNTRjZTEwY2Y0ODE0MmJlZDIxNTEiLCJzaXplIjo0ODV9LCJhbm5vdGF0aW9ucyI6eyJpby5jbmNmLm5vdGFyeS54NTA5Y2hhaW4udGh1bWJwcmludCNTMjU2IjoiW1wiODM0NDQ2Y2E1ZDk5Mzg2NTYxYjc0OWQ3MjdlNTI1ODU3ZjU3ZDlhNjY3NDRhZjYzZmMxY2I3YzcyNzYyZTA4ZlwiLFwiNzBhMzlkMWQ1Y2Y4ZDVhMWVkNzBiYmM1YWM1NjA5M2JhZDEzYzUyOTdiMzdkOTZiNTFkZDkxZThjYzZiM2IxNlwiLFwiYzQ0MWYzMzBiMzNhYzI2ODc0NWUzYzFkZTcwZjRiYTRjNzY1OTEzNGUwODQyNWY0N2JjOTQ2ZmZiNDgxMjc2NlwiXSIsIm9yZy5vcGVuY29udGFpbmVycy5pbWFnZS5jcmVhdGVkIjoiMjAyNC0xMS0wOFQxMTo0MzoxNVoifX0=",
          "chainloop.material.signature.digest" : "sha256:2e3aded29ba4266d4c682694c5b45585fa0a3d92bd1ea9bfd52448528c7eb6f5",
          "chainloop.material.signature.provider" : "notary",
          "chainloop.material.type" : "HELM_CHART"
        }
      }
    }
    
    Besides the basic information (name, digest) of the evidence, the annotations field will contain some useful metadata gathered by Chainloop during the attestation process. The example above corresponds to an OCI HELM_CHART evidence, for which Chainloop is able to detect the notary signature. You can write, for example, a policy that validates that your assets are properly signed, like this:
    violations contains msg if {
        not input.chainloop_metadata.annotations["chainloop.material.signature"]
        msg := sprintf("Signature not found for material '%s'", [input.chainloop_metadata.name])
    }
    

Using Custom Evidence

In some cases, you might want to run a policy against a custom piece of evidence that doesn’t match any of the built-in material types.

Structure Guidelines

We recommend that custom evidence has the following properties:
  • It’s in JSON format, since our policy engine only supports JSON.
  • The document has an identifier, and clear separation between that and it’s actual data, for example
Instead of this:
{
  "foo": "bar",
}
Have this:
{
  "id": "my-custom-evidence",
  "data": {
    "foo": "bar",
  }
}
This will allow you to write policies that can identify the provided evidence, skip it, etc. For example, we can now write a policy that skips the evaluation if it’s not this specific piece of evidence:
# From the rego template
valid_input if {
    input.id == "my-custom-evidence"
}

Troubleshooting

Common Issues

  • Rego type conflicts: Remove default violations := [] when using violations contains msg if rules
  • Missing material kind: Always specify --kind parameter in eval command
  • Invalid JSON: Ensure your material files are valid JSON format
  • Time calculations: Use nanoseconds for time comparisons in Rego policies

Debugging Tips

  • Use chainloop policy develop lint --format to fix formatting issues
  • Test with minimal examples first, then add complexity
  • Check the Rego Playground for syntax validation
  • Use the CLI development workflow: init → lint → eval → iterate

Performance Best Practices

  • Minimize iterations: Use some and contains efficiently
  • Early exits: Place most restrictive conditions first in rules
  • Avoid deep nesting: Flatten complex object traversals where possible
  • Cache calculations: Store expensive computations in variables

Policy Engine Constraints

To ensure the policy engine work as pure and as fast as possible, we have deactivated some of the OPA built-in functions. The following functions are not allowed in the policy scripts:
  • opa.runtime
  • rego.parse_module
  • trace
Also http.send has been isolated so only requests to the following domains are allowed:
  • chainloop.dev
  • cisa.gov
This prevents unexpected behavior and potential remote exploits, particularly since these policies are evaluated client-side.