Metadata-Version: 2.4
Name: compliance-to-policy
Version: 1.0.0
Summary: Tools to bridge Compliance and Policy
Author-email: Takumi Yanagawa <yana1205dev@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/oscal-compass/compliance-to-policy
Project-URL: Issues, https://github.com/oscal-compass/compliance-to-policy/issues
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: compliance-trestle~=3.3
Requires-Dist: jinja2>=3.1.6
Requires-Dist: PyGithub==1.58.0
Requires-Dist: jq==1.6.0
Requires-Dist: pluggy
Provides-Extra: dev
Requires-Dist: build>=1.0.3; extra == "dev"
Requires-Dist: pyclean; extra == "dev"
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pre-commit>=2.4.0; extra == "dev"
Requires-Dist: pep8-naming; extra == "dev"
Requires-Dist: toml-cli; extra == "dev"
Requires-Dist: types-PyYAML; extra == "dev"
Requires-Dist: types-setuptools; extra == "dev"
Requires-Dist: mkdocs; extra == "dev"
Requires-Dist: mkdocs-redirects; extra == "dev"
Requires-Dist: mkdocstrings-python; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: isort; extra == "dev"
Requires-Dist: pylint; extra == "dev"
Dynamic: license-file

# <img alt="Logo" width="50px" src="https://raw.githubusercontent.com/oscal-compass/compliance-to-policy/main/assets/compliance-to-policy-800x800.PNG" style="vertical-align: middle;" /> Compliance-to-Policy (also known as `C2P`)

Compliance-to-Policy (C2P) is designed to bridge Compliance as Code such as Open Security Controls Assessment Language (OSCAL) and Policy as Code used by Policy Validation Point (PVP). It generates policies in native format of PVP from OSCAL Component Definitions, and turns the native assessment results of PVP into OSCAL Assessment Results and a control-level compliance posture. C2P can be used both as a command-line tool and a Python library, making it easy and flexible to integrate into your Continuous Compliance pipelines, such as GitHub Actions, Tekton Pipelines, or Agile Authoring Pipelines. Custom plugins can be implemented with a small amount of Python code.

**C2P++ is C2P with an agent skill added to its policy generation**, automating the production of the engine-specific policy templates. A component definition names the checks that verify each rule. C2P produces the target engine's native policy from the template that corresponds to each check. Until now those templates had to be prepared in advance. A check added to a component definition produced no policy until someone had written the template for it. In C2P++ an agent skill, [`skills/policy-generation`](skills/policy-generation/), produces that engine-specific template.

![C2P Overview](/assets/architecture.png)

1. Compliance-to-Policy (C2P) is running in GitOps Pipeline, Kubernetes controller, or Python/Go environment
1. C2P receives Compliance as Code, for example OSCAL Component Definition that represents mapping between controls and policies (policy names/ids)
1. C2P generates policies through plugin for each policy engine
    - The plugin is responsible for implementing a function that takes policy names/ids and returns policies
1. Policies are delivered to policy engines by GitOps sync, the subsequence pipeline task, Kubernetes controller, or a deployment automation program 
1. Results are collected from policy engines by a scheduled task or Kubernetes controller
1. C2P aggregates the results of policy engines by controls through plugin for each policy engine
    - The plugin is responsible for implementing a function that takes the results of the policy engine and returns verdicts (pass/fail/error), reason, and/or resource name for each respective policy by its names/IDs.
1. C2P produces Compliance Assessment Results, for example OSCAL Assessment Results that represents the assessment results of each control 

That chain run for real, step by step, is the
[end-to-end walkthrough on Kubernetes](docs/end-to-end/README.md): one NIST SP 800-53 control to a
compliance posture against a live cluster, with the captured output of every command. There is a
[recording of the demo](https://www.youtube.com/watch?v=pk3EsgA4EBQ) as well.

## Goals
Provide seamless integration with compliance frameworks and existing policy engines, and enable to use heterogeneous policy engines in compliance check operation
- Flexibility in choise of policy engines and compliance frameworks
    - Provide plugins to cover various policy engines including proprietary/open source policy validation/enforcement engines, or in-house policy validation/enforcement program
    - Cover various compliance frameworks not only OSCAL but also other GRC frameworks and Cloud Security Posture Management services
- Community-driven plugin extension
    - Provide an efficient plugin interface and development method

## Supported Compliance Frameworks
- [Open Security Controls Assessment Language (OSCAL)](https://pages.nist.gov/OSCAL/documentation/)
    - OSCAL standard provides a compliance framework and the corresponding set of key compliance artifacts expressed in machine processable formats enabling all compliance documents to be treated as code and therefore processed and managed in the same manner.

## Supported Policy Engines
- [Kyverno](https://kyverno.io/) (for Kubernetes resources)
    - Kyverno is a policy engine designed for Kubernetes, where policies are managed as Kubernetes resources. Kyverno policies can validate, mutate, generate, and clean up Kubernetes resources.
    - Two policy languages are supported, by separate plugins. `kyverno.io/v1 ClusterPolicy` is the original DSL, deprecated in Kyverno 1.19 and removed in 1.20; `policies.kyverno.io/v1` is its CEL-based replacement. Both are generated from the same component definition, which is the argument for authoring the control rather than the policy
- [ValidatingAdmissionPolicy](https://kubernetes.io/docs/reference/access-authn-authz/validating-admission-policy/) (for Kubernetes resources)
    - Upstream Kubernetes, CEL evaluated inside the API server, no controller to install. It decides at admission time only: it runs no background scan over objects that already exist and publishes no report, so C2P obtains its verdicts by replaying a workload as a server-side dry run. What CEL in the API server cannot do — fetch from a registry, read another object — is a limit on which checks an estate can express with it, which is visible in the posture as coverage rather than hidden
- [Open Cluster Management Policy Framework](https://open-cluster-management.io/) (for Kubernetes resources)
    - OCM is a multi-cluster management platform that provides governance of Kubernetes policies. [Its policy framework](https://open-cluster-management.io/concepts/policy/) allows for the validation and enforcement of policies across multiple clusters.
- [Auditree](https://auditree.github.io/) (for any target, especially well-suited for resources of PaaS/SaaS/IaaS available through REST API.)
    - Auditree is a GitOps based workflow automation that enables the collection and verification of evidence, building a long-term store of evidence in an git "evidence locker." Evidence is gathered by code scripts called "fetchers" and verified by "checks."

Roadmap:
- [OPA/Gatekeeper](https://github.com/open-policy-agent/gatekeeper) (for Kubernetes resources)
- [Ansible](https://www.ansible.com/) (for any target, especially for VMs and OnPremise hosts)

## C2P in Go language
The Go verion is available in the [go directory](/go/README.md). 

## Install 

#### From git repo
```
pip install git+https://github.com/oscal-compass/compliance-to-policy.git
``` 
You may be asked passphrase of SSH key to access to the git repo.

#### From source
1. Clone the repository
    ```
    git clone https://github.com/oscal-compass/compliance-to-policy.git
    ```
1. Go to `compliance-to-policy`
    ```
    cd compliance-to-policy
    ```
1. Install
    ```
    make install
    ```

## Quick demo

1. Generate Kyverno Policy (C2P Compliance to Policy)
    ```
    python samples_public/kyverno/compliance_to_policy.py -o /tmp/deliverable-policy
    ```
    E.g.
    ```
    $ python samples_public/kyverno/compliance_to_policy.py -o /tmp/deliverable-policy

    tree /tmp/deliverable-policy
    disallow-capabilities
    - disallow-capabilities.yaml
    allowed-base-images
    - 02-setup-cm.yaml
    - allowed-base-images.yaml
    ```
1. Deploy the generated policies
    ```
    kubectl apply -R -f /tmp/deliverable-policy
    ```
    E.g.
    ```
    $ kubectl apply -R -f /tmp/deliverable-policy
    namespace/platform created
    configmap/baseimages created
    Warning: Validation failure actions enforce/audit are deprecated, use Enforce/Audit instead.
    clusterpolicy.kyverno.io/allowed-base-images created
    clusterpolicy.kyverno.io/disallow-capabilities created
    ```
1. Check policy results
    ```
    $ kubectl get policyreport,clusterpolicyreport -A
    NAMESPACE            NAME                                                     PASS   FAIL   WARN   ERROR   SKIP   AGE
    kube-system          policyreport.wgpolicyk8s.io/cpol-allowed-base-images     0      12     0      0       0      19s
    kube-system          policyreport.wgpolicyk8s.io/cpol-disallow-capabilities   9      2      0      0       0      19s
    kyverno              policyreport.wgpolicyk8s.io/cpol-allowed-base-images     0      18     0      0       0      9s
    kyverno              policyreport.wgpolicyk8s.io/cpol-disallow-capabilities   18     0      0      0       0      9s
    local-path-storage   policyreport.wgpolicyk8s.io/cpol-allowed-base-images     0      3      0      0       0      16s
    local-path-storage   policyreport.wgpolicyk8s.io/cpol-disallow-capabilities   3      0      0      0       0      16s
    ```
1. Collect policy/cluster policy reports as PVP Raw results
    ```
    kubectl get policyreport -A -o yaml > /tmp/policyreports.wgpolicyk8s.io.yaml
    kubectl get clusterpolicyreport -o yaml > /tmp/clusterpolicyreports.wgpolicyk8s.io.yaml
    ```
1. Generate Assessment Result (C2P Result to Compliance)
    ```
    python samples_public/kyverno/result_to_compliance.py \
     -polr /tmp/policyreports.wgpolicyk8s.io.yaml \
     -cpolr /tmp/clusterpolicyreports.wgpolicyk8s.io.yaml \
     > /tmp/assessment_results.json
    ```
1. OSCAL Assessment Results is not human readable format. You can see the merged report in markdown by a quick viewer.
    ```
    c2p tools viewer -ar /tmp/assessment_results.json -cdef ./plugins_public/tests/data/kyverno/component-definition.json -o /tmp/assessment_results.md
    ```
    e.g. [kyverno.result.md](/docs/public/kyverno.result.md)
1. (Optional) Render a control-level compliance posture instead. Unlike the viewer, the posture
   is a document in its own right -- `json` is the [`c2p-posture/v1`](docs/public/posture.md)
   model, and `md` and `html` are views over it -- so it can be diffed, served and re-rendered.
    ```
    c2p tools result2posture -ar /tmp/assessment_results.json -cdef ./plugins_public/tests/data/kyverno/component-definition.json -f html -o /tmp/posture.html
    # and as the c2p-posture/v1 document, which is what posture-compare reads
    c2p tools result2posture -ar /tmp/assessment_results.json -cdef ./plugins_public/tests/data/kyverno/component-definition.json -f json -o /tmp/posture.json
    ```
    The posture is accountable for every check the component definition declares, so a check
    no engine reported is a `not-assessed` row rather than an omission, and each control carries
    `coverage` alongside its state. Repeat `-ar` to combine several Assessment Results into one
    posture.
1. (Optional) Compare two postures control by control, to see which controls stop being
   assessed under a narrower set of engines. Both inputs are `-f json` postures, each produced
   from its own collection -- below, a second one collected with `vap-cel` alone.
    ```
    c2p tools posture-compare -b /tmp/posture.json -p /tmp/posture-vap-only.json \
      --baseline-label 'every engine' --posture-label 'vap-cel only' \
      --condition 'when only ValidatingAdmissionPolicy is available'
    ```

## Usage of C2P Plugins
- [Kyverno](docs/public/kyverno.md)
- [Kubernetes policy engines — Kyverno DSL, Kyverno CEL and ValidatingAdmissionPolicy](docs/public/kubernetes.md)
- [Open Cluster Management Governance Policy Framework](docs/public/ocm.md)
- [Auditree](docs/public/auditree.md)
- [Heterogeneous PVPs (mixing Kyverno, OCM Policy, and Auditree)](docs/public/heterogeneous.md)
- [The compliance posture](docs/public/posture.md) — `c2p tools result2posture` and `posture-compare`, and the `c2p-posture/v1` document

## Usage of C2P as a library

#### Generate PVP Policies from Compliance
1. Create `C2PConfig` object to supply compliance requirements and some metadata (See also [kyverno/compliance_to_policy.py](/samples_public/kyverno/compliance_to_policy.py) for a real example)
    ```python
    c2p_config = C2PConfig()
    c2p_config.compliance = ComplianceOscal()
    c2p_config.compliance.component_definition = 'plugins_public/tests/data/kyverno/component-definition.json'
    c2p_config.pvp_name = 'Kyverno'
    c2p_config.result_title = 'Kyverno Assessment Results'
    c2p_config.result_description = 'OSCAL Assessment Results from Kyverno'
    ```
1. Select a plugin for supported PVPs (`PluginKyverno`, `PluginOCM`) and create `PluginConfig` object to supply plugin specific properties
    ```python
    from plugins_public.plugins.kyverno import PluginConfigKyverno, PluginKyverno
    policy_template_dir = 'plugins_public/tests/data/kyverno/policy-resources'
    config = PluginConfigKyverno(policy_template_dir=policy_template_dir, deliverable_policy_dir='/tmp/deliverable-policies')
    ```
1. Create `C2P` and `Plugin`
    ```python
    c2p = C2P(c2p_config)
    plugin = PluginKyverno(config)
    ```
1. Get policy from `c2p` and generate PVP policy by `generate_pvp_policy()`
    ```python
    policy = c2p.get_policy()
    plugin.generate_pvp_policy(policy)
    ```
1. The deliverable policies are output in '/tmp/deliverable-policies'
    ```
    $ tree /tmp/deliverable-policy
    /tmp/deliverable-policy
    ├── allowed-base-images
    │   ├── 02-setup-cm.yaml
    │   └── allowed-base-images.yaml
    └── disallow-capabilities
        └── disallow-capabilities.yaml
    ```
##### Rule parameters

`get_policy()` resolves each parameter a rule declares, in this order:

1. the value in the component definition's `set-parameters`
1. the `Parameter_Value_Default` prop
1. the `Parameter_Value_Alternatives` prop

`set-parameters` wins because it is the resolved value: trestle's `csv-to-oscal-cd` writes
parameter values there and leaves only the id in the props, so reading the props alone yields
parameters with nothing in them.

Parameters are read from **every** component that is not a validation component, and a rule can
declare several by numbering the prop columns — `Parameter_Id_2`, `Parameter_Value_Default_2`,
and so on.

> **Behaviour change — check your generated output after upgrading.** Four things differ from
> earlier releases, and a component definition that generated correctly before can generate
> different policy now:
>
> | | Before | Now |
> |---|---|---|
> | Where the value comes from | `Parameter_Value_Alternatives` only | `set-parameters`, then `Parameter_Value_Default`, then `Parameter_Value_Alternatives` |
> | Which components are read | only the **last** non-validation component — the loop overwrote its accumulator each time round, so a component definition with several service components silently used one of them | every non-validation component |
> | Numbered columns | only the unnumbered `Parameter_Id` | `Parameter_Id`, `Parameter_Id_2`, … |
> | A parameter declared twice | — | the later value wins, silently, in every plugin that turns the list into a `{id: value}` mapping — the three Kubernetes plugins, `kyverno` and `ocm`. `auditree` iterates the list instead and sees both |

**A parameter with no value anywhere renders as an empty string.** It is logged as a warning and
substituted as `''`. `StrictUndefined` does not catch it — the variable is defined, it is empty —
so a check written as `image.startsWith({{ params.approved_registry | quote }})` becomes
`image.startsWith("")` and asserts nothing. Read the generated policy, and treat a parameter
warning in the log as a generation failure until the value is supplied.

#### Generate Compliance Assessment Results from PVP native results
1. Create `C2PConfig` object to supply compliance requirements and some metadata (See also [kyverno/compliance_to_policy.py](/samples_public/kyverno/result_to_compliance.py) for a real example)
    ```python
    c2p_config = C2PConfig()
    c2p_config.compliance = ComplianceOscal()
    c2p_config.compliance.component_definition = 'plugins_public/tests/data/kyverno/component-definition.json'
    c2p_config.pvp_name = 'Kyverno'
    c2p_config.result_title = 'Kyverno Assessment Results'
    c2p_config.result_description = 'OSCAL Assessment Results from Kyverno'
    ```
1. Select a plugin for supported PVPs (`PluginKyverno`, `PluginOCM`) and create `PluginConfig` object to supply plugin specific properties
    ```python
    from plugins_public.plugins.kyverno import PluginConfigKyverno, PluginKyverno
    config = PluginConfigKyverno()
    ```
1. Create `C2P` and `Plugin`
    ```python
    c2p = C2P(c2p_config)
    plugin = PluginKyverno(config)
    ```
1. Load PVP native results
    ```python
    policy_report_file = 'plugins_public/tests/data/kyverno/policyreports.wgpolicyk8s.io.yaml'
    cluster_policy_report_file = 'plugins_public/tests/data/kyverno/clusterpolicyreports.wgpolicyk8s.io.yaml'
    policy_report = yaml.safe_load(pathlib.Path(policy_report_file).open('r'))
    cluster_policy = yaml.safe_load(pathlib.Path(cluster_policy_report_file).open('r'))
    pvp_raw_result = RawResult(data=policy_report['items'] + cluster_policy['items'])
    ```
1. Call `generate_pvp_result()` of the plugin to get a formatted PVP result
    ```python
    pvp_result = PluginKyverno().generate_pvp_result(pvp_raw_result)
    ```
1. Create `C2P` and call `result_to_oscal()` to obtain Compliance Assessment Results
    ```python
    c2p.set_pvp_result(pvp_result)
    oscal_assessment_results = c2p.result_to_oscal()
    print(oscal_assessment_results.oscal_serialize_json(pretty=True))
    ```
    A cluster typically runs more than one policy engine, and each is assessed on its own.
    Call `add_pvp_result()` once per engine instead of `set_pvp_result()`, and
    `result_to_oscal()` aggregates them into **one** Assessment Results document:
    ```python
    for pvp_result in [kyverno_dsl_result, kyverno_cel_result, vap_result]:
        c2p.add_pvp_result(pvp_result)
    oscal_assessment_results = c2p.result_to_oscal()
    ```
    One document per engine would make the artifact an accident of how the assessment was
    organised rather than a statement about the system, and anything reading it would have to
    know to look for several files.

    Where the engines are collected by separate pipelines and aggregating in one process is not
    possible, each run produces its own Assessment Results and `c2p tools result2posture` takes
    a repeated `-ar` to bring them back together.

    Every observation carries an `assessment-check-id` prop as well as `assessment-rule-id`.
    One rule is routinely implemented by several PVPs, so a rule id alone cannot say which
    engine reported an observation, and a reader of the Assessment Results -- including
    `c2p tools result2posture` -- has no way to attribute it.
1. (Optional) you may reformat OSCAL Assessment Results in markdown style.
    ```
    c2p tools viewer -ar <OSCAL Assessment Results (json)> -cdef ./plugins_public/tests/data/ocm/component-definition.json -o /tmp/assessment_results.md
    ```

## How to support your own PVP in C2P

You can create a custom plugin by overriding `PluginSpec` and `PluginConfig`. 
`PluginSpec` has two interfaces `generate_pvp_policy` and `generate_pvp_result`. 
C2P framework will instantiate `PluginSpec` with `PluginConfig`.

A plugin whose generated artifact is one document per check renders it from a template, and
writing those templates is the part that needs engine knowledge rather than c2p knowledge. The
agent skill in [`skills/policy-generation/`](skills/policy-generation/SKILL.md) covers it: the
template contract, the three Kubernetes engines and the shape each one wants, what an engine
cannot express (and why declaring no check is the right answer when it cannot), and how to
verify generated policy byte for byte.

#### PluginConfig
1. Extend PluginConfig with custom fields as the plugin needs 
    ```python
    from c2p.framework.plugin_spec import PluginSpec
    class YourPluginConfig(PluginConfig):
        custom_field: str = Field(..., title='Custom field for your plugin')
    ```
1. Extend PluginSpec and define __init__ with YourPluginConfig
    ```python
    class YourPlugin(PluginSpec):
        def __init__(self, config: Optional[YourPluginConfig] = None) -> None:
            super().__init__()
            self.config = config # work on config
    ```

#### PluginSpec.generate_pvp_policy
1. `generate_pvp_policy()` in `PluginSpec` accepts one argument `policy: c2p.framework.models.Policy`.
    The object has two fields (`rule_sets` and `parameters`). `rule_sets` and `parameters` are a list of Rule_Id, Check_Id, Parameter_Id, Parameter_Value, etc of the components handled by your PVP in OSCAL Component Definition.
1. Implement the logic to generate PVP policy from provided rule_sets and parameters. 
    ```python
        def generate_pvp_policy(self, policy: Policy):
            rule_sets: List[RuleSet] = policy.rule_sets
            parameters: List[Parameter] = policy.parameters
            # generate deliverable policy from rule_sets and parameters
    ```

#### PluginSpec.generate_pvp_result
1. `generate_pvp_result()` is expected to generate the summarized raw results of your PVP per unit in `PVPResult` format. This unit must be associated with a unique id called Check_Id. For example of [PluginKyverno](/plugins_public/plugins/kyverno.py), Policy Reports is the raw results and are summarized by policy name.
    ```python
    def generate_pvp_result(self, raw_result: RawResult) -> PVPResult:
        pvp_result: PVPResult = PVPResult()
        observations: List[ObservationByCheck] = []

        polrs = list(
            filter(
                lambda x: x['apiVersion'] == 'wgpolicyk8s.io/v1alpha2' and x['kind'] == 'PolicyReport', raw_result.data
            )
        )
        cpolrs = list(
            filter(
                lambda x: x['apiVersion'] == 'wgpolicyk8s.io/v1alpha2' and x['kind'] == 'ClusterPolicyReport',
                raw_result.data,
            )
        )

        results = []
        for polr in polrs:
            for result in polr['results']:
                results.append(result)
        for cpolr in cpolrs:
            for result in cpolr['results']:
                results.append(result)

        policy_names = list(map(lambda x: x['policy'], results))  # policy_name is used as check_id
        policy_names = set(policy_names)

        for policy_name in policy_names:
            observation = ObservationByCheck(check_id=policy_name, methods=['AUTOMATED'], collected=get_datetime())
    ```

1. The input argument `raw_result` has `data` field that is serialized raw results as dict. You can define your preferable format of the data. C2P Framework will pass PVP native results to plugin with this format.

#### Publish plugin
1. Put the plugin in plugin directory [/plugins_public/plugins](/plugins_public/plugins) or Python module path when you use C2P.

## Development

### Developing
1. Install Python
    ```
    $ python --version
    Python 3.10.12
    ```
1. Setup venv
    ```
    python -m venv .venv
    ```
1. Install dependant modules
    ```
    make install-dev
    ```
1. Enable detect-secret
    ```
    pre-commit install
    ```

### Test
```
$ make test       

plugins_public/tests/plugins/test_kyverno.py::test_kyverno_pvp_result_to_compliance PASSED                                                                                                   [ 25%]
plugins_public/tests/plugins/test_kyverno.py::test_kyverno_compliance_to_policy PASSED                                                                                                       [ 50%]
plugins_public/tests/plugins/test_ocm.py::test_ocm_pvp_result_to_compliance PASSED                                                                                                           [ 75%]
plugins_public/tests/plugins/test_ocm.py::test_ocm_compliance_to_policy 
------------------------------------------------------------------------------------------ live log call -------------------------------------------------------------------------------------------
2024-04-25 05:31:48 [    INFO] The deliverable policy directory '/var/folders/yx/1mv5rdh53xd93bphsc459ht00000gn/T/tmpxtvpcrpr/deliverable-policy' is not found. Creating... (ocm.py:191)
PASSED                                                                                                                                                                                       [100%]

======================================================================================== 4 passed in 0.31s =========================================================================================

tests/c2p/framework/test_c2p.py::test_result_to_oscal PASSED                                                                                                                                 [ 33%]
tests/c2p/test_cli.py::test_run PASSED                                                                                                                                                       [ 66%]
tests/c2p/test_cli.py::test_version PASSED                                                                                                                                                   [100%]

======================================================================================== 3 passed in 0.26s =========================================================================================
```

### Cleanup caches
```
make clean
```

## License & Authors

If you would like to see the detailed LICENSE click [here](LICENSE).
Consult [contributors](https://github.com/oscal-compass/compliance-to-policy/graphs/contributors) for a list of authors and [maintainers](MAINTAINERS.md) for the core team.

```text
# Copyright (c) 2024 The OSCAL Compass Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

```

______________________________________________________________________

We are a Cloud Native Computing Foundation sandbox project.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://www.cncf.io/wp-content/uploads/2022/07/cncf-white-logo.svg">
  <img src="https://www.cncf.io/wp-content/uploads/2022/07/cncf-color-bg.svg" width=300 />
</picture>

The Linux Foundation® (TLF) has registered trademarks and uses trademarks. For a list of TLF trademarks, see [Trademark Usage](https://www.linuxfoundation.org/legal/trademark-usage).

*OSCAL Compass is an independent open source project. It is not affiliated with, endorsed by, or sponsored by the National Institute of Standards and Technology (NIST) or any other government agency.*

*OSCAL Compass was originally contributed by IBM.*
