diff --git a/.github/workflows/create-and-publish-image.yml b/.github/disabled-workflows/create-and-publish-image.yml similarity index 100% rename from .github/workflows/create-and-publish-image.yml rename to .github/disabled-workflows/create-and-publish-image.yml diff --git a/.github/workflows/goreleaser-workflow.yml b/.github/disabled-workflows/goreleaser-workflow.yml similarity index 100% rename from .github/workflows/goreleaser-workflow.yml rename to .github/disabled-workflows/goreleaser-workflow.yml diff --git a/.gitignore b/.gitignore index a644dd5..5601e50 100644 --- a/.gitignore +++ b/.gitignore @@ -1,43 +1,164 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll +# C extensions *.so -*.dylib -bin -testbin/* -Dockerfile.cross -# Test binary, build with `go test -c` -*.test +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST -# Output of the go coverage tool, specifically when used with LiteIDE -*.out +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec -# Kubernetes Generated files - skip generated files, except for vendored files +# Installer logs +pip-log.txt +pip-delete-this-directory.txt -!vendor/**/zz_generated.* +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ -# editor and IDE paraphernalia -.idea -*.swp -*.swo -*~ +# Translations +*.mo +*.pot +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal -# IDE -.vscode -.idea +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ -# Output of gorelease -dist +# Celery stuff +celerybeat-schedule +celerybeat.pid -# ignore output by test -/**/_test +# SageMath parsed files +*.sage.py -# -policy-collection -out -work -kubeconfig.* \ No newline at end of file +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# vscode +.vscode +config/**/*.local.* \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ec30804 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,21 @@ +# This is an example configuration to enable detect-secrets in the pre-commit hook. +# Add this file to the root folder of your repository. +# +# Read pre-commit hook framework https://pre-commit.com/ for more details about the structure of config yaml file and how git pre-commit would invoke each hook. +# +# This line indicates we will use the hook from ibm/detect-secrets to run scan during committing phase. +repos: + - repo: https://github.com/ibm/detect-secrets + # If you desire to use a specific version of detect-secrets, you can replace `master` with other git revisions such as branch, tag or commit sha. + # You are encouraged to use static refs such as tags, instead of branch name + # + # Running "pre-commit autoupdate" automatically updates rev to latest tag + rev: 0.13.1+ibm.61.dss + hooks: + - id: detect-secrets # pragma: whitelist secret + # Add options for detect-secrets-hook binary. You can run `detect-secrets-hook --help` to list out all possible options. + # You may also run `pre-commit run detect-secrets` to preview the scan result. + # when "--baseline" without "--use-all-plugins", pre-commit scan with just plugins in baseline file + # when "--baseline" with "--use-all-plugins", pre-commit scan with all available plugins + # add "--fail-on-unaudited" to fail pre-commit for unaudited potential secrets + args: [--baseline, .secrets.baseline, --use-all-plugins] diff --git a/.secrets.baseline b/.secrets.baseline new file mode 100644 index 0000000..7a572f5 --- /dev/null +++ b/.secrets.baseline @@ -0,0 +1,152 @@ +{ + "exclude": { + "files": "go/go.sum|^.secrets.baseline$", + "lines": null + }, + "generated_at": "2024-04-28T07:58:38Z", + "plugins_used": [ + { + "name": "AWSKeyDetector" + }, + { + "name": "ArtifactoryDetector" + }, + { + "name": "AzureStorageKeyDetector" + }, + { + "base64_limit": 4.5, + "name": "Base64HighEntropyString" + }, + { + "name": "BasicAuthDetector" + }, + { + "name": "BoxDetector" + }, + { + "name": "CloudantDetector" + }, + { + "ghe_instance": "github.ibm.com", + "name": "GheDetector" + }, + { + "name": "GitHubTokenDetector" + }, + { + "hex_limit": 3, + "name": "HexHighEntropyString" + }, + { + "name": "IbmCloudIamDetector" + }, + { + "name": "IbmCosHmacDetector" + }, + { + "name": "JwtTokenDetector" + }, + { + "keyword_exclude": null, + "name": "KeywordDetector" + }, + { + "name": "MailchimpDetector" + }, + { + "name": "NpmDetector" + }, + { + "name": "PrivateKeyDetector" + }, + { + "name": "SlackDetector" + }, + { + "name": "SoftlayerDetector" + }, + { + "name": "SquareOAuthDetector" + }, + { + "name": "StripeDetector" + }, + { + "name": "TwilioKeyDetector" + } + ], + "results": { + "README.md": [ + { + "hashed_secret": "845d87d073c35614bfe1fe7f7f3821ea0f175126", + "is_secret": false, + "is_verified": false, + "line_number": 279, + "type": "Base64 High Entropy String", + "verified_result": null + } + ], + "go/controllers/utils/gitrepo/gitrepo.go": [ + { + "hashed_secret": "3aa3f05a1cbf42942040995f7e6842769216bdbc", + "is_secret": false, + "is_verified": false, + "line_number": 104, + "type": "Secret Keyword", + "verified_result": null + } + ], + "go/controllers/utils/utils.go": [ + { + "hashed_secret": "49531b78f7258280352a3f4d6679d963f7cc430c", + "is_secret": false, + "is_verified": false, + "line_number": 308, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "746637d90e70b787088b90792a905d7e450dd379", + "is_secret": false, + "is_verified": false, + "line_number": 308, + "type": "Secret Keyword", + "verified_result": null + } + ], + "go/docs/ocm/README.md": [ + { + "hashed_secret": "21c50805b553b7a40e48394a5d77d442587ddee2", + "is_secret": false, + "is_verified": false, + "line_number": 141, + "type": "Secret Keyword", + "verified_result": null + } + ], + "go/pkg/gitutils.go": [ + { + "hashed_secret": "49531b78f7258280352a3f4d6679d963f7cc430c", + "is_secret": false, + "is_verified": false, + "line_number": 154, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "746637d90e70b787088b90792a905d7e450dd379", + "is_secret": false, + "is_verified": false, + "line_number": 154, + "type": "Secret Keyword", + "verified_result": null + } + ] + }, + "version": "0.13.1+ibm.61.dss", + "word_list": { + "file": null, + "hash": null + } +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..6f0e294 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Contributor Covenant Code of Conduct + +Following to [Code of Conduct of OSCAL COMPASS project](https://github.com/oscal-compass/compliance-trestle/blob/develop/CODE_OF_CONDUCT.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..1838ce0 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,186 @@ +## Contributing In General + +Our project welcomes external contributions. If you have an itch, please feel +free to scratch it. + +To contribute code or documentation, please submit a [pull request](https://github.com/oscal-compass/compliance-to-policy/pulls). + +A good way to familiarize yourself with the codebase and contribution process is +to look for and tackle low-hanging fruit in the [issue tracker](https://github.com/oscal-compass/compliance-to-policy/issues). +Before embarking on a more ambitious contribution, please quickly [get in touch](/MAINTAINERS.md) with us. + +**Note: We appreciate your effort, and want to avoid a situation where a contribution +requires extensive rework (by you or by us), sits in backlog for a long time, or +cannot be accepted at all!** + +We have also adopted [Contributor Covenant Code of Conduct](/CODE_OF_CONDUCT.md). + +### Proposing new features + +If you would like to implement a new feature, please [raise an issue](https://github.com/oscal-compass/compliance-to-policy/issues) +labelled `enhancement` before sending a pull request so the feature can be discussed. This is to avoid +you wasting your valuable time working on a feature that the project developers +are not interested in accepting into the code base. + +### Fixing bugs + +If you would like to fix a bug, please [raise an issue](https://github.com/oscal-compass/compliance-to-policy/issues) labelled `bug` before sending a +pull request so it can be tracked. + +### Merge approval + +The project maintainers use LGTM (Looks Good To Me) in comments on the code +review to indicate acceptance. A change requires LGTMs from one of the maintainers. + +For a list of the maintainers, see the [maintainers](/MAINTAINERS.md) page. + +### C2P merging and release workflow + +`C2P` is operating on a simple, yet opinionated, method for continuous integration. It's designed to give developers a coherent understanding of the objectives of other past developers. +The criteria for this are below. Trestle effectively uses a gitflow workflow with one modification: PR's merge into develop are squash merged as one commit. + +In trestle's CI environment this results in the following rules: + +1. All Commit's *MUST* be signed off with `git commit --signoff` irrespective of the author's affiliation. This ensures all code can be attributed. + 1. This is enforced by DCO bot and can be overrided by maintainers presuming at least one commit is signed-off. +1. All commits *SHOULD* use [conventional commits](https://www.conventionalcommits.org/en/v1.0.0-beta.2/) + 1. This is as github, when only one commit is in a PR, will use the native git commit message as the merge commit title. + 1. When only a single commit is provided the commit MUST be an conventional commit and will be checked the `Lint PR` aciton. +1. All PR's title's MUST be formed as an [convention commit](https://www.conventionalcommits.org/en/v1.0.0-beta.2/) + 1. This is checked by the `Lint PR` action +1. All PR's to `main` should close at least one issue by [linking the PR to an issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword). +1. C2P will release on demand. +1. Each feature/fix/chore (PR into develop) be represented by a single commit into develop / main with a coherent title (in the PR). + 1. The C2P preference for doing this is to use squash merge functionality when merging a PR into develop. +1. Developers *MUST* pass the required CI checks for each PR. +1. Developers are encouraged to use GitHub's automated merge process where possible to keep the number of active PR's low. + +## Typing, docstrings and documentation + +`C2P` has a goal of using [PEP 484](https://www.python.org/dev/peps/pep-0484/) type annotations where possible / practical. +The devops process does not _strictly_ enforce typing, however, the expectation is that type coverage is added for new +commits with a focus on quality over quantity (e.g. don't add `Any` everywhere just to meet coverage requirements). +Python typing of functions is an active work in progress. + +## Legal + +Each source file must include a license header for the Apache +Software License 2.0. Using the SPDX format is the simplest approach. +e.g. + +```text +# Copyright (c) 2020 IBM Corp. 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 have tried to make it as easy as possible to make contributions. This +applies to how we handle the legal aspects of contribution. We use the +same approach - the [Developer's Certificate of Origin 1.1 (DCO)](https://oscal-compass.github.io/compliance-trestle/contributing/DCO/) - that the Linux® Kernel [community](https://elinux.org/Developer_Certificate_Of_Origin) +uses to manage code contributions. + +We simply ask that when submitting a patch for review, the developer +must include a sign-off statement in the commit message. + +Here is an example Signed-off-by line, which indicates that the +submitter accepts the DCO: + +```text +Signed-off-by: John Doe +``` + +You can include this automatically when you commit a change to your +local git repository using the following command: + +```bash +git commit --signoff +``` + +Note that DCO signoff is enforced by [DCO bot](https://github.com/probot/dco). Missing DCO's will be required to be rebased +with a signed off commit before being accepted. + +## Setup - Developing `C2P` + +### Does `C2P` run correctly on my platform + +- Setup a venv for python in .venv directory in the repository root directory. +- Run `make install-dev` + - This will install all python dependencies. + - It will also checkout the submodules required for testing. +- Run `make test` + - This *should* run on all platforms. + +### Setting up `vscode` for python. + +- Use the following commands to setup python: + +```bash +python3 -m venv venv +. ./venv/bin/activate +make install-dev +``` + +- Install vscode plugin [Python extension for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-python.python) + +- Install vscode plugin [Formatter extension for Visual Studio Code using the Black formatter](https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter) + +- Configure vscode setting with the black-formatter enabled. The example setting.json is as follows: + ``` + { + "[python]": { + "diffEditor.ignoreTrimWhitespace": false, + "gitlens.codeLens.symbolScopes": [ + "!Module" + ], + "editor.formatOnType": true, + "editor.formatOnSave": true, + "editor.wordBasedSuggestions": "off", + "editor.defaultFormatter": "ms-python.black-formatter", + "editor.tabSize": 4, + }, + "isort.args":["--profile", "black"], + "black-formatter.args": [ + "--line-length=120", + "--skip-string-normalization" + ] + } + ``` +### Testing python + +Tests should be in the test subdirectory. Each file should be named test\_\*.py and each test function should be named test\_\*(). +Tests can be executed by `make test`. + +If you want to debug test, here is the example launch.json. +``` +{ + "version": "0.2.0", + "configurations": [{ + "name": "Pytest current file", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "console": "integratedTerminal", + "args": ["${file}"], + "justMyCode": false + }] +} +``` + +### Code style and formating + +`C2P` uses [Black](https://black.readthedocs.io/en/stable/) for code formatting and [isort](https://pycqa.github.io/isort/) for sorting imports. `make format` runs both tools. + +`C2P` also uses [pre-commit](https://pre-commit.com/) hooks that are integrated into the development process with [detect-secrets](https://github.com/IBM/detect-secrets) to prevent from contaminating any confidential data. + +## For Go project +Please refer to [go/README.md](/go) \ No newline at end of file diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 0000000..97e0413 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,5 @@ +Compliance-to-Policy (C2P) was designed and open sourced by a team based at [IBM Research](https://www.research.ibm.com/) and others around the world. The list includes: + +Takumi Yanagawa [yana1205](https://github.com/yana1205) + +Yuji Watanabe [yuji-watanabe-jp](https://github.com/yuji-watanabe-jp) \ No newline at end of file diff --git a/Makefile b/Makefile index e7a4ebb..564f761 100644 --- a/Makefile +++ b/Makefile @@ -1,295 +1,49 @@ -# VERSION defines the project version for the bundle. -# Update this value when you upgrade the version of your project. -# To re-generate a bundle for another specific version without changing the standard setup, you can: -# - use the VERSION as arg of the bundle target (e.g make bundle VERSION=0.0.2) -# - use environment variables to overwrite this value (e.g export VERSION=0.0.2) -VERSION ?= 0.0.1 +PYTHON := $(shell pwd)/.venv/bin/python -# CHANNELS define the bundle channels used in the bundle. -# Add a new line here if you would like to change its default config. (E.g CHANNELS = "candidate,fast,stable") -# To re-generate a bundle for other specific channels without changing the standard setup, you can: -# - use the CHANNELS as arg of the bundle target (e.g make bundle CHANNELS=candidate,fast,stable) -# - use environment variables to overwrite this value (e.g export CHANNELS="candidate,fast,stable") -ifneq ($(origin CHANNELS), undefined) -BUNDLE_CHANNELS := --channels=$(CHANNELS) -endif +.venv: + @echo Please create venv firstly -# DEFAULT_CHANNEL defines the default channel used in the bundle. -# Add a new line here if you would like to change its default config. (E.g DEFAULT_CHANNEL = "stable") -# To re-generate a bundle for any other default channel without changing the default setup, you can: -# - use the DEFAULT_CHANNEL as arg of the bundle target (e.g make bundle DEFAULT_CHANNEL=stable) -# - use environment variables to overwrite this value (e.g export DEFAULT_CHANNEL="stable") -ifneq ($(origin DEFAULT_CHANNEL), undefined) -BUNDLE_DEFAULT_CHANNEL := --default-channel=$(DEFAULT_CHANNEL) -endif -BUNDLE_METADATA_OPTS ?= $(BUNDLE_CHANNELS) $(BUNDLE_DEFAULT_CHANNEL) +build: .venv + @$(PYTHON) -m build -# IMAGE_TAG_BASE defines the docker.io namespace and part of the image name for remote images. -# This variable is used to construct full image tags for bundle and catalog images. -# -# For example, running 'make bundle-build bundle-push catalog-build catalog-push' will build and push both -# github.com/compliance-to-policy-bundle:$VERSION and github.com/compliance-to-policy-catalog:$VERSION. -IMAGE_TAG_BASE ?= github.com/compliance-to-policy +install: .venv + @$(PYTHON) -m pip install . -# BUNDLE_IMG defines the image:tag used for the bundle. -# You can use it as an arg. (E.g make bundle-build BUNDLE_IMG=/:) -BUNDLE_IMG ?= $(IMAGE_TAG_BASE)-bundle:v$(VERSION) +install-dev: .venv + @$(PYTHON) -m pip install ".[dev]" -# BUNDLE_GEN_FLAGS are the flags passed to the operator-sdk generate bundle command -BUNDLE_GEN_FLAGS ?= -q --overwrite --version $(VERSION) $(BUNDLE_METADATA_OPTS) +uninstall: .venv + @$(PYTHON) -m pip uninstall compliance-to-policy -# USE_IMAGE_DIGESTS defines if images are resolved via tags or digests -# You can enable this value if you would like to use SHA Based Digests -# To enable set flag to true -USE_IMAGE_DIGESTS ?= false -ifeq ($(USE_IMAGE_DIGESTS), true) - BUNDLE_GEN_FLAGS += --use-image-digests -endif -# Image URL to use all building/pushing image targets -IMG ?= controller:latest -# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary. -ENVTEST_K8S_VERSION = 1.25.0 +format: .venv + @$(PYTHON) -m isort . + @$(PYTHON) -m black . -# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) -ifeq (,$(shell go env GOBIN)) -GOBIN=$(shell go env GOPATH)/bin -else -GOBIN=$(shell go env GOBIN) -endif +lint: .venv + @$(PYTHON) -m pylint ./c2p ./tests -# Setting SHELL to bash allows bash commands to be executed by recipes. -# Options are set to exit when a recipe line exits non-zero or a piped command fails. -SHELL = /usr/bin/env bash -o pipefail -.SHELLFLAGS = -ec +.PHONY: docs +docs: .venv + @$(PYTHON) -m mkdocs build -.PHONY: all -all: build +.PHONY: gh-pages + gh-pages: .venv + @$(PYTHON) -m mkdocs gh-deploy -##@ General +# make test ARGS="-n 2 --dist loadscope --log-cli-level DEBUG" TARGET="tests/c2p/test_cli.py" +# TODO: -n 2 (pytest-xdist plugin) results in no logs displayed. +test: ARGS ?= +test: TARGET ?= tests/ +test: .venv test-plugin + @OUTPUT_PATH=/dev/null $(PYTHON) -m pytest $(ARGS) $(TARGET) -# The help target prints out all targets with their descriptions organized -# beneath their categories. The categories are represented by '##@' and the -# target descriptions by '##'. The awk commands is responsible for reading the -# entire set of makefiles included in this invocation, looking for lines of the -# file as xyz: ## something, and then pretty-format the target and help. Then, -# if there's a line with ##@ something, that gets pretty-printed as a category. -# More info on the usage of ANSI control characters for terminal formatting: -# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters -# More info on the awk command: -# http://linuxcommand.org/lc3_adv_awk.php +test-plugin: ARGS ?= +test-plugin: TARGET ?= plugins_public/tests/ +test-plugin: .venv + @OUTPUT_PATH=/dev/null $(PYTHON) -m pytest $(ARGS) $(TARGET) -.PHONY: help -help: ## Display this help. - @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) - -##@ Development - -.PHONY: manifests -manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. - $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases - -.PHONY: generate -generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. - $(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..." - -.PHONY: fmt -fmt: ## Run go fmt against code. - go fmt ./... - -.PHONY: vet -vet: ## Run go vet against code. - go vet ./... - -.PHONY: test-controllers -test-controllers: manifests generate fmt vet envtest ## Run tests. - KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./controllers/... -coverprofile cover.controllers.out -p=1 - -.PHONY: test-pkg -test-pkg: - go test ./pkg/... -coverprofile cover.out - -.PHONY: test -test: test-pkg test-controllers - -##@ Build - -.PHONY: build -build: generate fmt vet ## Build manager binary. - go build -o bin/manager main.go - -.PHONY: run -run: manifests generate fmt vet ## Run a controller from your host. - go run ./main.go - -# If you wish built the manager image targeting other platforms you can use the --platform flag. -# (i.e. docker build --platform linux/arm64 ). However, you must enable docker buildKit for it. -# More info: https://docs.docker.com/develop/develop-images/build_enhancements/ -.PHONY: docker-build -docker-build: test ## Build docker image with the manager. - docker build -t ${IMG} . - -.PHONY: docker-push -docker-push: ## Push docker image with the manager. - docker push ${IMG} - -# PLATFORMS defines the target platforms for the manager image be build to provide support to multiple -# architectures. (i.e. make docker-buildx IMG=myregistry/mypoperator:0.0.1). To use this option you need to: -# - able to use docker buildx . More info: https://docs.docker.com/build/buildx/ -# - have enable BuildKit, More info: https://docs.docker.com/develop/develop-images/build_enhancements/ -# - be able to push the image for your registry (i.e. if you do not inform a valid value via IMG=> than the export will fail) -# To properly provided solutions that supports more than one platform you should use this option. -PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le -.PHONY: docker-buildx -docker-buildx: test ## Build and push docker image for the manager for cross-platform support - # copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile - sed -e '1 s/\(^FROM\)/FROM --platform=\$$\{BUILDPLATFORM\}/; t' -e ' 1,// s//FROM --platform=\$$\{BUILDPLATFORM\}/' Dockerfile > Dockerfile.cross - - docker buildx create --name project-v3-builder - docker buildx use project-v3-builder - - docker buildx build --push --platform=$(PLATFORMS) --tag ${IMG} -f Dockerfile.cross - - docker buildx rm project-v3-builder - rm Dockerfile.cross - -##@ Deployment - -ifndef ignore-not-found - ignore-not-found = false -endif - -.PHONY: install -install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config. - $(KUSTOMIZE) build config/crd | kubectl apply -f - - -.PHONY: uninstall -uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. - $(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f - - -## For development in a non OCM Hub -.PHONY: install-ocm-related-crds -install-ocm-related-crds: - kubectl apply -f config/ocm - -.PHONY: uninstall-ocm-related-crds -uninstall-ocm-related-crds: - kubectl delete --ignore-not-found=$(ignore-not-found) -f config/ocm - -.PHONY: deploy -deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. - cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} - $(KUSTOMIZE) build config/default | kubectl apply -f - - -.PHONY: undeploy -undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. - $(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f - - -.PHONY: get-policy-resources -get-policy-resources: - kubectl get policy,placementrule,placementbinding - -.PHONY: delete-policy-resources -delete-all-policy-resources: - kubectl delete policy,placementrule,placementbinding --all - -##@ Build Dependencies - -## Location to install dependencies to -LOCALBIN ?= $(shell pwd)/bin -$(LOCALBIN): - mkdir -p $(LOCALBIN) - -## Tool Binaries -KUSTOMIZE ?= $(LOCALBIN)/kustomize -CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen -ENVTEST ?= $(LOCALBIN)/setup-envtest - -## Tool Versions -KUSTOMIZE_VERSION ?= v4.5.7 -CONTROLLER_TOOLS_VERSION ?= v0.10.0 - -KUSTOMIZE_INSTALL_SCRIPT ?= "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" -.PHONY: kustomize -kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. -$(KUSTOMIZE): $(LOCALBIN) - test -s $(LOCALBIN)/kustomize || { curl -Ss $(KUSTOMIZE_INSTALL_SCRIPT) | bash -s -- $(subst v,,$(KUSTOMIZE_VERSION)) $(LOCALBIN); } - -.PHONY: controller-gen -controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary. -$(CONTROLLER_GEN): $(LOCALBIN) - test -s $(LOCALBIN)/controller-gen || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION) - -.PHONY: envtest -envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. -$(ENVTEST): $(LOCALBIN) - test -s $(LOCALBIN)/setup-envtest || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest - -.PHONY: bundle -bundle: manifests kustomize ## Generate bundle manifests and metadata, then validate generated files. - operator-sdk generate kustomize manifests -q - cd config/manager && $(KUSTOMIZE) edit set image controller=$(IMG) - $(KUSTOMIZE) build config/manifests | operator-sdk generate bundle $(BUNDLE_GEN_FLAGS) - operator-sdk bundle validate ./bundle - -.PHONY: bundle-build -bundle-build: ## Build the bundle image. - docker build -f bundle.Dockerfile -t $(BUNDLE_IMG) . - -.PHONY: bundle-push -bundle-push: ## Push the bundle image. - $(MAKE) docker-push IMG=$(BUNDLE_IMG) - -.PHONY: opm -OPM = ./bin/opm -opm: ## Download opm locally if necessary. -ifeq (,$(wildcard $(OPM))) -ifeq (,$(shell which opm 2>/dev/null)) - @{ \ - set -e ;\ - mkdir -p $(dir $(OPM)) ;\ - OS=$(shell go env GOOS) && ARCH=$(shell go env GOARCH) && \ - curl -sSLo $(OPM) https://github.com/operator-framework/operator-registry/releases/download/v1.23.0/$${OS}-$${ARCH}-opm ;\ - chmod +x $(OPM) ;\ - } -else -OPM = $(shell which opm) -endif -endif - -# A comma-separated list of bundle images (e.g. make catalog-build BUNDLE_IMGS=example.com/operator-bundle:v0.1.0,example.com/operator-bundle:v0.2.0). -# These images MUST exist in a registry and be pull-able. -BUNDLE_IMGS ?= $(BUNDLE_IMG) - -# The image tag given to the resulting catalog image (e.g. make catalog-build CATALOG_IMG=example.com/operator-catalog:v0.2.0). -CATALOG_IMG ?= $(IMAGE_TAG_BASE)-catalog:v$(VERSION) - -# Set CATALOG_BASE_IMG to an existing catalog image tag to add $BUNDLE_IMGS to that image. -ifneq ($(origin CATALOG_BASE_IMG), undefined) -FROM_INDEX_OPT := --from-index $(CATALOG_BASE_IMG) -endif - -# Build a catalog image by adding bundle images to an empty catalog using the operator package manager tool, 'opm'. -# This recipe invokes 'opm' in 'semver' bundle add mode. For more information on add modes, see: -# https://github.com/operator-framework/community-operators/blob/7f1438c/docs/packaging-operator.md#updating-your-existing-operator -.PHONY: catalog-build -catalog-build: opm ## Build a catalog image. - $(OPM) index add --container-tool docker --mode semver --tag $(CATALOG_IMG) --bundles $(BUNDLE_IMGS) $(FROM_INDEX_OPT) - -# Push the catalog image. -.PHONY: catalog-push -catalog-push: ## Push a catalog image. - $(MAKE) docker-push IMG=$(CATALOG_IMG) - -### -.PHONY: compose-v2 -compose-v2: bin/compose-v2.linux_amd64 bin/compose-v2.darwin_amd64 bin/compose-v2.darwin_arm64 - -bin/compose-v2.linux_amd64: - GOOS=linux GOARCH=amd64 go build -o bin/compose-v2.linux_amd64 ./cmd/compose-v2 - -bin/compose-v2.darwin_amd64: - GOOS=darwin GOARCH=amd64 go build -o bin/compose-v2.darwin_amd64 ./cmd/compose-v2 - -bin/compose-v2.darwin_arm64: - GOOS=darwin GOARCH=arm64 go build -o bin/compose-v2.darwin_arm64 ./cmd/compose-v2 - -bin/compose-v2.%.gz: bin/compose-v2.% - gzip ./bin/compose-v2.$* +clean: .venv + @rm -rf build *.egg-info dist + @find ./plugins -type d \( -name '*.egg-info' -o -name 'dist' \) | while read x; do echo $$x; rm -r $$x ; done + @$(PYTHON) -m pyclean -v . \ No newline at end of file diff --git a/README.md b/README.md index f830bc0..f54dc97 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,294 @@ -# compliance-to-policy -Compliance-to-Policy (C2P) provides the framework to bridge Compliance administration and Policy administration by [OSCAL](https://pages.nist.gov/OSCAL/). OSCAL (Open Security Controls Assessment Language) is a standardized framework developed by NIST for expressing and automating the assessment and management of security controls in machine-readable format (xml, json, yaml) +## Introduction +C2P bridges Compliance and PVPs. C2P takes Compliance requirements and generates technical policies for PVP, and takes PVP native results and generates Compliance Assessment Results. -![C2P Overview](/docs/images/e2e-pm.png) +C2P supports Compliance and PVP as follows: +- Compliance framework + - Open Security Controls Assessment Language (OSCAL) +- PVP + - Kyverno + - Open Cluster Management Governance Policy Framework -## Usage of C2P CLI +C2P reduces the cost to implement the interchange between Compliance artifacts and PVP proprietary artifacts. C2P is extensible to various PVPs through plugin. + +## C2P in Go language (deprecated) +C2P was originally maintained in Go language but now it's maintained in Python. The Go verion is moved to [/go](/go/README.md). + +## Install + +#### From git repo ``` -$ c2pcli -h -C2P CLI +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. -Usage: - c2pcli [flags] - c2pcli [command] +#### 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 + ``` -Available Commands: - completion Generate the autocompletion script for the specified shell - help Help about any command - kyverno C2P CLI Kyverno plugin - ocm C2P CLI OCM plugin - version Display version +## Quick demo -Flags: - -h, --help help for c2pcli +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 -Use "c2pcli [command] --help" for more information about a command. -``` + 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 + ``` + ![assessment-results-md.kyverno.jpg](/docs/public/images/assessment-results-md.kyverno.jpg) + +## 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 + ``` +#### 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)) + ``` +1. (Optional) you may reformat OSCAL Assessment Results in markdown style. + ``` + c2p tools viewer -ar -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`. + +#### 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] = [] -C2P is targeting a plugin architecture to cover not only OCM Policy Framework but also other types of PVPs. -Please go to the docs for each usage. -- [C2P for OCM](/docs/ocm/README.md) -- [C2P for Kyverno](/docs/kyverno/README.md) + 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, + ) + ) -## Build at local + 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 ``` -goreleaser release --snapshot --clean +$ 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 ========================================================================================= ``` -## Test +### Cleanup caches ``` -make test-pkg +make clean ``` \ No newline at end of file diff --git a/c2p/__init__.py b/c2p/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/c2p/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/c2p/__main__.py b/c2p/__main__.py new file mode 100644 index 0000000..61d3f25 --- /dev/null +++ b/c2p/__main__.py @@ -0,0 +1,26 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import c2p.cli + + +def init() -> None: + """Initialize c2p CLI.""" + if __name__ == '__main__': + c2p.cli.run() + + +init() diff --git a/c2p/cli.py b/c2p/cli.py new file mode 100644 index 0000000..926315c --- /dev/null +++ b/c2p/cli.py @@ -0,0 +1,53 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import argparse +from logging import DEBUG +from sys import exit + +from trestle.common import const, log +from trestle.core.commands.command_docs import CommandBase + +from c2p.commands.tools.tools import Tools +from c2p.commands.version import VersionCmd +from c2p.common import logging + +logger = logging.getLogger(__name__) + + +class C2P(CommandBase): + """Bridge Compliance and Policy""" + + subcommands = [ + VersionCmd, + Tools, + ] + + def _init_arguments(self) -> None: + self.add_argument('-v', '--verbose', help=const.DISPLAY_VERBOSE_OUTPUT, action='count', default=0) + + def _validate_and_run(self, args: argparse.ArgumentParser): + if args.verbose > 0: + logging.set_global_logging_levels(DEBUG) + + +def run() -> None: + """Run the c2p cli.""" + log.set_global_logging_levels() + logging.set_global_logging_levels() + logger.debug('Main entry point.') + + exit(C2P().run()) diff --git a/c2p/commands/__init__.py b/c2p/commands/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/c2p/commands/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/c2p/commands/tools/__init__.py b/c2p/commands/tools/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/c2p/commands/tools/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/c2p/commands/tools/csv2oscal_cd.py b/c2p/commands/tools/csv2oscal_cd.py new file mode 100644 index 0000000..46cd44b --- /dev/null +++ b/c2p/commands/tools/csv2oscal_cd.py @@ -0,0 +1,70 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import argparse +import pathlib + +from trestle.common.err import handle_generic_command_exception +from trestle.core.commands.command_docs import CommandBase +from trestle.core.commands.common.return_codes import CmdReturnCodes + +from c2p.common import logging +from c2p.tools.oscal_csv_to_json import OscalCsvToJson + +logger = logging.getLogger(__name__) + + +class Csv2OscalCd(CommandBase): + """Command to generate OSCAL Component Definition from component definition in csv format""" + + name = 'csv-to-oscal-cd' + + def _init_arguments(self) -> None: + self.add_argument( + '-c', + '--config', + type=pathlib.Path, + help='Path to config file if --csv, --title, and -o are not given', + required=False, + ) + self.add_argument('--title', type=str, help='Title of component-definition', required=False) + self.add_argument('--csv', type=pathlib.Path, help='Path to csv file', required=False) + self.add_argument( + '-o', + '--out', + type=pathlib.Path, + help='Path to directory for output of component-definition.json', + required=False, + ) + self.add_argument( + '-i', '--info', action='store_true', help='Print information about a particular task.', required=False + ) + + def _run(self, args: argparse.Namespace) -> int: + octj = OscalCsvToJson() + try: + if args.config != None: + octj.generate(pathlib.Path(args.config)) + elif args.title != None and args.csv != None and args.out != None: + path = octj.generate_config(args.title, args.csv, args.out) + octj.generate(path) + + except Exception as e: + return handle_generic_command_exception( + e, logger, 'Error while performing OSCAL Assessment Results generation' + ) + + return CmdReturnCodes.SUCCESS.value diff --git a/c2p/commands/tools/tools.py b/c2p/commands/tools/tools.py new file mode 100644 index 0000000..2eb79a0 --- /dev/null +++ b/c2p/commands/tools/tools.py @@ -0,0 +1,28 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from trestle.core.commands.command_docs import CommandBase + +from c2p.commands.tools.csv2oscal_cd import Csv2OscalCd +from c2p.commands.tools.viewer import Viewer + + +class Tools(CommandBase): + """Subcommand for tools""" + + name = 'tools' + + subcommands = [Csv2OscalCd, Viewer] diff --git a/c2p/commands/tools/viewer.py b/c2p/commands/tools/viewer.py new file mode 100644 index 0000000..e498246 --- /dev/null +++ b/c2p/commands/tools/viewer.py @@ -0,0 +1,74 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import argparse +import pathlib + +from trestle.common.err import handle_generic_command_exception +from trestle.core.commands.command_docs import CommandBase +from trestle.core.commands.common.return_codes import CmdReturnCodes +from trestle.oscal.assessment_results import AssessmentResults +from trestle.oscal.component import ComponentDefinition + +from c2p.common import logging +from c2p.tools.viewer import viewer + +logger = logging.getLogger(__name__) + + +class Viewer(CommandBase): + """Command to render OSCAL Assessment Results in markdown""" + + name = 'viewer' + + def _init_arguments(self) -> None: + self.add_argument( + '-ar', + '--assessment-results', + type=pathlib.Path, + help='Path to OSCAL Assessment Results', + required=True, + ) + self.add_argument( + '-cdef', + '--component-definition', + type=pathlib.Path, + help='Path to OSCAL Component Definition', + required=True, + ) + self.add_argument( + '-o', + '--out', + type=pathlib.Path, + help='Path to output file', + required=False, + ) + + def _run(self, args: argparse.Namespace) -> int: + + ar = AssessmentResults.oscal_read(args.assessment_results) + cdef = ComponentDefinition.oscal_read(args.component_definition) + rendered_md = viewer.render(ar, cdef) + try: + if args.out != None: + pathlib.Path(args.out).open('w').write(rendered_md) + else: + self.out(rendered_md) + + except Exception as e: + return handle_generic_command_exception(e, logger, 'Error while performing rendering Assessment Results') + + return CmdReturnCodes.SUCCESS.value diff --git a/c2p/commands/version.py b/c2p/commands/version.py new file mode 100644 index 0000000..320e70c --- /dev/null +++ b/c2p/commands/version.py @@ -0,0 +1,32 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +"""C2P Version Command.""" +import argparse +from importlib.metadata import version + +from trestle.core.commands.command_docs import CommandBase +from trestle.core.commands.common.return_codes import CmdReturnCodes + + +class VersionCmd(CommandBase): + """Output version info for C2P.""" + + name = 'version' + + def _run(self, _: argparse.Namespace) -> int: + self.out(version('compliance-to-policy')) + return CmdReturnCodes.SUCCESS.value diff --git a/c2p/common/__init__.py b/c2p/common/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/c2p/common/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/c2p/common/c2p_base_model.py b/c2p/common/c2p_base_model.py new file mode 100644 index 0000000..884f031 --- /dev/null +++ b/c2p/common/c2p_base_model.py @@ -0,0 +1,92 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import datetime +import json +import pathlib +from typing import Any, Dict, Optional, Type, TypeVar + +import orjson +from pydantic import BaseModel +from pydantic.parse import load_file +from trestle.core.base_model import robust_datetime_serialization + +import c2p.common.err as err + + +class C2PBaseModel(BaseModel): + """Base Model. Serves as wrapper around BaseModel for overriding methods.""" + + class Config: + json_encoders = {datetime.datetime: lambda x: robust_datetime_serialization(x)} + + @classmethod + def read(cls, path: pathlib.Path) -> Optional['C2PBaseModel']: + obj: Dict[str, Any] = {} + try: + obj = load_file( + path, + json_loads=cls.__config__.json_loads, + ) + except Exception as e: + raise err.C2PError(f'Error loading file {path} {str(e)}') + + try: + parsed = cls.parse_obj(obj) + except Exception as e: + raise err.C2PError(f'Error parsing file {path} {str(e)}') + + return parsed + + def serialize_json_bytes(self, pretty: bool = False) -> bytes: + odict = self.dict(by_alias=True, exclude_none=True) + if pretty: + return orjson.dumps(odict, default=self.__json_encoder__, option=orjson.OPT_INDENT_2) # type: ignore + return orjson.dumps(odict, default=self.__json_encoder__) # type: ignore + + +T = TypeVar('T', BaseModel, Any) + + +class C2PBaseDict(Dict[str, T]): + _member_class: Type[T] + + def __init__(self, obj: dict = {}, **kwargs): + if issubclass(self._member_class, BaseModel): + member_dict = {} + for key, value in kwargs.items(): + c = self._member_class(**value) + member_dict[key] = c + for key, value in obj.items(): + c = self._member_class(**value) + member_dict[key] = c + super().__init__(member_dict) + else: + super().__init__(obj, **kwargs) + + def serialize_json_bytes(self, pretty: bool = False) -> bytes: + if pretty: + return orjson.dumps(self, default=self._get_json_encoder(), option=orjson.OPT_INDENT_2) # type: ignore + return orjson.dumps(self, default=self._get_json_encoder()) + + def json(self) -> str: + return json.dumps(self, default=self._get_json_encoder()) + + def _get_json_encoder(self) -> Any: + if issubclass(self._member_class, BaseModel): + return self._member_class.__json_encoder__ + else: + return None diff --git a/c2p/common/err.py b/c2p/common/err.py new file mode 100644 index 0000000..e0062bb --- /dev/null +++ b/c2p/common/err.py @@ -0,0 +1,37 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + + +class C2PError(RuntimeError): + """ + General framework (non-application) related errors. + + Attributes: + msg (str): Human readable string describing the exception. + """ + + def __init__(self, msg: str): + """Intialization for C2PError. + + Args: + msg (str): The error message + """ + RuntimeError.__init__(self) + self.msg = msg + + def __str__(self) -> str: + """Return C2P error message if asked for a string.""" + return self.msg diff --git a/c2p/common/logging.py b/c2p/common/logging.py new file mode 100644 index 0000000..c6aeb8a --- /dev/null +++ b/c2p/common/logging.py @@ -0,0 +1,47 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import logging +import sys + +# Singleton logger instance +_logger = logging.getLogger('c2p') + +FORMATTER_STR = '[%(asctime)s %(levelname)s %(name)s] %(message)s' + + +def set_global_logging_levels(level: int = logging.INFO) -> None: + """Initialise logging. + + Should only be invoked by the CLI classes or similar. + """ + # This line stops default root loggers setup for a python context from logging extra messages. + # DO NOT USE THIS COMMAND directly from an SDK. Handle logs levels based on your own application + _logger.propagate = False + # Remove handlers + _logger.handlers.clear() + # set global level + _logger.setLevel(level) + # Create standard out + handler = logging.StreamHandler(sys.stderr) + handler.setLevel(level) + handler.setFormatter(logging.Formatter(FORMATTER_STR)) + # add ch to logger + _logger.addHandler(handler) + + +def getLogger(name: str) -> logging.Logger: + return logging.getLogger(name) diff --git a/c2p/common/oscal.py b/c2p/common/oscal.py new file mode 100644 index 0000000..d1fe487 --- /dev/null +++ b/c2p/common/oscal.py @@ -0,0 +1,37 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from typing import Dict, List + +from trestle.common import const +from trestle.common.common_types import TypeWithParamId, TypeWithParts, TypeWithProps +from trestle.common.list_utils import as_filtered_list, as_list, none_if_empty + + +def is_component_type_validation(component_type: str) -> bool: + return component_type.lower() == 'validation' + + +def get_rule_sets(item: TypeWithProps) -> List[Dict[str, str]]: + """Get all rules found in this items props.""" + # rules is dict containing rule_id and description + rules_dict = {} + for prop in as_list(item.props): + remarks = prop.remarks + if not remarks in rules_dict: + rules_dict[remarks] = {} + rules_dict[remarks][prop.name] = prop.value + return list(map(lambda x: x[1], rules_dict.items())) diff --git a/c2p/common/utils.py b/c2p/common/utils.py new file mode 100644 index 0000000..15b9543 --- /dev/null +++ b/c2p/common/utils.py @@ -0,0 +1,100 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import json +import pathlib +import re +from datetime import datetime, timezone +from typing import Any, List, Union + +from trestle.oscal.component import ComponentDefinition + +from c2p.common import logging + +logger = logging.getLogger('common:utils') + + +class Control: + def __init__(self, control_id, impl_id, component_id): + self.control_id = control_id + self.impl_id = impl_id + self.component_id = component_id + + +class ControlList: + def __init__(self, items: List['Control']): + self.items = items + + def get_control_ids(self) -> List[str]: + def custom_sort(key): + tokens = re.split('(\d+)', key) + return list(map(lambda x: int(x) if x.isdigit() else x, tokens)) + + control_ids = set(map(lambda x: x.control_id, self.items)) + return sorted(list(control_ids), key=custom_sort) + + +def get_control_list(path: str) -> ControlList: + cdef = ComponentDefinition.oscal_read(pathlib.Path(path)) + controls: List[Control] = [] + for component in cdef.components: + for control_impl in component.control_implementations: + control_impl.uuid + for impl_req in control_impl.implemented_requirements: + control = Control(impl_req.control_id, control_impl.uuid, component.uuid) + controls.append(control) + + return ControlList(controls) + + +def load_json_as_dict(path: Union[str, pathlib.Path]) -> Any: + test_te_path: pathlib.Path + if isinstance(path, str): + test_te_path = pathlib.Path(path) + elif isinstance(path, pathlib.Path): + test_te_path = path + else: + return + fh = test_te_path.open('r', encoding='utf8') + return json.load(fh) + + +def get_datetime() -> datetime: + return datetime.utcnow().replace(microsecond=0).replace(tzinfo=timezone.utc) + + +def get_dict_safely(d, key: Union[str, List[str]], default=None): + if isinstance(key, str): + if d is not None and isinstance(d, dict): + return d[key] if key in d else default + else: + return default + else: + if len(key) > 0: + k = key.pop(0) + v = get_dict_safely(d, k, default) + return get_dict_safely(v, key, default) + else: + return d + + +def remove_none(obj): + if isinstance(obj, (list, tuple, set)): + return type(obj)(remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((remove_none(k), remove_none(v)) for k, v in obj.items() if k is not None and v is not None) + else: + return obj diff --git a/c2p/framework/__init__.py b/c2p/framework/__init__.py new file mode 100644 index 0000000..c81a41f --- /dev/null +++ b/c2p/framework/__init__.py @@ -0,0 +1,21 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import pluggy + +LAYER_NAME = 'p2c' +hookimpl = pluggy.HookimplMarker(LAYER_NAME) +hookspec = pluggy.HookspecMarker(LAYER_NAME) diff --git a/c2p/framework/c2p.py b/c2p/framework/c2p.py new file mode 100644 index 0000000..037c1d2 --- /dev/null +++ b/c2p/framework/c2p.py @@ -0,0 +1,211 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import pathlib +from typing import Dict, List, Optional + +from pydantic import BaseModel +from trestle import __version__ as TRESTLE_VERSION +from trestle.oscal import OSCAL_VERSION +from trestle.oscal.assessment_results import ( + AssessmentResults, + ImportAp, + Observation, + Result, +) +from trestle.oscal.catalog import Catalog +from trestle.oscal.catalog import Model as CatalogRoot +from trestle.oscal.common import ( + Link, + Metadata, + Property, + RelevantEvidence, + SubjectReference, +) +from trestle.oscal.component import ComponentDefinition +from trestle.oscal.component import Model as ComponentDefinitionRoot +from trestle.oscal.profile import Model as ProfileRoot +from trestle.oscal.profile import Profile + +from c2p.common.oscal import is_component_type_validation +from c2p.common.utils import get_dict_safely +from c2p.framework import oscal_utils +from c2p.framework.models.c2p_config import C2PConfig +from c2p.framework.models.policy import Parameter, Policy, RuleSet +from c2p.framework.models.pvp_result import PVPResult, set_defaults + +RuleId = str + + +class _RuleSet(BaseModel): + effective_rule_id: str + effective_check_id: str + rule_id: str + rule_description: Optional[str] + check_id: Optional[str] + check_description: Optional[str] + raw: Optional[Dict[str, str]] + + +class C2P: + def __init__(self, c2p_config: C2PConfig): + self._c2p_config = c2p_config + if c2p_config.compliance.catalog: + catalog = Catalog.oscal_read(pathlib.Path(c2p_config.compliance.catalog)) + self._catalog_root: CatalogRoot = CatalogRoot(catalog=catalog) + if c2p_config.compliance.profile: + profile = Profile.oscal_read(pathlib.Path(c2p_config.compliance.profile)) + self._profile_root: ProfileRoot = ProfileRoot(profile=profile) + cdef = ComponentDefinition.oscal_read(pathlib.Path(c2p_config.compliance.component_definition)) + self._component_root: ComponentDefinitionRoot = ComponentDefinitionRoot(component_definition=cdef) + + def set_pvp_result(self, pvp_result: PVPResult): + self._c2p_config.pvp_result = pvp_result + + def result_to_oscal(self) -> AssessmentResults: + pvp_result = set_defaults(self._c2p_config.pvp_result) + timestamp = oscal_utils.get_datetime_str() + metadata = Metadata( + title=self._c2p_config.result_title, + oscal_version=OSCAL_VERSION, + version=TRESTLE_VERSION, + last_modified=timestamp, + ) + import_ap = ImportAp(href='https://not-available-for-now') + value = AssessmentResults( + uuid=oscal_utils.uuid(), + metadata=metadata, + import_ap=import_ap, + results=[self._get_result(pvp_result)], + ) + return value + + def get_policy(self) -> Policy: + return Policy(rule_sets=self.get_rule_sets(), parameters=self.get_parameters()) + + def get_rule_sets(self) -> List[RuleSet]: + _rule_sets = self._get_rule_sets() + + def _conv(x: _RuleSet): + return RuleSet( + rule_id=x.effective_rule_id, + rule_description=x.rule_description, + check_id=x.effective_check_id, + check_description=x.check_description, + raw=x.raw, + ) + + return list(map(_conv, _rule_sets)) + + def get_parameters(self) -> List[Parameter]: + return self._get_parameters() + + def _get_rule_sets(self) -> List[_RuleSet]: + rule_sets: List[Dict[str, str]] = [] + for comp in self._component_root.component_definition.components: + if is_component_type_validation(comp.type) and comp.title == self._c2p_config.pvp_name: + rule_sets = oscal_utils.group_props_by_remarks(comp) + + def _conv(x: Dict[str, str]) -> _RuleSet: + return _RuleSet( + rule_id=get_dict_safely(x, 'Rule_Id'), + rule_description=get_dict_safely(x, 'Rule_Description'), + check_id=get_dict_safely(x, 'Check_Id'), + check_description=get_dict_safely(x, 'Check_Description'), + effective_rule_id=get_dict_safely(x, self._c2p_config.compliance.rule_id_column), + effective_check_id=get_dict_safely(x, self._c2p_config.compliance.check_id_column), + raw=x, + ) + + return list(map(_conv, filter(lambda x: 'Rule_Id' in x, rule_sets))) + + def _find_rule_set(self, check_id: str, rule_sets: List[_RuleSet]) -> Optional[_RuleSet]: + return next(filter(lambda x: x.effective_check_id == check_id, rule_sets), None) + + def _get_parameters(self) -> List[Parameter]: + parameters: List[Dict[str, str]] = [] + for component in self._component_root.component_definition.components: + if not is_component_type_validation(component.type): + parameters = oscal_utils.group_props_by_remarks(component) + + def _conv(x: Dict[str, str]) -> Parameter: + return Parameter( + id=get_dict_safely(x, 'Parameter_Id'), + description=get_dict_safely(x, 'Parameter_Description'), + value=get_dict_safely(x, 'Parameter_Value_Alternatives'), + ) + + return list(map(_conv, filter(lambda x: 'Parameter_Id' in x, parameters))) + + def _find_parameter(self, id: str, parameters: List[Parameter]) -> Optional[Parameter]: + return next(filter(lambda x: x.id == id, parameters), None) + + def _get_result(self, pvp_result: PVPResult) -> Result: + """Return result.""" + result = Result( + uuid=oscal_utils.uuid(), + title=self._c2p_config.result_title, + description=self._c2p_config.result_description, + start=oscal_utils.get_datetime_str(), + observations=self._get_observations(pvp_result), + reviewed_controls=oscal_utils.reviewed_controls(self._component_root.component_definition), + ) + if pvp_result.links != None: + result.links = list(map(lambda x: Link(href=x.href, text=x.description), pvp_result.links)) + if self._c2p_config.result_labels != None: + result.props = list(map(lambda x: Property(name='label', value=x), self._c2p_config.result_labels)) + return result + + def _get_observations(self, pvp_result: PVPResult) -> List[Observation]: + rule_sets = self._get_rule_sets() + observations = [] + for observation in pvp_result.observations_by_check: + rule_set = self._find_rule_set(observation.check_id, rule_sets) + if rule_set != None: + subjects = [] + for subject in observation.subjects: + props = [] + oscal_utils.add_prop(props, 'resource-id', subject, ['resource_id']) + oscal_utils.add_prop(props, 'result', subject, ['result']) + oscal_utils.add_prop(props, 'evaluated-on', subject, ['evaluated_on']) + oscal_utils.add_prop(props, 'reason', subject, ['reason']) + s = SubjectReference( + subject_uuid=oscal_utils.uuid(), title=subject.title, type=subject.type, props=props + ) + subjects.append(s) + + relevant_evidences = [] + if observation.relevant_evidences != None: + for rel in observation.relevant_evidences: + relevant_evidences.append(RelevantEvidence(href=rel.href, description=rel.description)) + + props = [] + oscal_utils.add_prop(props, 'assessment-rule-id', rule_set.effective_rule_id, []) + if observation.props != None: + props = props + observation.props + o = Observation( + uuid=oscal_utils.uuid(), + title=observation.title, + description=observation.title, + methods=observation.methods, + props=props, + subjects=subjects, + collected=observation.collected, + ) + if len(relevant_evidences) > 0: + o.relevant_evidence = relevant_evidences + observations.append(o) + return observations diff --git a/c2p/framework/models/__init__.py b/c2p/framework/models/__init__.py new file mode 100644 index 0000000..2c0e86c --- /dev/null +++ b/c2p/framework/models/__init__.py @@ -0,0 +1,19 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from c2p.framework.models.pvp_result import PVPResult +from c2p.framework.models.raw_result import RawResult +from c2p.framework.models.policy import Policy, Parameter, RuleSet diff --git a/c2p/framework/models/c2p_config.py b/c2p/framework/models/c2p_config.py new file mode 100644 index 0000000..bbdae8c --- /dev/null +++ b/c2p/framework/models/c2p_config.py @@ -0,0 +1,59 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from enum import Enum +from typing import Dict, List, Literal, Optional, Union + +from pydantic import Field + +from c2p.common.c2p_base_model import C2PBaseModel +from c2p.framework.models import PVPResult + + +class ComplianceType(str, Enum): + OSCAL = 'oscal' + + +class ComplianceOscal(C2PBaseModel): + type: Literal[ComplianceType.OSCAL] = Field(ComplianceType.OSCAL, title='Compliance Type') + catalog: Optional[str] + profile: Optional[str] + component_definition: Optional[str] + rule_id_column: Optional[str] = Field( + 'Rule_Id', + title='Column name of Rule Id in component-definition', + ) + rule_description_column: Optional[str] = Field( + 'Rule_Description', + title='Column name of Rule Description in component-definition', + ) + check_id_column: Optional[str] = Field( + 'Check_Id', + title='Column name of Check Id in component-definition', + ) + check_description_column: Optional[str] = Field( + 'Check_Description', + title='Column name of Check Description in component-definition', + ) + + +class C2PConfig(C2PBaseModel): + compliance: Optional[Union[ComplianceOscal]] + pvp_result: Optional[PVPResult] + pvp_name: Optional[str] + result_title: Optional[str] + result_description: Optional[str] + result_labels: Optional[List[str]] = None diff --git a/c2p/framework/models/policy.py b/c2p/framework/models/policy.py new file mode 100644 index 0000000..1ec8052 --- /dev/null +++ b/c2p/framework/models/policy.py @@ -0,0 +1,52 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from typing import Dict, List, Optional + +from pydantic import Field + +from c2p.common.c2p_base_model import C2PBaseModel + + +class RuleSet(C2PBaseModel): + rule_id: str = Field( + ..., + title='A unique identifier of a policy (desired state)', + ) + rule_description: Optional[str] = Field(title='Rule description') + check_id: str = Field( + ..., + title='A unique identifier used to reference the result of the policy (desired state)', + ) + check_description: Optional[str] + raw: Optional[Dict[str, str]] + + +class Parameter(C2PBaseModel): + id: str = Field( + ..., + title='A unique identifier of a parameter that can be used while PVP Policy generation', + ) + description: Optional[str] + value: str = Field( + ..., + title='The value of the parameter', + ) + + +class Policy(C2PBaseModel): + rule_sets: List[RuleSet] = Field(None) + parameters: List[Parameter] = Field(None) diff --git a/c2p/framework/models/pvp_result.py b/c2p/framework/models/pvp_result.py new file mode 100644 index 0000000..19649e3 --- /dev/null +++ b/c2p/framework/models/pvp_result.py @@ -0,0 +1,132 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from datetime import datetime +from enum import Enum +from typing import List, Optional + +from pydantic import Field + +from c2p.common.c2p_base_model import C2PBaseModel + + +class ResultEnum(str, Enum): + Pass = 'pass' + Failure = 'failure' + Error = 'error' + + +class Property(C2PBaseModel): + """ + An attribute, characteristic, or quality of the containing object expressed as a namespace qualified name/value pair. The value of a property is a simple scalar value, which may be expressed as a list of values. + """ + + name: str = Field( + ..., + description="A textual label that uniquely identifies a specific attribute, characteristic, or quality of the property's containing object.", + title='Property Name', + ) + value: str = Field( + ..., + description='Indicates the value of the attribute, characteristic, or quality.', + title='Property Value', + ) + + +class Link(C2PBaseModel): + """ + A reference to a local or remote resource + """ + + description: str = Field( + ..., + description='A human-readable description of this evidence.', + title='Relevant Evidence Description', + ) + href: str = Field( + ..., + description='A resolvable URL reference to relevant evidence.', + title='Relevant Evidence Reference', + ) + + +class Subject(C2PBaseModel): + """ + A human-oriented identifier reference to a resource. Use type to indicate whether the identified resource is a component, inventory item, location, user, or something else. + """ + + title: str = Field(title='Name of the object') + type: str = Field( + ..., + title='Subject Universally Unique Identifier Reference Type', + ) + resource_id: str = Field(..., title='Subject Universally Unique Identifier Reference') + result: ResultEnum = Field(..., title='Assessment result') + evaluated_on: Optional[datetime] = Field( + None, + title='Evaluated data/time', + description='The date and time the subject was evaluated. If not given, observations_by_check.collected is used.', + ) + reason: Optional[str] = Field(None, title='Reason') + props: Optional[List[Property]] = Field(None) + + +class ObservationByCheck(C2PBaseModel): + """ + Describes an individual observation based on each Check_Id defined in Component Definition. + """ + + title: Optional[str] = Field( + None, + description='The title for this observation for the check item. If not given, check id is used.', + title='Observation Title', + ) + description: Optional[str] = Field( + None, + description='A human-readable description of this assessment observation. If not given, check description is used.', + title='Observation Description', + ) + check_id: str = Field(..., description='Check_Id', title='Check_Id') + methods: List[str] = Field( + ..., + description='Identifies how the observation was made.', + title='Observation Method', + example=['TEST-AUTOMATED'], + ) + subjects: Optional[List[Subject]] = Field(None) + collected: datetime = Field( + ..., + description='The date and time identifying when the finding information was collected.', + title='Collected date/time', + ) + relevant_evidences: Optional[List[Link]] = Field(None) + props: Optional[List[Property]] = Field(None) + + +class PVPResult(C2PBaseModel): + observations_by_check: Optional[List[ObservationByCheck]] = Field(None) + links: Optional[List[Link]] = Field(None) + + +def set_defaults(pvp_result: PVPResult) -> PVPResult: + for observation in pvp_result.observations_by_check: + if observation.description == None: + observation.title = observation.check_id + observation.description = observation.check_id + for subject in observation.subjects: + if subject.evaluated_on == None: + subject.evaluated_on = observation.collected + return pvp_result diff --git a/c2p/framework/models/raw_result.py b/c2p/framework/models/raw_result.py new file mode 100644 index 0000000..a6618b2 --- /dev/null +++ b/c2p/framework/models/raw_result.py @@ -0,0 +1,46 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from typing import Any, Dict, Optional + +from pydantic import Field + +from c2p.common.c2p_base_model import C2PBaseModel + + +class Metadata(C2PBaseModel): + """ + Attributes: + filepath: Filepath + """ + + filepath: Optional[str] = Field(None, title='Filepath') + + +class RawResult(C2PBaseModel): + """ + + Attributes: + metadata: Metadata + data: Data + additional_props: Additional properties + """ + + metadata: Metadata = Field(Metadata()) + data: Any = Field(title='Serialized raw results (JSON, YAML) as dict object') + additional_props: Optional[Dict[str, Any]] = Field( + {}, title='Additional properties', description='Add any information in key-value format if required.' + ) diff --git a/c2p/framework/oscal_utils.py b/c2p/framework/oscal_utils.py new file mode 100644 index 0000000..9a68561 --- /dev/null +++ b/c2p/framework/oscal_utils.py @@ -0,0 +1,118 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from datetime import datetime, timezone +from enum import Enum +from typing import Any, Dict, List, Union +from uuid import uuid4 + +from pydantic import BaseModel +from trestle.common.common_types import TypeWithProps +from trestle.common.list_utils import as_list +from trestle.oscal.assessment_results import ( + ControlSelection, + ReviewedControls, + SelectControlById, +) +from trestle.oscal.common import Property +from trestle.oscal.component import ComponentDefinition + +from c2p.common.oscal import is_component_type_validation + + +def uuid() -> str: + """Return uuid.""" + return str(uuid4()) + + +def group_props_by_remarks(item: TypeWithProps) -> List[Dict[str, str]]: + """Group props by remarks and return as dict of [remark, prop].""" + grouped = {} + for prop in as_list(item.props): + remarks = prop.remarks + if not remarks in grouped: + grouped[remarks] = {} + grouped[remarks][prop.name] = prop.value + return list(map(lambda x: x[1], grouped.items())) + + +def reviewed_controls(component_definition: ComponentDefinition) -> ReviewedControls: + """Return reviewed controls.""" + control_selections = [] + for component in component_definition.components: + if is_component_type_validation(component.type): + continue + for control_impl in component.control_implementations: + selectControls = [] + for impl_req in control_impl.implemented_requirements: + statement_ids = [] + for stmt in impl_req.statements if impl_req.statements != None else []: + statement_ids.append(stmt.statement_id) + selectControl = SelectControlById(control_id=impl_req.control_id, statement_ids=statement_ids) + selectControls.append(selectControl) + control_selections.append(ControlSelection(include_controls=selectControls)) + rval = ReviewedControls(control_selections=control_selections) + return rval + + +def add_prop(props: List[Property], name: str, data: Union[str, Dict, BaseModel], keys: List[str]) -> None: + try: + if isinstance(data, str): + value = data + else: + if isinstance(data, BaseModel): + data = data.dict() + value = get_value(data, keys) + if value == None: + return None + prop = Property(name=normalize(name), value=whitespace(value)) + props.append(prop) + return prop + except KeyError: + return None + + +def get_value(data: Dict, keys: List[str]) -> Any: + """Descend yaml layers to get value for order list of keys.""" + try: + value = data + for key in keys: + value = value[key] + if isinstance(value, Enum): + value = value.value + if isinstance(value, datetime): + value = value.isoformat() + except KeyError: + raise KeyError + return value + + +def whitespace(text: str) -> str: + """Replace line ends with blanks.""" + return str(text).replace('\n', ' ') + + +def normalize(text: str) -> str: + """Replace slashes with underscores.""" + return text.replace('/', '_') + + +def get_datetime() -> datetime: + return datetime.utcnow().replace(microsecond=0).replace(tzinfo=timezone.utc) + + +def get_datetime_str() -> str: + return get_datetime().isoformat() diff --git a/c2p/framework/plugin_spec.py b/c2p/framework/plugin_spec.py new file mode 100644 index 0000000..f562dfe --- /dev/null +++ b/c2p/framework/plugin_spec.py @@ -0,0 +1,37 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from abc import ABC, abstractmethod +from typing import Any + +from pydantic import BaseModel + +from c2p.framework.models.policy import Policy +from c2p.framework.models.pvp_result import PVPResult +from c2p.framework.models.raw_result import RawResult + +PluginConfig = BaseModel + + +class PluginSpec(ABC): + + @abstractmethod + def generate_pvp_result(self, raw_result: RawResult) -> PVPResult: + pass + + @abstractmethod + def generate_pvp_policy(self, policy: Policy) -> Any: + pass diff --git a/c2p/tools/__init__.py b/c2p/tools/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/c2p/tools/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/c2p/tools/oscal_csv_to_json.py b/c2p/tools/oscal_csv_to_json.py new file mode 100644 index 0000000..f98e947 --- /dev/null +++ b/c2p/tools/oscal_csv_to_json.py @@ -0,0 +1,70 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import configparser +import pathlib +from textwrap import dedent +from typing import Optional + +import trestle.common.const as const +from trestle.common.err import TrestleError +from trestle.tasks.base_task import TaskOutcome +from trestle.tasks.csv_to_oscal_cd import CsvToOscalComponentDefinition + +from c2p.common.logging import getLogger + +logger = getLogger(__name__) + + +class OscalCsvToJson: + def __init__(self) -> None: + pass + + def generate_config(self, title: str, csv_path: pathlib.Path, output_path: pathlib.Path) -> pathlib.Path: + path = output_path / 'csv-to-oscal-cd.config' + with open(path.as_posix(), 'w') as file: + data = f""" + [task.csv-to-oscal-cd] + + title = {title} + version = 1.0 + csv-file = {csv_path.as_posix()} + output-dir = {output_path.as_posix()} + """ + file.write(dedent(data)) + return path + + def generate(self, config_path: pathlib.Path): + config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation()) + config.read_file(config_path.open('r', encoding=const.FILE_ENCODING)) + config_section: Optional[configparser.SectionProxy] = None + section_label = 'task.csv-to-oscal-cd' + if section_label in config.sections(): + config_section = config[section_label] + else: + logger.warning( + f'Config file was not configured with the appropriate section for the task: "[{section_label}]"' + ) + task = CsvToOscalComponentDefinition(config_section) + simulate_result = task.simulate() + if not (simulate_result == TaskOutcome.SIM_SUCCESS): + raise TrestleError(f'Task {section_label} reported a {simulate_result}') + + actual_result = task.execute() + if not (actual_result == TaskOutcome.SUCCESS): + raise TrestleError(f'Task {section_label} reported a {actual_result}') + + logger.info(f'Task: {section_label} executed successfully.') diff --git a/c2p/tools/viewer/__init__.py b/c2p/tools/viewer/__init__.py new file mode 100644 index 0000000..3242b47 --- /dev/null +++ b/c2p/tools/viewer/__init__.py @@ -0,0 +1,17 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from c2p.tools.viewer.template import TEMPLATE diff --git a/c2p/tools/viewer/template.py b/c2p/tools/viewer/template.py new file mode 100644 index 0000000..8939e45 --- /dev/null +++ b/c2p/tools/viewer/template.py @@ -0,0 +1,47 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +TEMPLATE = """ +{% for component in components %} +## Component: {{ component.title }} + +{% for control_result in component.control_results %} +#### Result of control {{ control_result.id }}: {{ control_result.description }} + +{% for rule_result in control_result.rule_results %} +{% if rule_result.subjects|length > 0 %} +Rule {{ rule_result.id}}: {{ rule_result.description}} +
Details +{% for subject in rule_result.subjects %} + + - Subject UUID: {{ subject.uuid }} + - Title: {{ subject.title }} + - Result: {{ subject.result}} + - Reason: + ``` + {{ subject.reason }} + ``` +{% endfor %} +
+{% else %} +Rule ID: {{ rule_result.id }} + - No subjects found +{% endif %} +{% endfor %} +--- +{% endfor %} +{% endfor %} +""" diff --git a/c2p/tools/viewer/viewer.py b/c2p/tools/viewer/viewer.py new file mode 100644 index 0000000..746cd46 --- /dev/null +++ b/c2p/tools/viewer/viewer.py @@ -0,0 +1,113 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +from typing import List, Optional + +from jinja2 import Template +from pydantic import BaseModel +from trestle.oscal.assessment_results import AssessmentResults, Observation +from trestle.oscal.common import Property +from trestle.oscal.component import ComponentDefinition, DefinedComponent + +from c2p.common.oscal import is_component_type_validation +from c2p.framework.oscal_utils import group_props_by_remarks +from c2p.tools.viewer import TEMPLATE + + +class SubjectResult(BaseModel): + uuid: str + title: str + result: str + reason: str + + +class RuleResult(BaseModel): + id: str + description: str + subjects: List[SubjectResult] = [] + + +class ControlResult(BaseModel): + id: str + rule_results: List[RuleResult] = [] + + +class RenderedComponent(BaseModel): + title: str + control_results: List[ControlResult] = [] + + +def find_observation(observations: List[Observation], check_id) -> Optional[Observation]: + for observation in observations: + for prop in observation.props: + if prop.name == 'assessment-rule-id' and prop.value == check_id: + return observation + return None + + +def get_prop_value(props: List[Property], name): + p = next(filter(lambda x: x.name == name, props), None) + return p.value if p != None else None + + +def get_pass_fail_icon(result): + if result == 'pass': + return ':white_check_mark:' + elif result == 'failure': + return ':x:' + else: + return ':warning:' + + +def render(assessment_results: AssessmentResults, component_definition: ComponentDefinition) -> str: + rule_sets = [] + for component in component_definition.components: + if is_component_type_validation(component.type): + rule_sets = rule_sets + group_props_by_remarks(component) + + components: List[DefinedComponent] = list( + filter(lambda x: not is_component_type_validation(x.type), component_definition.components) + ) + + render_components = [] + for component in components: + rendered_component = RenderedComponent(title=component.title) + for control_imple in component.control_implementations: + for imple_req in control_imple.implemented_requirements: + control_id = imple_req.control_id + control_result = ControlResult(id=control_id) + for prop in filter(lambda x: x.name == 'Rule_Id', imple_req.props): + rule_id = prop.value + rule_set = next(filter(lambda x: x['Rule_Id'] == rule_id, rule_sets), None) + if rule_set != None: + rule_result = RuleResult(id=rule_id, description=rule_set['Check_Description']) + o = find_observation(assessment_results.results[0].observations, rule_set['Check_Id']) + if o != None: + for subject in o.subjects: + result = get_prop_value(subject.props, 'result') + result = f'{result} {get_pass_fail_icon(result)}' + reason = get_prop_value(subject.props, 'reason') + sr = SubjectResult( + uuid=subject.subject_uuid, title=subject.title, result=result, reason=reason + ) + rule_result.subjects.append(sr) + control_result.rule_results.append(rule_result) + rendered_component.control_results.append(control_result) + render_components.append(rendered_component) + + tp = Template(source=TEMPLATE) + rendered = tp.render(components=render_components) + return rendered diff --git a/docs/public/images/assessment-results-md.kyverno.jpg b/docs/public/images/assessment-results-md.kyverno.jpg new file mode 100644 index 0000000..42a553a Binary files /dev/null and b/docs/public/images/assessment-results-md.kyverno.jpg differ diff --git a/docs/public/images/assessment-results-md.ocm.jpg b/docs/public/images/assessment-results-md.ocm.jpg new file mode 100644 index 0000000..79953fe Binary files /dev/null and b/docs/public/images/assessment-results-md.ocm.jpg differ diff --git a/docs/public/kyverno.md b/docs/public/kyverno.md new file mode 100644 index 0000000..9ffde2f --- /dev/null +++ b/docs/public/kyverno.md @@ -0,0 +1,63 @@ +## Plugin for Kyverno + +#### Prerequisite +- Install KinD and Kyverno 1.10 + +#### Example usage of C2P + +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 + ``` + ![assessment-results-md.kyverno.jpg](/docs/public/images/assessment-results-md.kyverno.jpg) \ No newline at end of file diff --git a/docs/public/ocm.md b/docs/public/ocm.md new file mode 100644 index 0000000..3e696b5 --- /dev/null +++ b/docs/public/ocm.md @@ -0,0 +1,194 @@ +## Plugin for OCM + +#### Prerequisite +- Install KinD and setup Open Cluster Management Hub cluster and managed clusters ([Setup OCM](#setup-ocm)) + +#### Example usage of C2P + +1. Generate OCM Policy (C2P Compliance to Policy) + ``` + python samples_public/ocm/compliance_to_policy.py -o /tmp/deliverable-policy + ``` + E.g. + ``` + $ python samples_public/ocm/compliance_to_policy.py + + tree /tmp/deliverable-policy + parameters.yaml + policy-high-scan + - compliance-high-scan + - ScanSettingBinding.high.0.yaml + - policy-generator.yaml + - kustomization.yaml + - compliance-suite-high + - ComplianceSuite.high.0.yaml + - compliance-suite-high-results + - ComplianceCheckResult.noname.0.yaml + policy-deployment + - policy-generator.yaml + - kustomization.yaml + - policy-nginx-deployment + - Deployment.nginx-deployment.0.yaml + policy-disallowed-roles + - policy-disallowed-roles-sample-role + - Role.noname.0.yaml + - policy-generator.yaml + - kustomization.yaml + policy-generator.yaml + ``` +1. Deploy the generated policies + ``` + kustomize build --enable-alpha-plugins /tmp/deliverable-policy | kubectl apply -f - + ``` + 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 statuses at hub cluster + ``` + $ kubectl get policy -A + NAMESPACE NAME REMEDIATION ACTION COMPLIANCE STATE AGE + c2p policy-deployment inform NonCompliant 55s + c2p policy-disallowed-roles inform Compliant 55s + c2p policy-high-scan inform NonCompliant 55s + cluster1 c2p.policy-deployment inform NonCompliant 54s + cluster1 c2p.policy-disallowed-roles inform Compliant 54s + cluster1 c2p.policy-high-scan inform NonCompliant 54s + cluster2 c2p.policy-deployment inform NonCompliant 54s + cluster2 c2p.policy-disallowed-roles inform Compliant 54s + cluster2 c2p.policy-high-scan inform NonCompliant 54s + ``` +1. Collect policies as PVP Raw results + ``` + kubectl get policy -A -o yaml > /tmp/policies.policy.open-cluster-management.io.yaml + kubectl get placementdecisions -A -o yaml > /tmp/placementdecisions.cluster.open-cluster-management.io.yaml + kubectl get policysets -A -o yaml > /tmp/policysets.policy.open-cluster-management.io.yaml + ``` +1. Generate Assessment Result (C2P Result to Compliance) + ``` + python samples_public/ocm/result_to_compliance.py \ + -p /tmp/policies.policy.open-cluster-management.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/ocm/component-definition.json -o /tmp/assessment_results.md + ``` + ![assessment-results-md.ocm.jpg](/docs/public/images/assessment-results-md.ocm.jpg) + +## Setup OCM +1. Prerequisite + - kind + ``` + $ kind version + kind v0.19.0 go1.20.4 darwin/arm64 + ``` + - clusteradm + ``` + $ clusteradm version + client version :v0.8.1-0-g3aea9c5 + server release version :v1.26.0 + default bundle version :0.13.1 + ``` +1. Create 3 KinD clusters (hub, cluster1 and 2) + ``` + kind create cluster --name hub --image kindest/node:v1.26.0 --wait 5m + kind create cluster --name cluster1 --image kindest/node:v1.26.0 --wait 5m + kind create cluster --name cluster2 --image kindest/node:v1.26.0 --wait 5m + ``` +1. Install OCM Hub + ``` + kubectl config use-context kind-hub + clusteradm init --wait + ``` +1. Join clusters to Hub + ``` + kubectl config use-context kind-hub + token=`clusteradm get token | head -n 1 | clusteradm get token | head -n 1 | cut -f 2 -d "="` + server=`kubectl config view --minify -o=jsonpath='{.clusters[0].cluster.server}'` + kubectl config use-context kind-cluster1 + clusteradm join --hub-token $token --hub-apiserver $server --cluster-name cluster1 --force-internal-endpoint-lookup --wait + kubectl config use-context kind-cluster2 + clusteradm join --hub-token $token --hub-apiserver $server --cluster-name cluster2 --force-internal-endpoint-lookup --wait + kubectl config use-context kind-hub + clusteradm accept --clusters cluster2 + ``` +1. Enable governance-policy-framework + ``` + kubectl config use-context kind-hub + clusteradm install hub-addon --names governance-policy-framework + kubectl -n open-cluster-management wait deployment --all --for=condition=Available --timeout 3m + ``` +1. Deploy synchronization components to manages clusters + ``` + kubectl config use-context kind-hub + clusteradm addon enable --names governance-policy-framework --clusters cluster1,cluster2 + for c in cluster1 cluster2 + do + kubectl -n $c wait managedclusteraddon --all --for=condition=Available --timeout 3m + done + ``` +1. Deploy configuration policy controller to the managed cluster(s) + ``` + kubectl config use-context kind-hub + clusteradm addon enable --names config-policy-controller --clusters cluster1,cluster2 + for c in cluster1 cluster2 + do + kubectl -n $c wait managedclusteraddon --all --for=condition=Available --timeout 3m + done + ``` +1. Labeling "environment=dev" to managed clusters + ``` + kubectl config use-context kind-hub + for c in cluster1 cluster2 + do + kubectl label managedcluster $c environment=dev + done + ``` +1. Create managedclusterset + ``` + kubectl config use-context kind-hub + kubectl apply -f - << EOL + apiVersion: cluster.open-cluster-management.io/v1beta2 + kind: ManagedClusterSet + metadata: + name: myclusterset + spec: + clusterSelector: + labelSelector: + matchExpressions: + - key: environment + operator: In + values: + - dev + selectorType: LabelSelector + EOL + ``` +1. Create "c2p" namespace and bind managed clusters to "c2p" namespace + ``` + kubectl config use-context kind-hub + kubectl create ns c2p + clusteradm clusterset bind myclusterset --namespace c2p + ``` +1. The final cluster configuration + ``` + $ clusteradm get clustersets + + └── + │ ├── + │ ├── 2 ManagedClusters selected + │ ├── [cluster1 cluster2] + └── + │ ├── + │ ├── 2 ManagedClusters selected + │ ├── [cluster1 cluster2] + └── + └── c2p + └── 2 ManagedClusters selected + └── [cluster1 cluster2] + ``` diff --git a/.dockerignore b/go/.dockerignore similarity index 100% rename from .dockerignore rename to go/.dockerignore diff --git a/go/.gitignore b/go/.gitignore new file mode 100644 index 0000000..a644dd5 --- /dev/null +++ b/go/.gitignore @@ -0,0 +1,43 @@ + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib +bin +testbin/* +Dockerfile.cross + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Kubernetes Generated files - skip generated files, except for vendored files + +!vendor/**/zz_generated.* + +# editor and IDE paraphernalia +.idea +*.swp +*.swo +*~ + + +# IDE +.vscode +.idea + +# Output of gorelease +dist + +# ignore output by test +/**/_test + +# +policy-collection +out +work +kubeconfig.* \ No newline at end of file diff --git a/.golangci.yaml b/go/.golangci.yaml similarity index 100% rename from .golangci.yaml rename to go/.golangci.yaml diff --git a/.goreleaser.yaml b/go/.goreleaser.yaml similarity index 100% rename from .goreleaser.yaml rename to go/.goreleaser.yaml diff --git a/Dockerfile b/go/Dockerfile similarity index 100% rename from Dockerfile rename to go/Dockerfile diff --git a/go/Makefile b/go/Makefile new file mode 100644 index 0000000..7498510 --- /dev/null +++ b/go/Makefile @@ -0,0 +1,324 @@ +# VERSION defines the project version for the bundle. +# Update this value when you upgrade the version of your project. +# To re-generate a bundle for another specific version without changing the standard setup, you can: +# - use the VERSION as arg of the bundle target (e.g make bundle VERSION=0.0.2) +# - use environment variables to overwrite this value (e.g export VERSION=0.0.2) +VERSION ?= 0.0.1 + +# CHANNELS define the bundle channels used in the bundle. +# Add a new line here if you would like to change its default config. (E.g CHANNELS = "candidate,fast,stable") +# To re-generate a bundle for other specific channels without changing the standard setup, you can: +# - use the CHANNELS as arg of the bundle target (e.g make bundle CHANNELS=candidate,fast,stable) +# - use environment variables to overwrite this value (e.g export CHANNELS="candidate,fast,stable") +ifneq ($(origin CHANNELS), undefined) +BUNDLE_CHANNELS := --channels=$(CHANNELS) +endif + +# DEFAULT_CHANNEL defines the default channel used in the bundle. +# Add a new line here if you would like to change its default config. (E.g DEFAULT_CHANNEL = "stable") +# To re-generate a bundle for any other default channel without changing the default setup, you can: +# - use the DEFAULT_CHANNEL as arg of the bundle target (e.g make bundle DEFAULT_CHANNEL=stable) +# - use environment variables to overwrite this value (e.g export DEFAULT_CHANNEL="stable") +ifneq ($(origin DEFAULT_CHANNEL), undefined) +BUNDLE_DEFAULT_CHANNEL := --default-channel=$(DEFAULT_CHANNEL) +endif +BUNDLE_METADATA_OPTS ?= $(BUNDLE_CHANNELS) $(BUNDLE_DEFAULT_CHANNEL) + +# IMAGE_TAG_BASE defines the docker.io namespace and part of the image name for remote images. +# This variable is used to construct full image tags for bundle and catalog images. +# +# For example, running 'make bundle-build bundle-push catalog-build catalog-push' will build and push both +# github.com/compliance-to-policy-bundle:$VERSION and github.com/compliance-to-policy-catalog:$VERSION. +IMAGE_TAG_BASE ?= github.com/compliance-to-policy + +# BUNDLE_IMG defines the image:tag used for the bundle. +# You can use it as an arg. (E.g make bundle-build BUNDLE_IMG=/:) +BUNDLE_IMG ?= $(IMAGE_TAG_BASE)-bundle:v$(VERSION) + +# BUNDLE_GEN_FLAGS are the flags passed to the operator-sdk generate bundle command +BUNDLE_GEN_FLAGS ?= -q --overwrite --version $(VERSION) $(BUNDLE_METADATA_OPTS) + +# USE_IMAGE_DIGESTS defines if images are resolved via tags or digests +# You can enable this value if you would like to use SHA Based Digests +# To enable set flag to true +USE_IMAGE_DIGESTS ?= false +ifeq ($(USE_IMAGE_DIGESTS), true) + BUNDLE_GEN_FLAGS += --use-image-digests +endif + +# Image URL to use all building/pushing image targets +IMG ?= controller:latest +# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary. +ENVTEST_K8S_VERSION = 1.25.0 + +# Get the currently used golang install path (in GOPATH/bin, unless GOBIN is set) +ifeq (,$(shell go env GOBIN)) +GOBIN=$(shell go env GOPATH)/bin +else +GOBIN=$(shell go env GOBIN) +endif + +# Setting SHELL to bash allows bash commands to be executed by recipes. +# Options are set to exit when a recipe line exits non-zero or a piped command fails. +SHELL = /usr/bin/env bash -o pipefail +.SHELLFLAGS = -ec + +GOOS ?= darwin +GOARCH ?= arm64 +GIT_TAG := $(shell git describe --tags --abbrev=0) +VERSION_FROM_GIT_TAG := $(shell echo "$(GIT_TAG)" | sed 's/^go\///') +DIRTY := $(shell [ -n "$(git status -s)" ] && echo '-snapshot') +REPO_NAME := $(shell git remote get-url origin | sed -r 's/.*:(.*)\.git/\1/') +VERSIONED_SUFFIX := $(if $(DIRTY),$(VERSION_FROM_GIT_TAG)_$(GOOS)_$(GOARCH),$(VERSION_FROM_GIT_TAG)_SNAPSHOT_$(GOOS)_$(GOARCH)) + +repo_name: + echo $(REPO_NAME) + +.PHONY: all +all: build + +.PHONY: build +build: + GOOS=$(GOOS) GOARCH=$(GOARCH) go build -o ./bin/c2pcli_$(VERSIONED_SUFFIX) ./cmd/c2pcli + +.PHONY: test +test: + go test ./pkg/... -coverprofile cover.out + +artifact: build + mkdir -p ./dist/artifacts + tar zcvf ./dist/artifacts/c2pcli_$(VERSIONED_SUFFIX).tar.gz -C ./bin c2pcli_$(VERSIONED_SUFFIX) + shasum -a 256 ./dist/artifacts/c2pcli_$(VERSIONED_SUFFIX).tar.gz > ./dist/artifacts/c2pcli_$(VERSIONED_SUFFIX).sha256 + +# echo $PAT | gh auth login --with-token -h github.com +release: GITHUB_HOST ?= github.com +release: artifact + @(gh release --repo $(GITHUB_HOST)/$(REPO_NAME) view $(GIT_TAG) ;\ + if [[ "$$?" != "0" ]];then \ + echo create release $(GIT_TAG) ;\ + gh release --repo $(GITHUB_HOST)/$(REPO_NAME) create $(GIT_TAG) --generate-notes ;\ + fi) + gh release --repo $(GITHUB_HOST)/$(REPO_NAME) upload $(GIT_TAG) ./dist/artifacts/c2pcli_$(VERSIONED_SUFFIX).* + +## OLM + +##@ General + +# The help target prints out all targets with their descriptions organized +# beneath their categories. The categories are represented by '##@' and the +# target descriptions by '##'. The awk commands is responsible for reading the +# entire set of makefiles included in this invocation, looking for lines of the +# file as xyz: ## something, and then pretty-format the target and help. Then, +# if there's a line with ##@ something, that gets pretty-printed as a category. +# More info on the usage of ANSI control characters for terminal formatting: +# https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters +# More info on the awk command: +# http://linuxcommand.org/lc3_adv_awk.php + +.PHONY: help +help: ## Display this help. + @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m\033[0m\n"} /^[a-zA-Z_0-9-]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) + +##@ Development + +.PHONY: manifests +manifests: controller-gen ## Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects. + $(CONTROLLER_GEN) rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases + +.PHONY: generate +generate: controller-gen ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. + $(CONTROLLER_GEN) object:headerFile="hack/boilerplate.go.txt" paths="./..." + +.PHONY: fmt +fmt: ## Run go fmt against code. + go fmt ./... + +.PHONY: vet +vet: ## Run go vet against code. + go vet ./... + +.PHONY: test-controllers +test-controllers: manifests generate fmt vet envtest ## Run tests. + KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./controllers/... -coverprofile cover.controllers.out -p=1 + +##@ Build + +.PHONY: build-controllers +build-controllers: generate fmt vet ## Build manager binary. + go build -o bin/manager main.go + +.PHONY: run +run: manifests generate fmt vet ## Run a controller from your host. + go run ./main.go + +# If you wish built the manager image targeting other platforms you can use the --platform flag. +# (i.e. docker build --platform linux/arm64 ). However, you must enable docker buildKit for it. +# More info: https://docs.docker.com/develop/develop-images/build_enhancements/ +.PHONY: docker-build +docker-build: test-controllers ## Build docker image with the manager. + docker build -t ${IMG} . + +.PHONY: docker-push +docker-push: ## Push docker image with the manager. + docker push ${IMG} + +# PLATFORMS defines the target platforms for the manager image be build to provide support to multiple +# architectures. (i.e. make docker-buildx IMG=myregistry/mypoperator:0.0.1). To use this option you need to: +# - able to use docker buildx . More info: https://docs.docker.com/build/buildx/ +# - have enable BuildKit, More info: https://docs.docker.com/develop/develop-images/build_enhancements/ +# - be able to push the image for your registry (i.e. if you do not inform a valid value via IMG=> than the export will fail) +# To properly provided solutions that supports more than one platform you should use this option. +PLATFORMS ?= linux/arm64,linux/amd64,linux/s390x,linux/ppc64le +.PHONY: docker-buildx +docker-buildx: test-controllers ## Build and push docker image for the manager for cross-platform support + # copy existing Dockerfile and insert --platform=${BUILDPLATFORM} into Dockerfile.cross, and preserve the original Dockerfile + sed -e '1 s/\(^FROM\)/FROM --platform=\$$\{BUILDPLATFORM\}/; t' -e ' 1,// s//FROM --platform=\$$\{BUILDPLATFORM\}/' Dockerfile > Dockerfile.cross + - docker buildx create --name project-v3-builder + docker buildx use project-v3-builder + - docker buildx build --push --platform=$(PLATFORMS) --tag ${IMG} -f Dockerfile.cross + - docker buildx rm project-v3-builder + rm Dockerfile.cross + +##@ Deployment + +ifndef ignore-not-found + ignore-not-found = false +endif + +.PHONY: install +install: manifests kustomize ## Install CRDs into the K8s cluster specified in ~/.kube/config. + $(KUSTOMIZE) build config/crd | kubectl apply -f - + +.PHONY: uninstall +uninstall: manifests kustomize ## Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. + $(KUSTOMIZE) build config/crd | kubectl delete --ignore-not-found=$(ignore-not-found) -f - + +## For development in a non OCM Hub +.PHONY: install-ocm-related-crds +install-ocm-related-crds: + kubectl apply -f config/ocm + +.PHONY: uninstall-ocm-related-crds +uninstall-ocm-related-crds: + kubectl delete --ignore-not-found=$(ignore-not-found) -f config/ocm + +.PHONY: deploy +deploy: manifests kustomize ## Deploy controller to the K8s cluster specified in ~/.kube/config. + cd config/manager && $(KUSTOMIZE) edit set image controller=${IMG} + $(KUSTOMIZE) build config/default | kubectl apply -f - + +.PHONY: undeploy +undeploy: ## Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion. + $(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f - + +.PHONY: get-policy-resources +get-policy-resources: + kubectl get policy,placementrule,placementbinding + +.PHONY: delete-policy-resources +delete-all-policy-resources: + kubectl delete policy,placementrule,placementbinding --all + +##@ Build Dependencies + +## Location to install dependencies to +LOCALBIN ?= $(shell pwd)/bin +$(LOCALBIN): + mkdir -p $(LOCALBIN) + +## Tool Binaries +KUSTOMIZE ?= $(LOCALBIN)/kustomize +CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen +ENVTEST ?= $(LOCALBIN)/setup-envtest + +## Tool Versions +KUSTOMIZE_VERSION ?= v4.5.7 +CONTROLLER_TOOLS_VERSION ?= v0.10.0 + +KUSTOMIZE_INSTALL_SCRIPT ?= "https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh" +.PHONY: kustomize +kustomize: $(KUSTOMIZE) ## Download kustomize locally if necessary. +$(KUSTOMIZE): $(LOCALBIN) + test -s $(LOCALBIN)/kustomize || { curl -Ss $(KUSTOMIZE_INSTALL_SCRIPT) | bash -s -- $(subst v,,$(KUSTOMIZE_VERSION)) $(LOCALBIN); } + +.PHONY: controller-gen +controller-gen: $(CONTROLLER_GEN) ## Download controller-gen locally if necessary. +$(CONTROLLER_GEN): $(LOCALBIN) + test -s $(LOCALBIN)/controller-gen || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-tools/cmd/controller-gen@$(CONTROLLER_TOOLS_VERSION) + +.PHONY: envtest +envtest: $(ENVTEST) ## Download envtest-setup locally if necessary. +$(ENVTEST): $(LOCALBIN) + test -s $(LOCALBIN)/setup-envtest || GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest + +.PHONY: bundle +bundle: manifests kustomize ## Generate bundle manifests and metadata, then validate generated files. + operator-sdk generate kustomize manifests -q + cd config/manager && $(KUSTOMIZE) edit set image controller=$(IMG) + $(KUSTOMIZE) build config/manifests | operator-sdk generate bundle $(BUNDLE_GEN_FLAGS) + operator-sdk bundle validate ./bundle + +.PHONY: bundle-build +bundle-build: ## Build the bundle image. + docker build -f bundle.Dockerfile -t $(BUNDLE_IMG) . + +.PHONY: bundle-push +bundle-push: ## Push the bundle image. + $(MAKE) docker-push IMG=$(BUNDLE_IMG) + +.PHONY: opm +OPM = ./bin/opm +opm: ## Download opm locally if necessary. +ifeq (,$(wildcard $(OPM))) +ifeq (,$(shell which opm 2>/dev/null)) + @{ \ + set -e ;\ + mkdir -p $(dir $(OPM)) ;\ + OS=$(shell go env GOOS) && ARCH=$(shell go env GOARCH) && \ + curl -sSLo $(OPM) https://github.com/operator-framework/operator-registry/releases/download/v1.23.0/$${OS}-$${ARCH}-opm ;\ + chmod +x $(OPM) ;\ + } +else +OPM = $(shell which opm) +endif +endif + +# A comma-separated list of bundle images (e.g. make catalog-build BUNDLE_IMGS=example.com/operator-bundle:v0.1.0,example.com/operator-bundle:v0.2.0). +# These images MUST exist in a registry and be pull-able. +BUNDLE_IMGS ?= $(BUNDLE_IMG) + +# The image tag given to the resulting catalog image (e.g. make catalog-build CATALOG_IMG=example.com/operator-catalog:v0.2.0). +CATALOG_IMG ?= $(IMAGE_TAG_BASE)-catalog:v$(VERSION) + +# Set CATALOG_BASE_IMG to an existing catalog image tag to add $BUNDLE_IMGS to that image. +ifneq ($(origin CATALOG_BASE_IMG), undefined) +FROM_INDEX_OPT := --from-index $(CATALOG_BASE_IMG) +endif + +# Build a catalog image by adding bundle images to an empty catalog using the operator package manager tool, 'opm'. +# This recipe invokes 'opm' in 'semver' bundle add mode. For more information on add modes, see: +# https://github.com/operator-framework/community-operators/blob/7f1438c/docs/packaging-operator.md#updating-your-existing-operator +.PHONY: catalog-build +catalog-build: opm ## Build a catalog image. + $(OPM) index add --container-tool docker --mode semver --tag $(CATALOG_IMG) --bundles $(BUNDLE_IMGS) $(FROM_INDEX_OPT) + +# Push the catalog image. +.PHONY: catalog-push +catalog-push: ## Push a catalog image. + $(MAKE) docker-push IMG=$(CATALOG_IMG) + +### +.PHONY: compose-v2 +compose-v2: bin/compose-v2.linux_amd64 bin/compose-v2.darwin_amd64 bin/compose-v2.darwin_arm64 + +bin/compose-v2.linux_amd64: + GOOS=linux GOARCH=amd64 go build -o bin/compose-v2.linux_amd64 ./cmd/compose-v2 + +bin/compose-v2.darwin_amd64: + GOOS=darwin GOARCH=amd64 go build -o bin/compose-v2.darwin_amd64 ./cmd/compose-v2 + +bin/compose-v2.darwin_arm64: + GOOS=darwin GOARCH=arm64 go build -o bin/compose-v2.darwin_arm64 ./cmd/compose-v2 + +bin/compose-v2.%.gz: bin/compose-v2.% + gzip ./bin/compose-v2.$* diff --git a/PROJECT b/go/PROJECT similarity index 73% rename from PROJECT rename to go/PROJECT index ac2e5f9..0f866d0 100644 --- a/PROJECT +++ b/go/PROJECT @@ -5,7 +5,7 @@ plugins: manifests.sdk.operatorframework.io/v2: {} scorecard.sdk.operatorframework.io/v2: {} projectName: compliance-to-policy -repo: github.com/IBM/compliance-to-policy +repo: github.com/oscal-compass/compliance-to-policy/go resources: - api: crdVersion: v1 @@ -14,7 +14,7 @@ resources: domain: github.com group: compliance-to-policy kind: ComplianceDeployment - path: github.com/IBM/compliance-to-policy/api/v1alpha1 + path: github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1 version: v1alpha1 - api: crdVersion: v1 @@ -23,6 +23,6 @@ resources: domain: github.com group: compliance-to-policy kind: ControlReference - path: github.com/IBM/compliance-to-policy/api/v1alpha1 + path: github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1 version: v1alpha1 version: "3" diff --git a/go/README.md b/go/README.md new file mode 100644 index 0000000..4608f2a --- /dev/null +++ b/go/README.md @@ -0,0 +1,52 @@ +# compliance-to-policy +Compliance-to-Policy (C2P) provides the framework to bridge Compliance administration and Policy administration by [OSCAL](https://pages.nist.gov/OSCAL/). OSCAL (Open Security Controls Assessment Language) is a standardized framework developed by NIST for expressing and automating the assessment and management of security controls in machine-readable format (xml, json, yaml) + +![C2P Overview](/go/docs/images/e2e-pm.png) + +## Usage of C2P CLI +``` +$ c2pcli -h +C2P CLI + +Usage: + c2pcli [flags] + c2pcli [command] + +Available Commands: + completion Generate the autocompletion script for the specified shell + help Help about any command + kyverno C2P CLI Kyverno plugin + ocm C2P CLI OCM plugin + version Display version + +Flags: + -h, --help help for c2pcli + +Use "c2pcli [command] --help" for more information about a command. +``` + +C2P is targeting a plugin architecture to cover not only OCM Policy Framework but also other types of PVPs. +Please go to the docs for each usage. +- [C2P for OCM](/go/docs/ocm/README.md) +- [C2P for Kyverno](/go/docs/kyverno/README.md) + +## Build at local +``` +make build +``` +``` +./bin/c2pcli___ -h +``` + +## Test +``` +make test +``` + +## Release +1. Create a git tag of the following format `go/` (e.g. `go/v0.1.2`) +1. Run release command + ``` + echo $PAT | gh auth login --with-token -h github.com + make release + ``` \ No newline at end of file diff --git a/api/v1alpha1/checkpolicy_types.go b/go/api/v1alpha1/checkpolicy_types.go similarity index 100% rename from api/v1alpha1/checkpolicy_types.go rename to go/api/v1alpha1/checkpolicy_types.go diff --git a/api/v1alpha1/compliancedeployment_types.go b/go/api/v1alpha1/compliancedeployment_types.go similarity index 100% rename from api/v1alpha1/compliancedeployment_types.go rename to go/api/v1alpha1/compliancedeployment_types.go diff --git a/api/v1alpha1/compliancereport_types.go b/go/api/v1alpha1/compliancereport_types.go similarity index 97% rename from api/v1alpha1/compliancereport_types.go rename to go/api/v1alpha1/compliancereport_types.go index d0f144f..df5bddb 100644 --- a/api/v1alpha1/compliancereport_types.go +++ b/go/api/v1alpha1/compliancereport_types.go @@ -17,7 +17,7 @@ limitations under the License. package v1alpha1 import ( - wgpolicyk8sv1alpha2 "github.com/IBM/compliance-to-policy/controllers/wgpolicyk8s.io/v1alpha2" + wgpolicyk8sv1alpha2 "github.com/oscal-compass/compliance-to-policy/go/controllers/wgpolicyk8s.io/v1alpha2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) diff --git a/api/v1alpha1/controlreference_common_types.go b/go/api/v1alpha1/controlreference_common_types.go similarity index 100% rename from api/v1alpha1/controlreference_common_types.go rename to go/api/v1alpha1/controlreference_common_types.go diff --git a/api/v1alpha1/controlreference_types.go b/go/api/v1alpha1/controlreference_types.go similarity index 100% rename from api/v1alpha1/controlreference_types.go rename to go/api/v1alpha1/controlreference_types.go diff --git a/api/v1alpha1/controlreferencekcp_types.go b/go/api/v1alpha1/controlreferencekcp_types.go similarity index 100% rename from api/v1alpha1/controlreferencekcp_types.go rename to go/api/v1alpha1/controlreferencekcp_types.go diff --git a/api/v1alpha1/groupversion_info.go b/go/api/v1alpha1/groupversion_info.go similarity index 100% rename from api/v1alpha1/groupversion_info.go rename to go/api/v1alpha1/groupversion_info.go diff --git a/api/v1alpha1/resultcollector_types.go b/go/api/v1alpha1/resultcollector_types.go similarity index 100% rename from api/v1alpha1/resultcollector_types.go rename to go/api/v1alpha1/resultcollector_types.go diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/go/api/v1alpha1/zz_generated.deepcopy.go similarity index 100% rename from api/v1alpha1/zz_generated.deepcopy.go rename to go/api/v1alpha1/zz_generated.deepcopy.go diff --git a/cmd/c2pcli/cmd/cmd.go b/go/cmd/c2pcli/cmd/cmd.go similarity index 88% rename from cmd/c2pcli/cmd/cmd.go rename to go/cmd/c2pcli/cmd/cmd.go index 5bc6c19..72e43c4 100644 --- a/cmd/c2pcli/cmd/cmd.go +++ b/go/cmd/c2pcli/cmd/cmd.go @@ -19,8 +19,8 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/options" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/subcommands" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/options" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/subcommands" ) func New() *cobra.Command { diff --git a/cmd/c2pcli/main.go b/go/cmd/c2pcli/main.go similarity index 94% rename from cmd/c2pcli/main.go rename to go/cmd/c2pcli/main.go index ed58863..0d6109b 100644 --- a/cmd/c2pcli/main.go +++ b/go/cmd/c2pcli/main.go @@ -20,7 +20,7 @@ import ( "fmt" "os" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/cmd" "github.com/spf13/cobra" ) diff --git a/cmd/c2pcli/options/options.go b/go/cmd/c2pcli/options/options.go similarity index 100% rename from cmd/c2pcli/options/options.go rename to go/cmd/c2pcli/options/options.go diff --git a/cmd/c2pcli/subcommands/kyverno.go b/go/cmd/c2pcli/subcommands/kyverno.go similarity index 73% rename from cmd/c2pcli/subcommands/kyverno.go rename to go/cmd/c2pcli/subcommands/kyverno.go index 4f8761b..ea7e570 100644 --- a/cmd/c2pcli/subcommands/kyverno.go +++ b/go/cmd/c2pcli/subcommands/kyverno.go @@ -19,10 +19,10 @@ package subcommands import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/options" - oscal2policycmd "github.com/IBM/compliance-to-policy/cmd/kyverno/oscal2policy/cmd" - result2oscalcmd "github.com/IBM/compliance-to-policy/cmd/kyverno/result2oscal/cmd" - toolscmd "github.com/IBM/compliance-to-policy/cmd/kyverno/tools/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/options" + oscal2policycmd "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/oscal2policy/cmd" + result2oscalcmd "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/result2oscal/cmd" + toolscmd "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/tools/cmd" ) func NewKyvernoSubCommand() *cobra.Command { diff --git a/cmd/c2pcli/subcommands/ocm.go b/go/cmd/c2pcli/subcommands/ocm.go similarity index 73% rename from cmd/c2pcli/subcommands/ocm.go rename to go/cmd/c2pcli/subcommands/ocm.go index d3a7cec..2871e1c 100644 --- a/cmd/c2pcli/subcommands/ocm.go +++ b/go/cmd/c2pcli/subcommands/ocm.go @@ -19,10 +19,10 @@ package subcommands import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/options" - oscal2policycmd "github.com/IBM/compliance-to-policy/cmd/ocm/oscal2policy/cmd" - result2oscalcmd "github.com/IBM/compliance-to-policy/cmd/ocm/result2oscal/cmd" - toolscmd "github.com/IBM/compliance-to-policy/cmd/ocm/tools/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/options" + oscal2policycmd "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/oscal2policy/cmd" + result2oscalcmd "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/result2oscal/cmd" + toolscmd "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/tools/cmd" ) func NewOcmSubCommand() *cobra.Command { diff --git a/cmd/decompose/decompose.go b/go/cmd/decompose/decompose.go similarity index 91% rename from cmd/decompose/decompose.go rename to go/cmd/decompose/decompose.go index 169da3c..e247d89 100644 --- a/cmd/decompose/decompose.go +++ b/go/cmd/decompose/decompose.go @@ -20,8 +20,8 @@ import ( "flag" "os" - cmdparse "github.com/IBM/compliance-to-policy/cmd/parse/modules" - "github.com/IBM/compliance-to-policy/pkg/decomposer" + cmdparse "github.com/oscal-compass/compliance-to-policy/go/cmd/parse/modules" + "github.com/oscal-compass/compliance-to-policy/go/pkg/decomposer" cp "github.com/otiai10/copy" "go.uber.org/zap" ) diff --git a/cmd/kyverno/oscal2policy/cmd/cmd.go b/go/cmd/kyverno/oscal2policy/cmd/cmd.go similarity index 86% rename from cmd/kyverno/oscal2policy/cmd/cmd.go rename to go/cmd/kyverno/oscal2policy/cmd/cmd.go index 6c4fa58..2094f74 100644 --- a/cmd/kyverno/oscal2policy/cmd/cmd.go +++ b/go/cmd/kyverno/oscal2policy/cmd/cmd.go @@ -21,10 +21,10 @@ import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/kyverno/oscal2policy/options" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/kyverno" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/oscal2policy/options" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/kyverno" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) func New() *cobra.Command { diff --git a/cmd/ocm/result2oscal/main.go b/go/cmd/kyverno/oscal2policy/main.go similarity index 89% rename from cmd/ocm/result2oscal/main.go rename to go/cmd/kyverno/oscal2policy/main.go index 63064d6..e009b8a 100644 --- a/cmd/ocm/result2oscal/main.go +++ b/go/cmd/kyverno/oscal2policy/main.go @@ -19,7 +19,7 @@ package main import ( "os" - "github.com/IBM/compliance-to-policy/cmd/ocm/result2oscal/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/oscal2policy/cmd" ) func main() { diff --git a/cmd/kyverno/oscal2policy/options/options.go b/go/cmd/kyverno/oscal2policy/options/options.go similarity index 100% rename from cmd/kyverno/oscal2policy/options/options.go rename to go/cmd/kyverno/oscal2policy/options/options.go diff --git a/cmd/kyverno/result2oscal/cmd/cmd.go b/go/cmd/kyverno/result2oscal/cmd/cmd.go similarity index 86% rename from cmd/kyverno/result2oscal/cmd/cmd.go rename to go/cmd/kyverno/result2oscal/cmd/cmd.go index 4fcaae7..7a44ada 100644 --- a/cmd/kyverno/result2oscal/cmd/cmd.go +++ b/go/cmd/kyverno/result2oscal/cmd/cmd.go @@ -19,10 +19,10 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/kyverno/result2oscal/options" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/kyverno" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/result2oscal/options" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/kyverno" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) func New() *cobra.Command { diff --git a/cmd/kyverno/oscal2policy/main.go b/go/cmd/kyverno/result2oscal/main.go similarity index 89% rename from cmd/kyverno/oscal2policy/main.go rename to go/cmd/kyverno/result2oscal/main.go index 4e4b766..165ede1 100644 --- a/cmd/kyverno/oscal2policy/main.go +++ b/go/cmd/kyverno/result2oscal/main.go @@ -19,7 +19,7 @@ package main import ( "os" - "github.com/IBM/compliance-to-policy/cmd/kyverno/oscal2policy/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/result2oscal/cmd" ) func main() { diff --git a/cmd/kyverno/result2oscal/options/options.go b/go/cmd/kyverno/result2oscal/options/options.go similarity index 100% rename from cmd/kyverno/result2oscal/options/options.go rename to go/cmd/kyverno/result2oscal/options/options.go diff --git a/cmd/kyverno/tools/cmd/cmd.go b/go/cmd/kyverno/tools/cmd/cmd.go similarity index 77% rename from cmd/kyverno/tools/cmd/cmd.go rename to go/cmd/kyverno/tools/cmd/cmd.go index ab035d4..ec9585f 100644 --- a/cmd/kyverno/tools/cmd/cmd.go +++ b/go/cmd/kyverno/tools/cmd/cmd.go @@ -19,10 +19,10 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/options" - kyvernocmd "github.com/IBM/compliance-to-policy/cmd/kyverno/tools/subcommands/kyverno" - oscal2posturecmd "github.com/IBM/compliance-to-policy/cmd/pvpcommon/oscal2posture/cmd" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/options" + kyvernocmd "github.com/oscal-compass/compliance-to-policy/go/cmd/kyverno/tools/subcommands/kyverno" + oscal2posturecmd "github.com/oscal-compass/compliance-to-policy/go/cmd/pvpcommon/oscal2posture/cmd" + "github.com/oscal-compass/compliance-to-policy/go/pkg" ) func New() *cobra.Command { diff --git a/cmd/kyverno/tools/options/options.go b/go/cmd/kyverno/tools/options/options.go similarity index 100% rename from cmd/kyverno/tools/options/options.go rename to go/cmd/kyverno/tools/options/options.go diff --git a/cmd/kyverno/tools/subcommands/kyverno/cmd.go b/go/cmd/kyverno/tools/subcommands/kyverno/cmd.go similarity index 97% rename from cmd/kyverno/tools/subcommands/kyverno/cmd.go rename to go/cmd/kyverno/tools/subcommands/kyverno/cmd.go index 94e2314..0cc0077 100644 --- a/cmd/kyverno/tools/subcommands/kyverno/cmd.go +++ b/go/cmd/kyverno/tools/subcommands/kyverno/cmd.go @@ -19,8 +19,8 @@ package kyverno import ( "fmt" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/kyverno" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/kyverno" cp "github.com/otiai10/copy" "github.com/spf13/cobra" "go.uber.org/zap" diff --git a/cmd/kyverno/tools/subcommands/kyverno/options.go b/go/cmd/kyverno/tools/subcommands/kyverno/options.go similarity index 100% rename from cmd/kyverno/tools/subcommands/kyverno/options.go rename to go/cmd/kyverno/tools/subcommands/kyverno/options.go diff --git a/cmd/ocm/oscal2policy/cmd/cmd.go b/go/cmd/ocm/oscal2policy/cmd/cmd.go similarity index 89% rename from cmd/ocm/oscal2policy/cmd/cmd.go rename to go/cmd/ocm/oscal2policy/cmd/cmd.go index c3df179..0f63824 100644 --- a/cmd/ocm/oscal2policy/cmd/cmd.go +++ b/go/cmd/ocm/oscal2policy/cmd/cmd.go @@ -22,10 +22,10 @@ import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/ocm/oscal2policy/options" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/ocm" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/oscal2policy/options" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/ocm" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) func New() *cobra.Command { diff --git a/cmd/kyverno/result2oscal/main.go b/go/cmd/ocm/oscal2policy/main.go similarity index 89% rename from cmd/kyverno/result2oscal/main.go rename to go/cmd/ocm/oscal2policy/main.go index adcb3ba..4f95ce6 100644 --- a/cmd/kyverno/result2oscal/main.go +++ b/go/cmd/ocm/oscal2policy/main.go @@ -19,7 +19,7 @@ package main import ( "os" - "github.com/IBM/compliance-to-policy/cmd/kyverno/result2oscal/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/oscal2policy/cmd" ) func main() { diff --git a/cmd/ocm/oscal2policy/options/options.go b/go/cmd/ocm/oscal2policy/options/options.go similarity index 100% rename from cmd/ocm/oscal2policy/options/options.go rename to go/cmd/ocm/oscal2policy/options/options.go diff --git a/cmd/ocm/result2oscal/cmd/cmd.go b/go/cmd/ocm/result2oscal/cmd/cmd.go similarity index 86% rename from cmd/ocm/result2oscal/cmd/cmd.go rename to go/cmd/ocm/result2oscal/cmd/cmd.go index 87cb305..5bd41ba 100644 --- a/cmd/ocm/result2oscal/cmd/cmd.go +++ b/go/cmd/ocm/result2oscal/cmd/cmd.go @@ -19,10 +19,10 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/ocm/result2oscal/options" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/ocm" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/result2oscal/options" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/ocm" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) func New() *cobra.Command { diff --git a/cmd/ocm/oscal2policy/main.go b/go/cmd/ocm/result2oscal/main.go similarity index 89% rename from cmd/ocm/oscal2policy/main.go rename to go/cmd/ocm/result2oscal/main.go index 6014769..eb4d483 100644 --- a/cmd/ocm/oscal2policy/main.go +++ b/go/cmd/ocm/result2oscal/main.go @@ -19,7 +19,7 @@ package main import ( "os" - "github.com/IBM/compliance-to-policy/cmd/ocm/oscal2policy/cmd" + "github.com/oscal-compass/compliance-to-policy/go/cmd/ocm/result2oscal/cmd" ) func main() { diff --git a/cmd/ocm/result2oscal/options/options.go b/go/cmd/ocm/result2oscal/options/options.go similarity index 100% rename from cmd/ocm/result2oscal/options/options.go rename to go/cmd/ocm/result2oscal/options/options.go diff --git a/cmd/ocm/tools/cmd/cmd.go b/go/cmd/ocm/tools/cmd/cmd.go similarity index 82% rename from cmd/ocm/tools/cmd/cmd.go rename to go/cmd/ocm/tools/cmd/cmd.go index 5b601a5..229a1e2 100644 --- a/cmd/ocm/tools/cmd/cmd.go +++ b/go/cmd/ocm/tools/cmd/cmd.go @@ -19,9 +19,9 @@ package cmd import ( "github.com/spf13/cobra" - "github.com/IBM/compliance-to-policy/cmd/c2pcli/options" - oscal2posturecmd "github.com/IBM/compliance-to-policy/cmd/pvpcommon/oscal2posture/cmd" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/cmd/c2pcli/options" + oscal2posturecmd "github.com/oscal-compass/compliance-to-policy/go/cmd/pvpcommon/oscal2posture/cmd" + "github.com/oscal-compass/compliance-to-policy/go/pkg" ) func New() *cobra.Command { diff --git a/cmd/ocm/tools/options/options.go b/go/cmd/ocm/tools/options/options.go similarity index 100% rename from cmd/ocm/tools/options/options.go rename to go/cmd/ocm/tools/options/options.go diff --git a/cmd/parse-single/parse-single.go b/go/cmd/parse-single/parse-single.go similarity index 95% rename from cmd/parse-single/parse-single.go rename to go/cmd/parse-single/parse-single.go index 21e771d..1d98cb9 100644 --- a/cmd/parse-single/parse-single.go +++ b/go/cmd/parse-single/parse-single.go @@ -20,7 +20,7 @@ import ( "flag" "os" - "github.com/IBM/compliance-to-policy/pkg/parser" + "github.com/oscal-compass/compliance-to-policy/go/pkg/parser" ) var TARGETS = []string{ diff --git a/cmd/parse/modules/parse.go b/go/cmd/parse/modules/parse.go similarity index 94% rename from cmd/parse/modules/parse.go rename to go/cmd/parse/modules/parse.go index 87645c5..80972c6 100644 --- a/cmd/parse/modules/parse.go +++ b/go/cmd/parse/modules/parse.go @@ -24,10 +24,10 @@ import ( "go.uber.org/zap" "gopkg.in/yaml.v3" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/parser" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - "github.com/IBM/compliance-to-policy/pkg/types/policycomposition" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/parser" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policycomposition" ) var TARGETS = []string{ diff --git a/cmd/parse/parse.go b/go/cmd/parse/parse.go similarity index 94% rename from cmd/parse/parse.go rename to go/cmd/parse/parse.go index f656c64..75627f0 100644 --- a/cmd/parse/parse.go +++ b/go/cmd/parse/parse.go @@ -22,7 +22,7 @@ import ( "go.uber.org/zap" - "github.com/IBM/compliance-to-policy/cmd/parse/modules" + "github.com/oscal-compass/compliance-to-policy/go/cmd/parse/modules" ) var TARGETS = []string{ diff --git a/cmd/publisher/publisher.go b/go/cmd/publisher/publisher.go similarity index 83% rename from cmd/publisher/publisher.go rename to go/cmd/publisher/publisher.go index 584998b..5571d4a 100644 --- a/cmd/publisher/publisher.go +++ b/go/cmd/publisher/publisher.go @@ -20,11 +20,11 @@ import ( "flag" "os" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/composer" - "github.com/IBM/compliance-to-policy/controllers/utils/gitrepo" - "github.com/IBM/compliance-to-policy/controllers/utils/publisher" - "github.com/IBM/compliance-to-policy/pkg" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/composer" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/gitrepo" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/publisher" + "github.com/oscal-compass/compliance-to-policy/go/pkg" ) func main() { diff --git a/cmd/publisher/samples/compliancedeployment.yaml b/go/cmd/publisher/samples/compliancedeployment.yaml similarity index 100% rename from cmd/publisher/samples/compliancedeployment.yaml rename to go/cmd/publisher/samples/compliancedeployment.yaml diff --git a/cmd/publisher/samples/component-definition.json b/go/cmd/publisher/samples/component-definition.json similarity index 100% rename from cmd/publisher/samples/component-definition.json rename to go/cmd/publisher/samples/component-definition.json diff --git a/cmd/publisher/samples/component-definition.low.json b/go/cmd/publisher/samples/component-definition.low.json similarity index 100% rename from cmd/publisher/samples/component-definition.low.json rename to go/cmd/publisher/samples/component-definition.low.json diff --git a/cmd/pvpcommon/oscal2posture/cmd/cmd.go b/go/cmd/pvpcommon/oscal2posture/cmd/cmd.go similarity index 84% rename from cmd/pvpcommon/oscal2posture/cmd/cmd.go rename to go/cmd/pvpcommon/oscal2posture/cmd/cmd.go index e154d51..402642f 100644 --- a/cmd/pvpcommon/oscal2posture/cmd/cmd.go +++ b/go/cmd/pvpcommon/oscal2posture/cmd/cmd.go @@ -23,11 +23,11 @@ import ( "github.com/spf13/cobra" "go.uber.org/zap" - "github.com/IBM/compliance-to-policy/cmd/pvpcommon/oscal2posture/options" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/kyverno" - "github.com/IBM/compliance-to-policy/pkg/pvpcommon" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/cmd/pvpcommon/oscal2posture/options" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/kyverno" + "github.com/oscal-compass/compliance-to-policy/go/pkg/pvpcommon" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) func New(logger *zap.Logger) *cobra.Command { diff --git a/cmd/pvpcommon/oscal2posture/options/options.go b/go/cmd/pvpcommon/oscal2posture/options/options.go similarity index 100% rename from cmd/pvpcommon/oscal2posture/options/options.go rename to go/cmd/pvpcommon/oscal2posture/options/options.go diff --git a/cmd/viewer/viewer.go b/go/cmd/viewer/viewer.go similarity index 92% rename from cmd/viewer/viewer.go rename to go/cmd/viewer/viewer.go index 5ad5e98..3d57bbb 100644 --- a/cmd/viewer/viewer.go +++ b/go/cmd/viewer/viewer.go @@ -22,9 +22,9 @@ import ( "net/url" "os" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - "github.com/IBM/compliance-to-policy/pkg/types/policycomposition" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policycomposition" "gopkg.in/yaml.v3" ) diff --git a/config/crd/bases/_.yaml b/go/config/crd/bases/_.yaml similarity index 100% rename from config/crd/bases/_.yaml rename to go/config/crd/bases/_.yaml diff --git a/config/crd/bases/compliance-to-policy.io_checkpolicies.yaml b/go/config/crd/bases/compliance-to-policy.io_checkpolicies.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_checkpolicies.yaml rename to go/config/crd/bases/compliance-to-policy.io_checkpolicies.yaml diff --git a/config/crd/bases/compliance-to-policy.io_compliancedeployments.yaml b/go/config/crd/bases/compliance-to-policy.io_compliancedeployments.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_compliancedeployments.yaml rename to go/config/crd/bases/compliance-to-policy.io_compliancedeployments.yaml diff --git a/config/crd/bases/compliance-to-policy.io_compliancereports.yaml b/go/config/crd/bases/compliance-to-policy.io_compliancereports.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_compliancereports.yaml rename to go/config/crd/bases/compliance-to-policy.io_compliancereports.yaml diff --git a/config/crd/bases/compliance-to-policy.io_controlreferencekcps.yaml b/go/config/crd/bases/compliance-to-policy.io_controlreferencekcps.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_controlreferencekcps.yaml rename to go/config/crd/bases/compliance-to-policy.io_controlreferencekcps.yaml diff --git a/config/crd/bases/compliance-to-policy.io_controlreferences.yaml b/go/config/crd/bases/compliance-to-policy.io_controlreferences.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_controlreferences.yaml rename to go/config/crd/bases/compliance-to-policy.io_controlreferences.yaml diff --git a/config/crd/bases/compliance-to-policy.io_resultcollectors.yaml b/go/config/crd/bases/compliance-to-policy.io_resultcollectors.yaml similarity index 100% rename from config/crd/bases/compliance-to-policy.io_resultcollectors.yaml rename to go/config/crd/bases/compliance-to-policy.io_resultcollectors.yaml diff --git a/config/crd/bases/wgpolicyk8s.io_clusterpolicyreports.yaml b/go/config/crd/bases/wgpolicyk8s.io_clusterpolicyreports.yaml similarity index 100% rename from config/crd/bases/wgpolicyk8s.io_clusterpolicyreports.yaml rename to go/config/crd/bases/wgpolicyk8s.io_clusterpolicyreports.yaml diff --git a/config/crd/bases/wgpolicyk8s.io_policyreports.yaml b/go/config/crd/bases/wgpolicyk8s.io_policyreports.yaml similarity index 100% rename from config/crd/bases/wgpolicyk8s.io_policyreports.yaml rename to go/config/crd/bases/wgpolicyk8s.io_policyreports.yaml diff --git a/config/crd/kustomization.yaml b/go/config/crd/kustomization.yaml similarity index 100% rename from config/crd/kustomization.yaml rename to go/config/crd/kustomization.yaml diff --git a/config/crd/kustomizeconfig.yaml b/go/config/crd/kustomizeconfig.yaml similarity index 100% rename from config/crd/kustomizeconfig.yaml rename to go/config/crd/kustomizeconfig.yaml diff --git a/config/crd/patches/cainjection_in_compliancedeployments.yaml b/go/config/crd/patches/cainjection_in_compliancedeployments.yaml similarity index 100% rename from config/crd/patches/cainjection_in_compliancedeployments.yaml rename to go/config/crd/patches/cainjection_in_compliancedeployments.yaml diff --git a/config/crd/patches/cainjection_in_controlreferences.yaml b/go/config/crd/patches/cainjection_in_controlreferences.yaml similarity index 100% rename from config/crd/patches/cainjection_in_controlreferences.yaml rename to go/config/crd/patches/cainjection_in_controlreferences.yaml diff --git a/config/crd/patches/webhook_in_compliancedeployments.yaml b/go/config/crd/patches/webhook_in_compliancedeployments.yaml similarity index 100% rename from config/crd/patches/webhook_in_compliancedeployments.yaml rename to go/config/crd/patches/webhook_in_compliancedeployments.yaml diff --git a/config/crd/patches/webhook_in_controlreferences.yaml b/go/config/crd/patches/webhook_in_controlreferences.yaml similarity index 100% rename from config/crd/patches/webhook_in_controlreferences.yaml rename to go/config/crd/patches/webhook_in_controlreferences.yaml diff --git a/config/default/kustomization.yaml b/go/config/default/kustomization.yaml similarity index 100% rename from config/default/kustomization.yaml rename to go/config/default/kustomization.yaml diff --git a/config/default/manager_auth_proxy_patch.yaml b/go/config/default/manager_auth_proxy_patch.yaml similarity index 100% rename from config/default/manager_auth_proxy_patch.yaml rename to go/config/default/manager_auth_proxy_patch.yaml diff --git a/config/default/manager_config_patch.yaml b/go/config/default/manager_config_patch.yaml similarity index 100% rename from config/default/manager_config_patch.yaml rename to go/config/default/manager_config_patch.yaml diff --git a/config/manager/kustomization.yaml b/go/config/manager/kustomization.yaml similarity index 100% rename from config/manager/kustomization.yaml rename to go/config/manager/kustomization.yaml diff --git a/config/manager/manager.yaml b/go/config/manager/manager.yaml similarity index 100% rename from config/manager/manager.yaml rename to go/config/manager/manager.yaml diff --git a/config/manifests/kustomization.yaml b/go/config/manifests/kustomization.yaml similarity index 100% rename from config/manifests/kustomization.yaml rename to go/config/manifests/kustomization.yaml diff --git a/config/ocm/apps.open-cluster-management.io_placementrules_crd.yaml b/go/config/ocm/apps.open-cluster-management.io_placementrules_crd.yaml similarity index 100% rename from config/ocm/apps.open-cluster-management.io_placementrules_crd.yaml rename to go/config/ocm/apps.open-cluster-management.io_placementrules_crd.yaml diff --git a/config/ocm/policy.open-cluster-management.io_placementbindings.yaml b/go/config/ocm/policy.open-cluster-management.io_placementbindings.yaml similarity index 100% rename from config/ocm/policy.open-cluster-management.io_placementbindings.yaml rename to go/config/ocm/policy.open-cluster-management.io_placementbindings.yaml diff --git a/config/ocm/policy.open-cluster-management.io_policies.yaml b/go/config/ocm/policy.open-cluster-management.io_policies.yaml similarity index 100% rename from config/ocm/policy.open-cluster-management.io_policies.yaml rename to go/config/ocm/policy.open-cluster-management.io_policies.yaml diff --git a/config/ocm/policy.open-cluster-management.io_policysets.yaml b/go/config/ocm/policy.open-cluster-management.io_policysets.yaml similarity index 100% rename from config/ocm/policy.open-cluster-management.io_policysets.yaml rename to go/config/ocm/policy.open-cluster-management.io_policysets.yaml diff --git a/config/prometheus/kustomization.yaml b/go/config/prometheus/kustomization.yaml similarity index 100% rename from config/prometheus/kustomization.yaml rename to go/config/prometheus/kustomization.yaml diff --git a/config/prometheus/monitor.yaml b/go/config/prometheus/monitor.yaml similarity index 100% rename from config/prometheus/monitor.yaml rename to go/config/prometheus/monitor.yaml diff --git a/config/rbac/auth_proxy_client_clusterrole.yaml b/go/config/rbac/auth_proxy_client_clusterrole.yaml similarity index 100% rename from config/rbac/auth_proxy_client_clusterrole.yaml rename to go/config/rbac/auth_proxy_client_clusterrole.yaml diff --git a/config/rbac/auth_proxy_role.yaml b/go/config/rbac/auth_proxy_role.yaml similarity index 100% rename from config/rbac/auth_proxy_role.yaml rename to go/config/rbac/auth_proxy_role.yaml diff --git a/config/rbac/auth_proxy_role_binding.yaml b/go/config/rbac/auth_proxy_role_binding.yaml similarity index 100% rename from config/rbac/auth_proxy_role_binding.yaml rename to go/config/rbac/auth_proxy_role_binding.yaml diff --git a/config/rbac/auth_proxy_service.yaml b/go/config/rbac/auth_proxy_service.yaml similarity index 100% rename from config/rbac/auth_proxy_service.yaml rename to go/config/rbac/auth_proxy_service.yaml diff --git a/config/rbac/compliancedeployment_editor_role.yaml b/go/config/rbac/compliancedeployment_editor_role.yaml similarity index 100% rename from config/rbac/compliancedeployment_editor_role.yaml rename to go/config/rbac/compliancedeployment_editor_role.yaml diff --git a/config/rbac/compliancedeployment_viewer_role.yaml b/go/config/rbac/compliancedeployment_viewer_role.yaml similarity index 100% rename from config/rbac/compliancedeployment_viewer_role.yaml rename to go/config/rbac/compliancedeployment_viewer_role.yaml diff --git a/config/rbac/controlreference_editor_role.yaml b/go/config/rbac/controlreference_editor_role.yaml similarity index 100% rename from config/rbac/controlreference_editor_role.yaml rename to go/config/rbac/controlreference_editor_role.yaml diff --git a/config/rbac/controlreference_viewer_role.yaml b/go/config/rbac/controlreference_viewer_role.yaml similarity index 100% rename from config/rbac/controlreference_viewer_role.yaml rename to go/config/rbac/controlreference_viewer_role.yaml diff --git a/config/rbac/kustomization.yaml b/go/config/rbac/kustomization.yaml similarity index 100% rename from config/rbac/kustomization.yaml rename to go/config/rbac/kustomization.yaml diff --git a/config/rbac/leader_election_role.yaml b/go/config/rbac/leader_election_role.yaml similarity index 100% rename from config/rbac/leader_election_role.yaml rename to go/config/rbac/leader_election_role.yaml diff --git a/config/rbac/leader_election_role_binding.yaml b/go/config/rbac/leader_election_role_binding.yaml similarity index 100% rename from config/rbac/leader_election_role_binding.yaml rename to go/config/rbac/leader_election_role_binding.yaml diff --git a/config/rbac/role.yaml b/go/config/rbac/role.yaml similarity index 100% rename from config/rbac/role.yaml rename to go/config/rbac/role.yaml diff --git a/config/rbac/role_binding.yaml b/go/config/rbac/role_binding.yaml similarity index 100% rename from config/rbac/role_binding.yaml rename to go/config/rbac/role_binding.yaml diff --git a/config/rbac/service_account.yaml b/go/config/rbac/service_account.yaml similarity index 100% rename from config/rbac/service_account.yaml rename to go/config/rbac/service_account.yaml diff --git a/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.kcp.yaml b/go/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.kcp.yaml similarity index 100% rename from config/samples/compliance-to-policy_v1alpha1_compliancedeployment.kcp.yaml rename to go/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.kcp.yaml diff --git a/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.yaml b/go/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.yaml similarity index 100% rename from config/samples/compliance-to-policy_v1alpha1_compliancedeployment.yaml rename to go/config/samples/compliance-to-policy_v1alpha1_compliancedeployment.yaml diff --git a/config/samples/compliance-to-policy_v1alpha1_controlreference.yaml b/go/config/samples/compliance-to-policy_v1alpha1_controlreference.yaml similarity index 100% rename from config/samples/compliance-to-policy_v1alpha1_controlreference.yaml rename to go/config/samples/compliance-to-policy_v1alpha1_controlreference.yaml diff --git a/config/samples/compliance-to-policy_v1alpha1_controlreferencekcp.yaml b/go/config/samples/compliance-to-policy_v1alpha1_controlreferencekcp.yaml similarity index 100% rename from config/samples/compliance-to-policy_v1alpha1_controlreferencekcp.yaml rename to go/config/samples/compliance-to-policy_v1alpha1_controlreferencekcp.yaml diff --git a/config/samples/kustomization.yaml b/go/config/samples/kustomization.yaml similarity index 100% rename from config/samples/kustomization.yaml rename to go/config/samples/kustomization.yaml diff --git a/config/scorecard/bases/config.yaml b/go/config/scorecard/bases/config.yaml similarity index 100% rename from config/scorecard/bases/config.yaml rename to go/config/scorecard/bases/config.yaml diff --git a/config/scorecard/kustomization.yaml b/go/config/scorecard/kustomization.yaml similarity index 100% rename from config/scorecard/kustomization.yaml rename to go/config/scorecard/kustomization.yaml diff --git a/config/scorecard/patches/basic.config.yaml b/go/config/scorecard/patches/basic.config.yaml similarity index 100% rename from config/scorecard/patches/basic.config.yaml rename to go/config/scorecard/patches/basic.config.yaml diff --git a/config/scorecard/patches/olm.config.yaml b/go/config/scorecard/patches/olm.config.yaml similarity index 100% rename from config/scorecard/patches/olm.config.yaml rename to go/config/scorecard/patches/olm.config.yaml diff --git a/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_clusterpolicyreports.yaml b/go/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_clusterpolicyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_clusterpolicyreports.yaml rename to go/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_clusterpolicyreports.yaml diff --git a/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_policyreports.yaml b/go/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_policyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_policyreports.yaml rename to go/config/wgpolicyk8s/v1alpha1/wgpolicyk8s.io_policyreports.yaml diff --git a/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_clusterpolicyreports.yaml b/go/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_clusterpolicyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_clusterpolicyreports.yaml rename to go/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_clusterpolicyreports.yaml diff --git a/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_policyreports.yaml b/go/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_policyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_policyreports.yaml rename to go/config/wgpolicyk8s/v1alpha2/wgpolicyk8s.io_policyreports.yaml diff --git a/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_clusterpolicyreports.yaml b/go/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_clusterpolicyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_clusterpolicyreports.yaml rename to go/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_clusterpolicyreports.yaml diff --git a/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_policyreports.yaml b/go/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_policyreports.yaml similarity index 100% rename from config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_policyreports.yaml rename to go/config/wgpolicyk8s/v1beta1/wgpolicyk8s.io_policyreports.yaml diff --git a/controllers/compliancedeployment/controller.go b/go/controllers/compliancedeployment/controller.go similarity index 96% rename from controllers/compliancedeployment/controller.go rename to go/controllers/compliancedeployment/controller.go index 26dd8e4..225feb6 100644 --- a/controllers/compliancedeployment/controller.go +++ b/go/controllers/compliancedeployment/controller.go @@ -29,8 +29,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" ) // ComplianceDeploymentReconciler reconciles a ComplianceDeployment object diff --git a/controllers/compliancedeployment/controller_test.go b/go/controllers/compliancedeployment/controller_test.go similarity index 93% rename from controllers/compliancedeployment/controller_test.go rename to go/controllers/compliancedeployment/controller_test.go index aeabce0..e3a6afe 100644 --- a/controllers/compliancedeployment/controller_test.go +++ b/go/controllers/compliancedeployment/controller_test.go @@ -23,11 +23,11 @@ import ( "testing" "time" - ctrlv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" - "github.com/IBM/compliance-to-policy/pkg" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + ctrlv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -37,8 +37,8 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" - ctrlrefocm "github.com/IBM/compliance-to-policy/controllers/controlreference/ocm" - "github.com/IBM/compliance-to-policy/controllers/testsetting" + ctrlrefocm "github.com/oscal-compass/compliance-to-policy/go/controllers/controlreference/ocm" + "github.com/oscal-compass/compliance-to-policy/go/controllers/testsetting" ) var testSetting *testsetting.TestSetting diff --git a/controllers/composer/composer.go b/go/controllers/composer/composer.go similarity index 96% rename from controllers/composer/composer.go rename to go/controllers/composer/composer.go index 5fbe1fd..6cb1e7d 100644 --- a/controllers/composer/composer.go +++ b/go/controllers/composer/composer.go @@ -21,13 +21,13 @@ import ( "os" "strings" - policygenerator "github.com/IBM/compliance-to-policy/pkg/policygenerator" - . "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - pgtype "github.com/IBM/compliance-to-policy/pkg/types/policygenerator" + policygenerator "github.com/oscal-compass/compliance-to-policy/go/pkg/policygenerator" + . "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + pgtype "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policygenerator" cp "github.com/otiai10/copy" typekustomize "sigs.k8s.io/kustomize/api/types" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "go.uber.org/zap" "k8s.io/apimachinery/pkg/util/sets" ) diff --git a/controllers/composer/composer_test.go b/go/controllers/composer/composer_test.go similarity index 94% rename from controllers/composer/composer_test.go rename to go/controllers/composer/composer_test.go index 306224e..47bae19 100644 --- a/controllers/composer/composer_test.go +++ b/go/controllers/composer/composer_test.go @@ -21,11 +21,11 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/types/configurationpolicy" - . "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - "github.com/IBM/compliance-to-policy/pkg/types/placements" - typepolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/configurationpolicy" + . "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" + typepolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" "github.com/stretchr/testify/assert" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" diff --git a/controllers/composer/helper.go b/go/controllers/composer/helper.go similarity index 94% rename from controllers/composer/helper.go rename to go/controllers/composer/helper.go index 607e937..ceb1c07 100644 --- a/controllers/composer/helper.go +++ b/go/controllers/composer/helper.go @@ -22,11 +22,11 @@ import ( "sort" "strings" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/types/configurationpolicy" - . "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - typespolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" - pgtype "github.com/IBM/compliance-to-policy/pkg/types/policygenerator" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/configurationpolicy" + . "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + typespolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" + pgtype "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policygenerator" cp "github.com/otiai10/copy" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" utilyaml "k8s.io/apimachinery/pkg/util/yaml" diff --git a/controllers/composer/testdata/compliance.yaml b/go/controllers/composer/testdata/compliance.yaml similarity index 100% rename from controllers/composer/testdata/compliance.yaml rename to go/controllers/composer/testdata/compliance.yaml diff --git a/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/add-chrony.yaml b/go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/add-chrony.yaml similarity index 100% rename from controllers/composer/testdata/expected/c2pcr-parser-composed-policies/add-chrony.yaml rename to go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/add-chrony.yaml diff --git a/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/install-odf-lvm-operator.yaml b/go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/install-odf-lvm-operator.yaml similarity index 100% rename from controllers/composer/testdata/expected/c2pcr-parser-composed-policies/install-odf-lvm-operator.yaml rename to go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/install-odf-lvm-operator.yaml diff --git a/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/policy-nginx-deployment.yaml b/go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/policy-nginx-deployment.yaml similarity index 100% rename from controllers/composer/testdata/expected/c2pcr-parser-composed-policies/policy-nginx-deployment.yaml rename to go/controllers/composer/testdata/expected/c2pcr-parser-composed-policies/policy-nginx-deployment.yaml diff --git a/controllers/composer/testdata/expected/composed-config-policies/add-chrony/add-chrony.yaml b/go/controllers/composer/testdata/expected/composed-config-policies/add-chrony/add-chrony.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-config-policies/add-chrony/add-chrony.yaml rename to go/controllers/composer/testdata/expected/composed-config-policies/add-chrony/add-chrony.yaml diff --git a/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator.yaml b/go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator.yaml rename to go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator.yaml diff --git a/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator2.yaml b/go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator2.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator2.yaml rename to go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator2.yaml diff --git a/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator3.yaml b/go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator3.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator3.yaml rename to go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator3.yaml diff --git a/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator4.yaml b/go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator4.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator4.yaml rename to go/controllers/composer/testdata/expected/composed-config-policies/install-odf-lvm-operator/install-odf-lvm-operator4.yaml diff --git a/controllers/composer/testdata/expected/composed-policies/add-chrony.yaml b/go/controllers/composer/testdata/expected/composed-policies/add-chrony.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-policies/add-chrony.yaml rename to go/controllers/composer/testdata/expected/composed-policies/add-chrony.yaml diff --git a/controllers/composer/testdata/expected/composed-policies/install-odf-lvm-operator.yaml b/go/controllers/composer/testdata/expected/composed-policies/install-odf-lvm-operator.yaml similarity index 100% rename from controllers/composer/testdata/expected/composed-policies/install-odf-lvm-operator.yaml rename to go/controllers/composer/testdata/expected/composed-policies/install-odf-lvm-operator.yaml diff --git a/controllers/composer/testdata/oscal/catalog.json b/go/controllers/composer/testdata/oscal/catalog.json similarity index 100% rename from controllers/composer/testdata/oscal/catalog.json rename to go/controllers/composer/testdata/oscal/catalog.json diff --git a/controllers/composer/testdata/oscal/component-definition.json b/go/controllers/composer/testdata/oscal/component-definition.json similarity index 100% rename from controllers/composer/testdata/oscal/component-definition.json rename to go/controllers/composer/testdata/oscal/component-definition.json diff --git a/controllers/composer/testdata/oscal/profile.json b/go/controllers/composer/testdata/oscal/profile.json similarity index 100% rename from controllers/composer/testdata/oscal/profile.json rename to go/controllers/composer/testdata/oscal/profile.json diff --git a/controllers/composer/testdata/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml b/go/controllers/composer/testdata/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml rename to go/controllers/composer/testdata/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml diff --git a/controllers/composer/testdata/policies/add-chrony/kustomization.yaml b/go/controllers/composer/testdata/policies/add-chrony/kustomization.yaml similarity index 100% rename from controllers/composer/testdata/policies/add-chrony/kustomization.yaml rename to go/controllers/composer/testdata/policies/add-chrony/kustomization.yaml diff --git a/controllers/composer/testdata/policies/add-chrony/policy-generator.yaml b/go/controllers/composer/testdata/policies/add-chrony/policy-generator.yaml similarity index 100% rename from controllers/composer/testdata/policies/add-chrony/policy-generator.yaml rename to go/controllers/composer/testdata/policies/add-chrony/policy-generator.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/kustomization.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/kustomization.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/kustomization.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/kustomization.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-generator.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-generator.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/policy-generator.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-generator.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml diff --git a/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml b/go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml rename to go/controllers/composer/testdata/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml diff --git a/controllers/composer/testdata/policies/policy-nginx-deployment/kustomization.yaml b/go/controllers/composer/testdata/policies/policy-nginx-deployment/kustomization.yaml similarity index 100% rename from controllers/composer/testdata/policies/policy-nginx-deployment/kustomization.yaml rename to go/controllers/composer/testdata/policies/policy-nginx-deployment/kustomization.yaml diff --git a/controllers/composer/testdata/policies/policy-nginx-deployment/policy-generator.yaml b/go/controllers/composer/testdata/policies/policy-nginx-deployment/policy-generator.yaml similarity index 100% rename from controllers/composer/testdata/policies/policy-nginx-deployment/policy-generator.yaml rename to go/controllers/composer/testdata/policies/policy-nginx-deployment/policy-generator.yaml diff --git a/controllers/composer/testdata/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml b/go/controllers/composer/testdata/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml similarity index 100% rename from controllers/composer/testdata/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml rename to go/controllers/composer/testdata/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml diff --git a/controllers/controlreference/kcp/controller.go b/go/controllers/controlreference/kcp/controller.go similarity index 96% rename from controllers/controlreference/kcp/controller.go rename to go/controllers/controlreference/kcp/controller.go index c4b4234..77ebeda 100644 --- a/controllers/controlreference/kcp/controller.go +++ b/go/controllers/controlreference/kcp/controller.go @@ -32,13 +32,13 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/composer" - "github.com/IBM/compliance-to-policy/controllers/utils" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" "github.com/go-logr/logr" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/composer" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" ) var logger logr.Logger = ctrl.Log.WithName("control-reference-controller-kcp") diff --git a/controllers/controlreference/kcp/controller_test.go b/go/controllers/controlreference/kcp/controller_test.go similarity index 95% rename from controllers/controlreference/kcp/controller_test.go rename to go/controllers/controlreference/kcp/controller_test.go index 5110026..df7c1fa 100644 --- a/controllers/controlreference/kcp/controller_test.go +++ b/go/controllers/controlreference/kcp/controller_test.go @@ -22,12 +22,12 @@ import ( "testing" "time" - ctrlv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/testsetting" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - "github.com/IBM/compliance-to-policy/pkg" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + ctrlv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/testsetting" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + "github.com/oscal-compass/compliance-to-policy/go/pkg" apixv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apix "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/controllers/controlreference/kcp/helper.go b/go/controllers/controlreference/kcp/helper.go similarity index 97% rename from controllers/controlreference/kcp/helper.go rename to go/controllers/controlreference/kcp/helper.go index d35d367..88e25c8 100644 --- a/controllers/controlreference/kcp/helper.go +++ b/go/controllers/controlreference/kcp/helper.go @@ -6,12 +6,12 @@ import ( "strings" "time" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - edgev1alpha1 "github.com/IBM/compliance-to-policy/controllers/edge.kcp.io/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - "github.com/IBM/compliance-to-policy/pkg" kcpv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/apis/v1alpha1" tenancyv1alpha1 "github.com/kcp-dev/kcp/pkg/apis/tenancy/v1alpha1" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + edgev1alpha1 "github.com/oscal-compass/compliance-to-policy/go/controllers/edge.kcp.io/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/controllers/controlreference/ocm/controller.go b/go/controllers/controlreference/ocm/controller.go similarity index 93% rename from controllers/controlreference/ocm/controller.go rename to go/controllers/controlreference/ocm/controller.go index fa8c4e4..8e3942a 100644 --- a/controllers/controlreference/ocm/controller.go +++ b/go/controllers/controlreference/ocm/controller.go @@ -28,14 +28,14 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/composer" - "github.com/IBM/compliance-to-policy/controllers/utils" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" - "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - typesplacement "github.com/IBM/compliance-to-policy/pkg/types/placements" - typespolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" "github.com/go-logr/logr" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/composer" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + typesplacement "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" + typespolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" utilyaml "k8s.io/apimachinery/pkg/util/yaml" ) diff --git a/controllers/controlreference/ocm/controller_test.go b/go/controllers/controlreference/ocm/controller_test.go similarity index 93% rename from controllers/controlreference/ocm/controller_test.go rename to go/controllers/controlreference/ocm/controller_test.go index 6b44a42..7625560 100644 --- a/controllers/controlreference/ocm/controller_test.go +++ b/go/controllers/controlreference/ocm/controller_test.go @@ -19,11 +19,11 @@ package ocm import ( "context" - ctrlv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" - "github.com/IBM/compliance-to-policy/pkg" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + ctrlv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "sigs.k8s.io/controller-runtime/pkg/client" "os" @@ -36,7 +36,7 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" - "github.com/IBM/compliance-to-policy/controllers/testsetting" + "github.com/oscal-compass/compliance-to-policy/go/controllers/testsetting" ) var testSetting *testsetting.TestSetting diff --git a/controllers/edge.kcp.io/v1alpha1/customize.go b/go/controllers/edge.kcp.io/v1alpha1/customize.go similarity index 100% rename from controllers/edge.kcp.io/v1alpha1/customize.go rename to go/controllers/edge.kcp.io/v1alpha1/customize.go diff --git a/controllers/edge.kcp.io/v1alpha1/edge-placement.go b/go/controllers/edge.kcp.io/v1alpha1/edge-placement.go similarity index 100% rename from controllers/edge.kcp.io/v1alpha1/edge-placement.go rename to go/controllers/edge.kcp.io/v1alpha1/edge-placement.go diff --git a/controllers/edge.kcp.io/v1alpha1/single-placement.go b/go/controllers/edge.kcp.io/v1alpha1/single-placement.go similarity index 100% rename from controllers/edge.kcp.io/v1alpha1/single-placement.go rename to go/controllers/edge.kcp.io/v1alpha1/single-placement.go diff --git a/controllers/resultcollector/collector.go b/go/controllers/resultcollector/collector.go similarity index 97% rename from controllers/resultcollector/collector.go rename to go/controllers/resultcollector/collector.go index 7fe0b81..60db3a4 100644 --- a/controllers/resultcollector/collector.go +++ b/go/controllers/resultcollector/collector.go @@ -21,10 +21,10 @@ import ( "fmt" "strings" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - wgpolicyk8sv1alpha2 "github.com/IBM/compliance-to-policy/controllers/wgpolicyk8s.io/v1alpha2" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + wgpolicyk8sv1alpha2 "github.com/oscal-compass/compliance-to-policy/go/controllers/wgpolicyk8s.io/v1alpha2" corev1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/rest" diff --git a/controllers/resultcollector/controller.go b/go/controllers/resultcollector/controller.go similarity index 96% rename from controllers/resultcollector/controller.go rename to go/controllers/resultcollector/controller.go index 6911748..5104922 100644 --- a/controllers/resultcollector/controller.go +++ b/go/controllers/resultcollector/controller.go @@ -22,9 +22,9 @@ import ( "sync" "time" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils" "github.com/go-logr/logr" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/client-go/rest" diff --git a/controllers/resultcollector/validator.go b/go/controllers/resultcollector/validator.go similarity index 97% rename from controllers/resultcollector/validator.go rename to go/controllers/resultcollector/validator.go index 5178342..4de2c4e 100644 --- a/controllers/resultcollector/validator.go +++ b/go/controllers/resultcollector/validator.go @@ -21,9 +21,9 @@ import ( "fmt" "strings" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - "github.com/IBM/compliance-to-policy/pkg" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" diff --git a/controllers/testdata/compliancedeployment.yaml b/go/controllers/testdata/compliancedeployment.yaml similarity index 100% rename from controllers/testdata/compliancedeployment.yaml rename to go/controllers/testdata/compliancedeployment.yaml diff --git a/controllers/testdata/configmap.component-definition.yaml b/go/controllers/testdata/configmap.component-definition.yaml similarity index 100% rename from controllers/testdata/configmap.component-definition.yaml rename to go/controllers/testdata/configmap.component-definition.yaml diff --git a/controllers/testdata/controlreference.yaml b/go/controllers/testdata/controlreference.yaml similarity index 100% rename from controllers/testdata/controlreference.yaml rename to go/controllers/testdata/controlreference.yaml diff --git a/controllers/testdata/controlreferencekcp.yaml b/go/controllers/testdata/controlreferencekcp.yaml similarity index 100% rename from controllers/testdata/controlreferencekcp.yaml rename to go/controllers/testdata/controlreferencekcp.yaml diff --git a/controllers/testdata/ws.test1.yaml b/go/controllers/testdata/ws.test1.yaml similarity index 100% rename from controllers/testdata/ws.test1.yaml rename to go/controllers/testdata/ws.test1.yaml diff --git a/controllers/testdata/ws.test2.yaml b/go/controllers/testdata/ws.test2.yaml similarity index 100% rename from controllers/testdata/ws.test2.yaml rename to go/controllers/testdata/ws.test2.yaml diff --git a/controllers/testsetting/common.go b/go/controllers/testsetting/common.go similarity index 100% rename from controllers/testsetting/common.go rename to go/controllers/testsetting/common.go diff --git a/controllers/testsetting/kcptestsetting.go b/go/controllers/testsetting/kcptestsetting.go similarity index 95% rename from controllers/testsetting/kcptestsetting.go rename to go/controllers/testsetting/kcptestsetting.go index ab33079..60dcba3 100644 --- a/controllers/testsetting/kcptestsetting.go +++ b/go/controllers/testsetting/kcptestsetting.go @@ -26,8 +26,8 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" diff --git a/controllers/testsetting/testsetting.go b/go/controllers/testsetting/testsetting.go similarity index 94% rename from controllers/testsetting/testsetting.go rename to go/controllers/testsetting/testsetting.go index 189b084..d4ba1ec 100644 --- a/controllers/testsetting/testsetting.go +++ b/go/controllers/testsetting/testsetting.go @@ -24,9 +24,9 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" - "github.com/IBM/compliance-to-policy/pkg" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" + "github.com/oscal-compass/compliance-to-policy/go/pkg" corev1 "k8s.io/api/core/v1" apixv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" diff --git a/controllers/utils/gitrepo/gitrepo.go b/go/controllers/utils/gitrepo/gitrepo.go similarity index 100% rename from controllers/utils/gitrepo/gitrepo.go rename to go/controllers/utils/gitrepo/gitrepo.go diff --git a/controllers/utils/gitrepo/gitrepo_test.go b/go/controllers/utils/gitrepo/gitrepo_test.go similarity index 96% rename from controllers/utils/gitrepo/gitrepo_test.go rename to go/controllers/utils/gitrepo/gitrepo_test.go index 4dc15b5..f175551 100644 --- a/controllers/utils/gitrepo/gitrepo_test.go +++ b/go/controllers/utils/gitrepo/gitrepo_test.go @@ -20,7 +20,7 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" ) func TestGitRepo(t *testing.T) { diff --git a/controllers/utils/kcpclient/kcpclient.go b/go/controllers/utils/kcpclient/kcpclient.go similarity index 100% rename from controllers/utils/kcpclient/kcpclient.go rename to go/controllers/utils/kcpclient/kcpclient.go diff --git a/controllers/utils/kcpclient/kcpclient_test.go b/go/controllers/utils/kcpclient/kcpclient_test.go similarity index 96% rename from controllers/utils/kcpclient/kcpclient_test.go rename to go/controllers/utils/kcpclient/kcpclient_test.go index 3c64b27..31c4406 100644 --- a/controllers/utils/kcpclient/kcpclient_test.go +++ b/go/controllers/utils/kcpclient/kcpclient_test.go @@ -22,10 +22,10 @@ import ( "testing" "time" - "github.com/IBM/compliance-to-policy/controllers/testsetting" - "github.com/IBM/compliance-to-policy/pkg" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/oscal-compass/compliance-to-policy/go/controllers/testsetting" + "github.com/oscal-compass/compliance-to-policy/go/pkg" corev1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" diff --git a/controllers/utils/kcpclient/testdata/ws.test1.yaml b/go/controllers/utils/kcpclient/testdata/ws.test1.yaml similarity index 100% rename from controllers/utils/kcpclient/testdata/ws.test1.yaml rename to go/controllers/utils/kcpclient/testdata/ws.test1.yaml diff --git a/controllers/utils/kcpclient/testdata/ws.test2.yaml b/go/controllers/utils/kcpclient/testdata/ws.test2.yaml similarity index 100% rename from controllers/utils/kcpclient/testdata/ws.test2.yaml rename to go/controllers/utils/kcpclient/testdata/ws.test2.yaml diff --git a/controllers/utils/ocmk8sclients/ocmk8sclient.go b/go/controllers/utils/ocmk8sclients/ocmk8sclient.go similarity index 100% rename from controllers/utils/ocmk8sclients/ocmk8sclient.go rename to go/controllers/utils/ocmk8sclients/ocmk8sclient.go diff --git a/controllers/utils/ocmk8sclients/placementbindingclient.go b/go/controllers/utils/ocmk8sclients/placementbindingclient.go similarity index 94% rename from controllers/utils/ocmk8sclients/placementbindingclient.go rename to go/controllers/utils/ocmk8sclients/placementbindingclient.go index fc04b97..163cee0 100644 --- a/controllers/utils/ocmk8sclients/placementbindingclient.go +++ b/go/controllers/utils/ocmk8sclients/placementbindingclient.go @@ -19,8 +19,8 @@ package ocmk8sclients import ( "context" - "github.com/IBM/compliance-to-policy/pkg" - typesplacement "github.com/IBM/compliance-to-policy/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typesplacement "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic" ) diff --git a/controllers/utils/ocmk8sclients/placementbindingclient_test.go b/go/controllers/utils/ocmk8sclients/placementbindingclient_test.go similarity index 93% rename from controllers/utils/ocmk8sclients/placementbindingclient_test.go rename to go/controllers/utils/ocmk8sclients/placementbindingclient_test.go index 30abc88..98c391e 100644 --- a/controllers/utils/ocmk8sclients/placementbindingclient_test.go +++ b/go/controllers/utils/ocmk8sclients/placementbindingclient_test.go @@ -17,8 +17,8 @@ limitations under the License. package ocmk8sclients import ( - "github.com/IBM/compliance-to-policy/pkg" - typesplacement "github.com/IBM/compliance-to-policy/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typesplacement "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" "k8s.io/client-go/dynamic" . "github.com/onsi/ginkgo/v2" diff --git a/controllers/utils/ocmk8sclients/placementruleclient.go b/go/controllers/utils/ocmk8sclients/placementruleclient.go similarity index 94% rename from controllers/utils/ocmk8sclients/placementruleclient.go rename to go/controllers/utils/ocmk8sclients/placementruleclient.go index a05f4cf..db90164 100644 --- a/controllers/utils/ocmk8sclients/placementruleclient.go +++ b/go/controllers/utils/ocmk8sclients/placementruleclient.go @@ -19,8 +19,8 @@ package ocmk8sclients import ( "context" - "github.com/IBM/compliance-to-policy/pkg" - typesplacement "github.com/IBM/compliance-to-policy/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typesplacement "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic" ) diff --git a/controllers/utils/ocmk8sclients/placementruleclient_test.go b/go/controllers/utils/ocmk8sclients/placementruleclient_test.go similarity index 93% rename from controllers/utils/ocmk8sclients/placementruleclient_test.go rename to go/controllers/utils/ocmk8sclients/placementruleclient_test.go index fe7c4d7..cb8d810 100644 --- a/controllers/utils/ocmk8sclients/placementruleclient_test.go +++ b/go/controllers/utils/ocmk8sclients/placementruleclient_test.go @@ -17,8 +17,8 @@ limitations under the License. package ocmk8sclients import ( - "github.com/IBM/compliance-to-policy/pkg" - typesplacement "github.com/IBM/compliance-to-policy/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typesplacement "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" "k8s.io/client-go/dynamic" . "github.com/onsi/ginkgo/v2" diff --git a/controllers/utils/ocmk8sclients/policyclient.go b/go/controllers/utils/ocmk8sclients/policyclient.go similarity index 94% rename from controllers/utils/ocmk8sclients/policyclient.go rename to go/controllers/utils/ocmk8sclients/policyclient.go index 0ed0b8d..e439ea7 100644 --- a/controllers/utils/ocmk8sclients/policyclient.go +++ b/go/controllers/utils/ocmk8sclients/policyclient.go @@ -19,8 +19,8 @@ package ocmk8sclients import ( "context" - "github.com/IBM/compliance-to-policy/pkg" - typespolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typespolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/dynamic" ) diff --git a/controllers/utils/ocmk8sclients/policyclient_test.go b/go/controllers/utils/ocmk8sclients/policyclient_test.go similarity index 93% rename from controllers/utils/ocmk8sclients/policyclient_test.go rename to go/controllers/utils/ocmk8sclients/policyclient_test.go index 80a2f70..5cd9d67 100644 --- a/controllers/utils/ocmk8sclients/policyclient_test.go +++ b/go/controllers/utils/ocmk8sclients/policyclient_test.go @@ -17,8 +17,8 @@ limitations under the License. package ocmk8sclients import ( - "github.com/IBM/compliance-to-policy/pkg" - typespolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typespolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" "k8s.io/client-go/dynamic" . "github.com/onsi/ginkgo/v2" diff --git a/controllers/utils/ocmk8sclients/suite_test.go b/go/controllers/utils/ocmk8sclients/suite_test.go similarity index 96% rename from controllers/utils/ocmk8sclients/suite_test.go rename to go/controllers/utils/ocmk8sclients/suite_test.go index 65eb62d..9547939 100644 --- a/controllers/utils/ocmk8sclients/suite_test.go +++ b/go/controllers/utils/ocmk8sclients/suite_test.go @@ -38,8 +38,8 @@ import ( logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/pkg" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/pkg" //+kubebuilder:scaffold:imports ) diff --git a/controllers/utils/ocmk8sclients/testdata/placement-binding.sample.yaml b/go/controllers/utils/ocmk8sclients/testdata/placement-binding.sample.yaml similarity index 100% rename from controllers/utils/ocmk8sclients/testdata/placement-binding.sample.yaml rename to go/controllers/utils/ocmk8sclients/testdata/placement-binding.sample.yaml diff --git a/controllers/utils/ocmk8sclients/testdata/placement-rule.sample.yaml b/go/controllers/utils/ocmk8sclients/testdata/placement-rule.sample.yaml similarity index 100% rename from controllers/utils/ocmk8sclients/testdata/placement-rule.sample.yaml rename to go/controllers/utils/ocmk8sclients/testdata/placement-rule.sample.yaml diff --git a/controllers/utils/ocmk8sclients/testdata/policy.sample.yaml b/go/controllers/utils/ocmk8sclients/testdata/policy.sample.yaml similarity index 100% rename from controllers/utils/ocmk8sclients/testdata/policy.sample.yaml rename to go/controllers/utils/ocmk8sclients/testdata/policy.sample.yaml diff --git a/controllers/utils/publisher/publisher.go b/go/controllers/utils/publisher/publisher.go similarity index 89% rename from controllers/utils/publisher/publisher.go rename to go/controllers/utils/publisher/publisher.go index 2bb2fb0..3a391d2 100644 --- a/controllers/utils/publisher/publisher.go +++ b/go/controllers/utils/publisher/publisher.go @@ -20,12 +20,12 @@ import ( "fmt" "os" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/composer" - "github.com/IBM/compliance-to-policy/controllers/utils" - "github.com/IBM/compliance-to-policy/controllers/utils/gitrepo" - "github.com/IBM/compliance-to-policy/pkg" "github.com/go-logr/logr" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/composer" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/gitrepo" + "github.com/oscal-compass/compliance-to-policy/go/pkg" cp "github.com/otiai10/copy" ctrl "sigs.k8s.io/controller-runtime" ) diff --git a/controllers/utils/publisher/testdata/compliancedeployment.yaml b/go/controllers/utils/publisher/testdata/compliancedeployment.yaml similarity index 100% rename from controllers/utils/publisher/testdata/compliancedeployment.yaml rename to go/controllers/utils/publisher/testdata/compliancedeployment.yaml diff --git a/controllers/utils/publisher/testdata/component-definition.json b/go/controllers/utils/publisher/testdata/component-definition.json similarity index 100% rename from controllers/utils/publisher/testdata/component-definition.json rename to go/controllers/utils/publisher/testdata/component-definition.json diff --git a/controllers/utils/utils.go b/go/controllers/utils/utils.go similarity index 95% rename from controllers/utils/utils.go rename to go/controllers/utils/utils.go index 945683e..525644b 100644 --- a/controllers/utils/utils.go +++ b/go/controllers/utils/utils.go @@ -27,15 +27,15 @@ import ( "strconv" "strings" - c2pv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - edge "github.com/IBM/compliance-to-policy/controllers/edge.kcp.io/v1alpha1" - "github.com/IBM/compliance-to-policy/controllers/utils/kcpclient" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/oscal" - internalcompliance "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - typesoscal "github.com/IBM/compliance-to-policy/pkg/types/oscal" - cd "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" "github.com/go-logr/logr" + c2pv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + edge "github.com/oscal-compass/compliance-to-policy/go/controllers/edge.kcp.io/v1alpha1" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/kcpclient" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + internalcompliance "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + typesoscal "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal" + cd "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" "gopkg.in/src-d/go-git.v4" githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http" "k8s.io/apimachinery/pkg/api/errors" diff --git a/controllers/wgpolicyk8s.io/v1alpha1/clusterpolicyreport_types.go b/go/controllers/wgpolicyk8s.io/v1alpha1/clusterpolicyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha1/clusterpolicyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1alpha1/clusterpolicyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1alpha1/doc.go b/go/controllers/wgpolicyk8s.io/v1alpha1/doc.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha1/doc.go rename to go/controllers/wgpolicyk8s.io/v1alpha1/doc.go diff --git a/controllers/wgpolicyk8s.io/v1alpha1/groupversion_info.go b/go/controllers/wgpolicyk8s.io/v1alpha1/groupversion_info.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha1/groupversion_info.go rename to go/controllers/wgpolicyk8s.io/v1alpha1/groupversion_info.go diff --git a/controllers/wgpolicyk8s.io/v1alpha1/policyreport_types.go b/go/controllers/wgpolicyk8s.io/v1alpha1/policyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha1/policyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1alpha1/policyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1alpha1/zz_generated.deepcopy.go b/go/controllers/wgpolicyk8s.io/v1alpha1/zz_generated.deepcopy.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha1/zz_generated.deepcopy.go rename to go/controllers/wgpolicyk8s.io/v1alpha1/zz_generated.deepcopy.go diff --git a/controllers/wgpolicyk8s.io/v1alpha2/clusterpolicyreport_types.go b/go/controllers/wgpolicyk8s.io/v1alpha2/clusterpolicyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha2/clusterpolicyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1alpha2/clusterpolicyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1alpha2/doc.go b/go/controllers/wgpolicyk8s.io/v1alpha2/doc.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha2/doc.go rename to go/controllers/wgpolicyk8s.io/v1alpha2/doc.go diff --git a/controllers/wgpolicyk8s.io/v1alpha2/groupversion_info.go b/go/controllers/wgpolicyk8s.io/v1alpha2/groupversion_info.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha2/groupversion_info.go rename to go/controllers/wgpolicyk8s.io/v1alpha2/groupversion_info.go diff --git a/controllers/wgpolicyk8s.io/v1alpha2/policyreport_types.go b/go/controllers/wgpolicyk8s.io/v1alpha2/policyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha2/policyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1alpha2/policyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1alpha2/zz_generated.deepcopy.go b/go/controllers/wgpolicyk8s.io/v1alpha2/zz_generated.deepcopy.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1alpha2/zz_generated.deepcopy.go rename to go/controllers/wgpolicyk8s.io/v1alpha2/zz_generated.deepcopy.go diff --git a/controllers/wgpolicyk8s.io/v1beta1/clusterpolicyreport_types.go b/go/controllers/wgpolicyk8s.io/v1beta1/clusterpolicyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1beta1/clusterpolicyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1beta1/clusterpolicyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1beta1/doc.go b/go/controllers/wgpolicyk8s.io/v1beta1/doc.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1beta1/doc.go rename to go/controllers/wgpolicyk8s.io/v1beta1/doc.go diff --git a/controllers/wgpolicyk8s.io/v1beta1/groupversion_info.go b/go/controllers/wgpolicyk8s.io/v1beta1/groupversion_info.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1beta1/groupversion_info.go rename to go/controllers/wgpolicyk8s.io/v1beta1/groupversion_info.go diff --git a/controllers/wgpolicyk8s.io/v1beta1/policyreport_types.go b/go/controllers/wgpolicyk8s.io/v1beta1/policyreport_types.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1beta1/policyreport_types.go rename to go/controllers/wgpolicyk8s.io/v1beta1/policyreport_types.go diff --git a/controllers/wgpolicyk8s.io/v1beta1/zz_generated.deepcopy.go b/go/controllers/wgpolicyk8s.io/v1beta1/zz_generated.deepcopy.go similarity index 100% rename from controllers/wgpolicyk8s.io/v1beta1/zz_generated.deepcopy.go rename to go/controllers/wgpolicyk8s.io/v1beta1/zz_generated.deepcopy.go diff --git a/docs/images/e2e-pm.drawio b/go/docs/images/e2e-pm.drawio similarity index 100% rename from docs/images/e2e-pm.drawio rename to go/docs/images/e2e-pm.drawio diff --git a/docs/images/e2e-pm.png b/go/docs/images/e2e-pm.png similarity index 100% rename from docs/images/e2e-pm.png rename to go/docs/images/e2e-pm.png diff --git a/docs/kyverno/README.md b/go/docs/kyverno/README.md similarity index 94% rename from docs/kyverno/README.md rename to go/docs/kyverno/README.md index 068f86b..7d349fa 100644 --- a/docs/kyverno/README.md +++ b/go/docs/kyverno/README.md @@ -2,7 +2,7 @@ ### Continuous Compliance by C2P -https://github.com/IBM/compliance-to-policy/assets/113283236/4b0b5357-4025-46c8-8d88-1f4c00538795 +https://github.com/oscal-compass/compliance-to-policy/assets/113283236/4b0b5357-4025-46c8-8d88-1f4c00538795 ### Usage of C2P CLI ``` @@ -26,7 +26,7 @@ Use "c2pcli kyverno [command] --help" for more information about a command. ### Prerequisites 1. Prepare Kyverno Policy Resources - - You can use [policy-resources for test](/pkg/testdata/kyverno/policy-resources) + - You can use [policy-resources for test](/go/pkg/testdata/kyverno/policy-resources) - For bring your own policies, please see [Bring your own Kyverno Policy Resources](#bring-your-own-kyverno-policy-resources) #### Convert OSCAL to Kyverno Policy diff --git a/docs/kyverno/kyverno-workflow.drawio b/go/docs/kyverno/kyverno-workflow.drawio similarity index 100% rename from docs/kyverno/kyverno-workflow.drawio rename to go/docs/kyverno/kyverno-workflow.drawio diff --git a/docs/kyverno/oscal-vs-kyverno-result-mapping.csv b/go/docs/kyverno/oscal-vs-kyverno-result-mapping.csv similarity index 100% rename from docs/kyverno/oscal-vs-kyverno-result-mapping.csv rename to go/docs/kyverno/oscal-vs-kyverno-result-mapping.csv diff --git a/docs/ocm/README.md b/go/docs/ocm/README.md similarity index 98% rename from docs/ocm/README.md rename to go/docs/ocm/README.md index e30501a..406109d 100644 --- a/docs/ocm/README.md +++ b/go/docs/ocm/README.md @@ -22,14 +22,14 @@ Use "c2pcli ocm [command] --help" for more information about a command. ### Prerequisites 1. Install [Policy Generator Plugin](https://github.com/open-cluster-management-io/policy-generator-plugin#as-a-kustomize-plugin) 1. Prepare OCM Policy Resources - - You can use [policy-resources for test](/pkg/testdata/ocm/policies) + - You can use [policy-resources for test](/go/pkg/testdata/ocm/policies) - You can also use [Policy Collection](https://github.com/open-cluster-management-io/policy-collection). Please see [C2P Decomposer](#c2p-decomposer) ### Manual end-to-end use case #### Outline 1. Create OSCAL Component Definition - - Use example one. In real cases, a user writes OSCAL by Authoring tool like [Trestle](https://ibm.github.io/compliance-trestle/)) + - Use example one. In real cases, a user writes OSCAL by Authoring tool like [Trestle](https://github.com/oscal-compass/compliance-trestle)) 1. Run oscal2policy to generate OCM Policies from OSCAL 1. Deploy generated OCM Policies to OCM Hub 1. Get OCM Policies from OCM Hub @@ -213,7 +213,7 @@ Decompose OCM poicy collection to kubernetes resources composing each OCM policy │   ├── kustomization.yaml ``` ### C2P Composer -Compose OCM Policy from policy resources from compliance information (for example, [compliance.yaml](cmd/compose/compliance.yaml)) +Compose OCM Policy from policy resources from compliance information (for example, [compliance.yaml](/go/cmd/compose/compliance.yaml)) 1. Run C2P Composer ``` diff --git a/docs/ocm/c2p-config.yaml b/go/docs/ocm/c2p-config.yaml similarity index 100% rename from docs/ocm/c2p-config.yaml rename to go/docs/ocm/c2p-config.yaml diff --git a/docs/ocm/final-outputs/assessment-results.json b/go/docs/ocm/final-outputs/assessment-results.json similarity index 100% rename from docs/ocm/final-outputs/assessment-results.json rename to go/docs/ocm/final-outputs/assessment-results.json diff --git a/docs/ocm/final-outputs/compliance-posture.md b/go/docs/ocm/final-outputs/compliance-posture.md similarity index 100% rename from docs/ocm/final-outputs/compliance-posture.md rename to go/docs/ocm/final-outputs/compliance-posture.md diff --git a/docs/ocm/final-outputs/ocm-policies/ConfigMap.c2p.c2p-parameters.yaml b/go/docs/ocm/final-outputs/ocm-policies/ConfigMap.c2p.c2p-parameters.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/ConfigMap.c2p.c2p-parameters.yaml rename to go/docs/ocm/final-outputs/ocm-policies/ConfigMap.c2p.c2p-parameters.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/Placement.c2p.placement-managed-kubernetes.yaml b/go/docs/ocm/final-outputs/ocm-policies/Placement.c2p.placement-managed-kubernetes.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/Placement.c2p.placement-managed-kubernetes.yaml rename to go/docs/ocm/final-outputs/ocm-policies/Placement.c2p.placement-managed-kubernetes.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/PlacementBinding.c2p.policy-set.yaml b/go/docs/ocm/final-outputs/ocm-policies/PlacementBinding.c2p.policy-set.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/PlacementBinding.c2p.policy-set.yaml rename to go/docs/ocm/final-outputs/ocm-policies/PlacementBinding.c2p.policy-set.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-deployment.yaml b/go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-deployment.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-deployment.yaml rename to go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-deployment.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-high-scan.yaml b/go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-high-scan.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-high-scan.yaml rename to go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-high-scan.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-install-kyverno-from-manifests.yaml b/go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-install-kyverno-from-manifests.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-install-kyverno-from-manifests.yaml rename to go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-install-kyverno-from-manifests.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-kyverno-require-labels.yaml b/go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-kyverno-require-labels.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-kyverno-require-labels.yaml rename to go/docs/ocm/final-outputs/ocm-policies/Policy.c2p.policy-kyverno-require-labels.yaml diff --git a/docs/ocm/final-outputs/ocm-policies/PolicySet.c2p.managed-kubernetes.yaml b/go/docs/ocm/final-outputs/ocm-policies/PolicySet.c2p.managed-kubernetes.yaml similarity index 100% rename from docs/ocm/final-outputs/ocm-policies/PolicySet.c2p.managed-kubernetes.yaml rename to go/docs/ocm/final-outputs/ocm-policies/PolicySet.c2p.managed-kubernetes.yaml diff --git a/docs/ocm/images/manual-end-to-end-use-case.drawio b/go/docs/ocm/images/manual-end-to-end-use-case.drawio similarity index 100% rename from docs/ocm/images/manual-end-to-end-use-case.drawio rename to go/docs/ocm/images/manual-end-to-end-use-case.drawio diff --git a/docs/ocm/images/manual-end-to-end-use-case.png b/go/docs/ocm/images/manual-end-to-end-use-case.png similarity index 100% rename from docs/ocm/images/manual-end-to-end-use-case.png rename to go/docs/ocm/images/manual-end-to-end-use-case.png diff --git a/docs/ocm/oscal-ar-vs-ocm-status-mapping.csv b/go/docs/ocm/oscal-ar-vs-ocm-status-mapping.csv similarity index 100% rename from docs/ocm/oscal-ar-vs-ocm-status-mapping.csv rename to go/docs/ocm/oscal-ar-vs-ocm-status-mapping.csv diff --git a/docs/ocm/oscal/component-definition.csv b/go/docs/ocm/oscal/component-definition.csv similarity index 100% rename from docs/ocm/oscal/component-definition.csv rename to go/docs/ocm/oscal/component-definition.csv diff --git a/docs/ocm/oscal/component-definition.json b/go/docs/ocm/oscal/component-definition.json similarity index 100% rename from docs/ocm/oscal/component-definition.json rename to go/docs/ocm/oscal/component-definition.json diff --git a/docs/ocm/oscal/profile.json b/go/docs/ocm/oscal/profile.json similarity index 100% rename from docs/ocm/oscal/profile.json rename to go/docs/ocm/oscal/profile.json diff --git a/go.mod b/go/go.mod similarity index 99% rename from go.mod rename to go/go.mod index eb74e73..382a947 100644 --- a/go.mod +++ b/go/go.mod @@ -1,4 +1,4 @@ -module github.com/IBM/compliance-to-policy +module github.com/oscal-compass/compliance-to-policy/go go 1.19 diff --git a/go.sum b/go/go.sum similarity index 100% rename from go.sum rename to go/go.sum diff --git a/hack/add-header.sh b/go/hack/add-header.sh similarity index 100% rename from hack/add-header.sh rename to go/hack/add-header.sh diff --git a/hack/boilerplate.go.txt b/go/hack/boilerplate.go.txt similarity index 100% rename from hack/boilerplate.go.txt rename to go/hack/boilerplate.go.txt diff --git a/hack/boilerplate.sh.txt b/go/hack/boilerplate.sh.txt similarity index 100% rename from hack/boilerplate.sh.txt rename to go/hack/boilerplate.sh.txt diff --git a/hack/cleanup-tmp-files-in-tests.sh b/go/hack/cleanup-tmp-files-in-tests.sh similarity index 100% rename from hack/cleanup-tmp-files-in-tests.sh rename to go/hack/cleanup-tmp-files-in-tests.sh diff --git a/hack/format/format.py b/go/hack/format/format.py similarity index 100% rename from hack/format/format.py rename to go/hack/format/format.py diff --git a/hack/format/requirements.txt b/go/hack/format/requirements.txt similarity index 100% rename from hack/format/requirements.txt rename to go/hack/format/requirements.txt diff --git a/hack/policy-checker/.gitignore b/go/hack/policy-checker/.gitignore similarity index 100% rename from hack/policy-checker/.gitignore rename to go/hack/policy-checker/.gitignore diff --git a/hack/policy-checker/README.md b/go/hack/policy-checker/README.md similarity index 100% rename from hack/policy-checker/README.md rename to go/hack/policy-checker/README.md diff --git a/hack/policy-checker/check.py b/go/hack/policy-checker/check.py similarity index 100% rename from hack/policy-checker/check.py rename to go/hack/policy-checker/check.py diff --git a/hack/policy-checker/common.py b/go/hack/policy-checker/common.py similarity index 100% rename from hack/policy-checker/common.py rename to go/hack/policy-checker/common.py diff --git a/hack/policy-checker/list_generated_policies.py b/go/hack/policy-checker/list_generated_policies.py similarity index 100% rename from hack/policy-checker/list_generated_policies.py rename to go/hack/policy-checker/list_generated_policies.py diff --git a/hack/policy-checker/requirements.txt b/go/hack/policy-checker/requirements.txt similarity index 100% rename from hack/policy-checker/requirements.txt rename to go/hack/policy-checker/requirements.txt diff --git a/main.go b/go/main.go similarity index 88% rename from main.go rename to go/main.go index 1bf7d47..f7e12a9 100644 --- a/main.go +++ b/go/main.go @@ -34,15 +34,15 @@ import ( "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" - compliancetopolicycontrollerv1alpha1 "github.com/IBM/compliance-to-policy/api/v1alpha1" - wgpolicyk8sv1alpha2 "github.com/IBM/compliance-to-policy/controllers/wgpolicyk8s.io/v1alpha2" - - "github.com/IBM/compliance-to-policy/controllers/compliancedeployment" - ctrlrefkcp "github.com/IBM/compliance-to-policy/controllers/controlreference/kcp" - ctrlrefocm "github.com/IBM/compliance-to-policy/controllers/controlreference/ocm" - "github.com/IBM/compliance-to-policy/controllers/resultcollector" - "github.com/IBM/compliance-to-policy/controllers/utils/ocmk8sclients" - "github.com/IBM/compliance-to-policy/pkg" + compliancetopolicycontrollerv1alpha1 "github.com/oscal-compass/compliance-to-policy/go/api/v1alpha1" + wgpolicyk8sv1alpha2 "github.com/oscal-compass/compliance-to-policy/go/controllers/wgpolicyk8s.io/v1alpha2" + + "github.com/oscal-compass/compliance-to-policy/go/controllers/compliancedeployment" + ctrlrefkcp "github.com/oscal-compass/compliance-to-policy/go/controllers/controlreference/kcp" + ctrlrefocm "github.com/oscal-compass/compliance-to-policy/go/controllers/controlreference/ocm" + "github.com/oscal-compass/compliance-to-policy/go/controllers/resultcollector" + "github.com/oscal-compass/compliance-to-policy/go/controllers/utils/ocmk8sclients" + "github.com/oscal-compass/compliance-to-policy/go/pkg" //+kubebuilder:scaffold:imports ) diff --git a/pkg/decomposer/decomposer.go b/go/pkg/decomposer/decomposer.go similarity index 94% rename from pkg/decomposer/decomposer.go rename to go/pkg/decomposer/decomposer.go index b9f7da2..b96e758 100644 --- a/pkg/decomposer/decomposer.go +++ b/go/pkg/decomposer/decomposer.go @@ -21,10 +21,10 @@ import ( "os" "path/filepath" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - . "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - "github.com/IBM/compliance-to-policy/pkg/types/policycomposition" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + . "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policycomposition" ) type Decomposer struct { diff --git a/pkg/gitutils.go b/go/pkg/gitutils.go similarity index 100% rename from pkg/gitutils.go rename to go/pkg/gitutils.go diff --git a/pkg/kyverno/configparser.go b/go/pkg/kyverno/configparser.go similarity index 91% rename from pkg/kyverno/configparser.go rename to go/pkg/kyverno/configparser.go index a85b70d..4a17525 100644 --- a/pkg/kyverno/configparser.go +++ b/go/pkg/kyverno/configparser.go @@ -19,10 +19,10 @@ package kyverno import ( "fmt" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/oscal" - "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - typear "github.com/IBM/compliance-to-policy/pkg/types/oscal/assessmentresults" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + typear "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/assessmentresults" "go.uber.org/zap" ) diff --git a/pkg/kyverno/fileloader.go b/go/pkg/kyverno/fileloader.go similarity index 98% rename from pkg/kyverno/fileloader.go rename to go/pkg/kyverno/fileloader.go index 13f564a..82cb07c 100644 --- a/pkg/kyverno/fileloader.go +++ b/go/pkg/kyverno/fileloader.go @@ -23,7 +23,7 @@ import ( "regexp" "strings" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "go.uber.org/zap" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) diff --git a/pkg/kyverno/oscal2policy.go b/go/pkg/kyverno/oscal2policy.go similarity index 92% rename from pkg/kyverno/oscal2policy.go rename to go/pkg/kyverno/oscal2policy.go index 788b85f..30eef22 100644 --- a/pkg/kyverno/oscal2policy.go +++ b/go/pkg/kyverno/oscal2policy.go @@ -19,8 +19,8 @@ package kyverno import ( "fmt" - "github.com/IBM/compliance-to-policy/pkg" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" cp "github.com/otiai10/copy" "go.uber.org/zap" ) diff --git a/pkg/kyverno/oscal2policy_test.go b/go/pkg/kyverno/oscal2policy_test.go similarity index 94% rename from pkg/kyverno/oscal2policy_test.go rename to go/pkg/kyverno/oscal2policy_test.go index 8dc2d5c..60dd6a3 100644 --- a/pkg/kyverno/oscal2policy_test.go +++ b/go/pkg/kyverno/oscal2policy_test.go @@ -20,8 +20,8 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" "github.com/stretchr/testify/assert" ) diff --git a/pkg/kyverno/result2oscal.go b/go/pkg/kyverno/result2oscal.go similarity index 95% rename from pkg/kyverno/result2oscal.go rename to go/pkg/kyverno/result2oscal.go index 7cb7500..eb9c485 100644 --- a/pkg/kyverno/result2oscal.go +++ b/go/pkg/kyverno/result2oscal.go @@ -21,12 +21,12 @@ import ( "strings" "time" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/oscal" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - typear "github.com/IBM/compliance-to-policy/pkg/types/oscal/assessmentresults" - typeoscalcommon "github.com/IBM/compliance-to-policy/pkg/types/oscal/common" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + typear "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/assessmentresults" + typeoscalcommon "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/common" "go.uber.org/zap" "k8s.io/apimachinery/pkg/util/sets" typepolr "sigs.k8s.io/wg-policy-prototypes/policy-report/pkg/api/wgpolicyk8s.io/v1beta1" diff --git a/pkg/ocm/configparser.go b/go/pkg/ocm/configparser.go similarity index 92% rename from pkg/ocm/configparser.go rename to go/pkg/ocm/configparser.go index 2ce0fed..68eb14d 100644 --- a/pkg/ocm/configparser.go +++ b/go/pkg/ocm/configparser.go @@ -19,9 +19,9 @@ package ocm import ( "fmt" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/oscal" - "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" ) type C2PCRParser struct { diff --git a/pkg/ocm/helper.go b/go/pkg/ocm/helper.go similarity index 95% rename from pkg/ocm/helper.go rename to go/pkg/ocm/helper.go index c99ef5f..3b12ea4 100644 --- a/pkg/ocm/helper.go +++ b/go/pkg/ocm/helper.go @@ -17,8 +17,8 @@ limitations under the License. package ocm import ( - typeconfigpolicy "github.com/IBM/compliance-to-policy/pkg/types/configurationpolicy" - typepolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" + typeconfigpolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/configurationpolicy" + typepolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" typepolr "sigs.k8s.io/wg-policy-prototypes/policy-report/pkg/api/wgpolicyk8s.io/v1beta1" ) diff --git a/pkg/ocm/oscal2policy.go b/go/pkg/ocm/oscal2policy.go similarity index 96% rename from pkg/ocm/oscal2policy.go rename to go/pkg/ocm/oscal2policy.go index 4ce0bea..a49accb 100644 --- a/pkg/ocm/oscal2policy.go +++ b/go/pkg/ocm/oscal2policy.go @@ -24,11 +24,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/sets" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/oscal" - policygenerator "github.com/IBM/compliance-to-policy/pkg/policygenerator" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - pgtype "github.com/IBM/compliance-to-policy/pkg/types/policygenerator" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + policygenerator "github.com/oscal-compass/compliance-to-policy/go/pkg/policygenerator" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + pgtype "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policygenerator" cp "github.com/otiai10/copy" "go.uber.org/zap" "sigs.k8s.io/kustomize/api/resmap" diff --git a/pkg/ocm/oscal2policy_test.go b/go/pkg/ocm/oscal2policy_test.go similarity index 94% rename from pkg/ocm/oscal2policy_test.go rename to go/pkg/ocm/oscal2policy_test.go index 1e62d8f..a3e45f5 100644 --- a/pkg/ocm/oscal2policy_test.go +++ b/go/pkg/ocm/oscal2policy_test.go @@ -20,8 +20,8 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" "github.com/stretchr/testify/assert" ) diff --git a/pkg/ocm/result2oscal.go b/go/pkg/ocm/result2oscal.go similarity index 92% rename from pkg/ocm/result2oscal.go rename to go/pkg/ocm/result2oscal.go index b7e6a5b..858865c 100644 --- a/pkg/ocm/result2oscal.go +++ b/go/pkg/ocm/result2oscal.go @@ -20,19 +20,19 @@ import ( "fmt" "time" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" sigyaml "sigs.k8s.io/yaml" "k8s.io/apimachinery/pkg/util/sets" - "github.com/IBM/compliance-to-policy/pkg/oscal" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - typear "github.com/IBM/compliance-to-policy/pkg/types/oscal/assessmentresults" - typeoscalcommon "github.com/IBM/compliance-to-policy/pkg/types/oscal/common" - typeplacementdecision "github.com/IBM/compliance-to-policy/pkg/types/placementdecision" - typepolicy "github.com/IBM/compliance-to-policy/pkg/types/policy" - typereport "github.com/IBM/compliance-to-policy/pkg/types/report" - typeutils "github.com/IBM/compliance-to-policy/pkg/types/utils" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + typear "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/assessmentresults" + typeoscalcommon "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/common" + typeplacementdecision "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placementdecision" + typepolicy "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" + typereport "github.com/oscal-compass/compliance-to-policy/go/pkg/types/report" + typeutils "github.com/oscal-compass/compliance-to-policy/go/pkg/types/utils" ) type ResultToOscal struct { diff --git a/pkg/ocm/result2oscal_test.go b/go/pkg/ocm/result2oscal_test.go similarity index 92% rename from pkg/ocm/result2oscal_test.go rename to go/pkg/ocm/result2oscal_test.go index b8b6226..33b7ca0 100644 --- a/pkg/ocm/result2oscal_test.go +++ b/go/pkg/ocm/result2oscal_test.go @@ -20,11 +20,11 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - typear "github.com/IBM/compliance-to-policy/pkg/types/oscal/assessmentresults" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + typear "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/assessmentresults" "github.com/stretchr/testify/assert" ) diff --git a/pkg/oscal/oscal.go b/go/pkg/oscal/oscal.go similarity index 95% rename from pkg/oscal/oscal.go rename to go/pkg/oscal/oscal.go index 99e1d3f..d860ce4 100644 --- a/pkg/oscal/oscal.go +++ b/go/pkg/oscal/oscal.go @@ -19,13 +19,13 @@ package oscal import ( "strings" - "github.com/IBM/compliance-to-policy/pkg/decomposer" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - "github.com/IBM/compliance-to-policy/pkg/types/oscal" - typecommon "github.com/IBM/compliance-to-policy/pkg/types/oscal/common" - cd "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" "github.com/google/uuid" + "github.com/oscal-compass/compliance-to-policy/go/pkg/decomposer" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal" + typecommon "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/common" + cd "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" ) var standardFromPolicyCollectionToOscal map[string]string = map[string]string{ diff --git a/pkg/oscal/oscal_test.go b/go/pkg/oscal/oscal_test.go similarity index 94% rename from pkg/oscal/oscal_test.go rename to go/pkg/oscal/oscal_test.go index 81d1117..b20a8b0 100644 --- a/pkg/oscal/oscal_test.go +++ b/go/pkg/oscal/oscal_test.go @@ -24,11 +24,11 @@ import ( "strings" "testing" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - "github.com/IBM/compliance-to-policy/pkg/types/internalcompliance" - "github.com/IBM/compliance-to-policy/pkg/types/oscal" - cd "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/internalcompliance" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal" + cd "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" "github.com/stretchr/testify/assert" ) @@ -106,7 +106,7 @@ func TestTrestleCsv(t *testing.T) { ComponentDescription: "Description ...", ComponentType: "Service", } - namespace := "https://github.com/IBM/compliance-to-policy" + namespace := "https://github.com/oscal-compass/compliance-to-policy/go" trestlCsvRowsMap := makeTrestleCsvFromMasterData(componentProps, namespace, resourceTable) t.Log(trestlCsvRowsMap) diff --git a/pkg/oscal/parser.go b/go/pkg/oscal/parser.go similarity index 97% rename from pkg/oscal/parser.go rename to go/pkg/oscal/parser.go index 3e77e3f..56ad207 100644 --- a/pkg/oscal/parser.go +++ b/go/pkg/oscal/parser.go @@ -17,7 +17,7 @@ limitations under the License. package oscal import ( - . "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" + . "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" ) type RuleObject struct { diff --git a/pkg/oscal/testdata/NIST_SP-800-53_rev5_HIGH-baseline_profile.json b/go/pkg/oscal/testdata/NIST_SP-800-53_rev5_HIGH-baseline_profile.json similarity index 100% rename from pkg/oscal/testdata/NIST_SP-800-53_rev5_HIGH-baseline_profile.json rename to go/pkg/oscal/testdata/NIST_SP-800-53_rev5_HIGH-baseline_profile.json diff --git a/pkg/oscal/testdata/NIST_SP-800-53_rev5_LOW-baseline_profile.json b/go/pkg/oscal/testdata/NIST_SP-800-53_rev5_LOW-baseline_profile.json similarity index 100% rename from pkg/oscal/testdata/NIST_SP-800-53_rev5_LOW-baseline_profile.json rename to go/pkg/oscal/testdata/NIST_SP-800-53_rev5_LOW-baseline_profile.json diff --git a/pkg/oscal/testdata/NIST_SP-800-53_rev5_MODERATE-baseline_profile.json b/go/pkg/oscal/testdata/NIST_SP-800-53_rev5_MODERATE-baseline_profile.json similarity index 100% rename from pkg/oscal/testdata/NIST_SP-800-53_rev5_MODERATE-baseline_profile.json rename to go/pkg/oscal/testdata/NIST_SP-800-53_rev5_MODERATE-baseline_profile.json diff --git a/pkg/oscal/testdata/NIST_SP-800-53_rev5_catalog.json b/go/pkg/oscal/testdata/NIST_SP-800-53_rev5_catalog.json similarity index 100% rename from pkg/oscal/testdata/NIST_SP-800-53_rev5_catalog.json rename to go/pkg/oscal/testdata/NIST_SP-800-53_rev5_catalog.json diff --git a/pkg/oscal/testdata/component-definition.json b/go/pkg/oscal/testdata/component-definition.json similarity index 100% rename from pkg/oscal/testdata/component-definition.json rename to go/pkg/oscal/testdata/component-definition.json diff --git a/pkg/oscal/testdata/resources.csv b/go/pkg/oscal/testdata/resources.csv similarity index 100% rename from pkg/oscal/testdata/resources.csv rename to go/pkg/oscal/testdata/resources.csv diff --git a/pkg/oscal/testdata/results/interna-oscal-standards-high.yaml b/go/pkg/oscal/testdata/results/interna-oscal-standards-high.yaml similarity index 100% rename from pkg/oscal/testdata/results/interna-oscal-standards-high.yaml rename to go/pkg/oscal/testdata/results/interna-oscal-standards-high.yaml diff --git a/pkg/oscal/testdata/results/interna-oscal-standards-low.yaml b/go/pkg/oscal/testdata/results/interna-oscal-standards-low.yaml similarity index 100% rename from pkg/oscal/testdata/results/interna-oscal-standards-low.yaml rename to go/pkg/oscal/testdata/results/interna-oscal-standards-low.yaml diff --git a/pkg/oscal/testdata/results/interna-oscal-standards-moderate.yaml b/go/pkg/oscal/testdata/results/interna-oscal-standards-moderate.yaml similarity index 100% rename from pkg/oscal/testdata/results/interna-oscal-standards-moderate.yaml rename to go/pkg/oscal/testdata/results/interna-oscal-standards-moderate.yaml diff --git a/pkg/oscal/testdata/results/interna-oscal-standards.yaml b/go/pkg/oscal/testdata/results/interna-oscal-standards.yaml similarity index 100% rename from pkg/oscal/testdata/results/interna-oscal-standards.yaml rename to go/pkg/oscal/testdata/results/interna-oscal-standards.yaml diff --git a/pkg/oscal/testdata/results/internal-compliance-from-cd.yaml b/go/pkg/oscal/testdata/results/internal-compliance-from-cd.yaml similarity index 100% rename from pkg/oscal/testdata/results/internal-compliance-from-cd.yaml rename to go/pkg/oscal/testdata/results/internal-compliance-from-cd.yaml diff --git a/pkg/oscal/testdata/results/internal-compliance.yaml b/go/pkg/oscal/testdata/results/internal-compliance.yaml similarity index 100% rename from pkg/oscal/testdata/results/internal-compliance.yaml rename to go/pkg/oscal/testdata/results/internal-compliance.yaml diff --git a/pkg/parser/parser.go b/go/pkg/parser/parser.go similarity index 94% rename from pkg/parser/parser.go rename to go/pkg/parser/parser.go index 36e746d..a5b83a7 100644 --- a/pkg/parser/parser.go +++ b/go/pkg/parser/parser.go @@ -23,13 +23,13 @@ import ( "path/filepath" "strings" - "github.com/IBM/compliance-to-policy/pkg" - "github.com/IBM/compliance-to-policy/pkg/policygenerator" - "github.com/IBM/compliance-to-policy/pkg/tables" - "github.com/IBM/compliance-to-policy/pkg/tables/resources" - "github.com/IBM/compliance-to-policy/pkg/types/configurationpolicy" - "github.com/IBM/compliance-to-policy/pkg/types/policy" - typepolicygenerator "github.com/IBM/compliance-to-policy/pkg/types/policygenerator" + "github.com/oscal-compass/compliance-to-policy/go/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg/policygenerator" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables" + "github.com/oscal-compass/compliance-to-policy/go/pkg/tables/resources" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/configurationpolicy" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" + typepolicygenerator "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policygenerator" "go.uber.org/zap" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" utilyaml "k8s.io/apimachinery/pkg/util/yaml" diff --git a/pkg/parser/parser_test.go b/go/pkg/parser/parser_test.go similarity index 94% rename from pkg/parser/parser_test.go rename to go/pkg/parser/parser_test.go index 4028bf5..75958e2 100644 --- a/pkg/parser/parser_test.go +++ b/go/pkg/parser/parser_test.go @@ -21,7 +21,7 @@ import ( "os" "testing" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" ) //go:embed testdata/* diff --git a/pkg/parser/testdata/expected/policies.csv b/go/pkg/parser/testdata/expected/policies.csv similarity index 100% rename from pkg/parser/testdata/expected/policies.csv rename to go/pkg/parser/testdata/expected/policies.csv diff --git a/pkg/parser/testdata/expected/resources.csv b/go/pkg/parser/testdata/expected/resources.csv similarity index 100% rename from pkg/parser/testdata/expected/resources.csv rename to go/pkg/parser/testdata/expected/resources.csv diff --git a/pkg/parser/testdata/policy.yaml b/go/pkg/parser/testdata/policy.yaml similarity index 100% rename from pkg/parser/testdata/policy.yaml rename to go/pkg/parser/testdata/policy.yaml diff --git a/pkg/parser/util.go b/go/pkg/parser/util.go similarity index 100% rename from pkg/parser/util.go rename to go/pkg/parser/util.go diff --git a/pkg/parser/yamlloder.go b/go/pkg/parser/yamlloder.go similarity index 94% rename from pkg/parser/yamlloder.go rename to go/pkg/parser/yamlloder.go index 72a625d..dfe7ddc 100644 --- a/pkg/parser/yamlloder.go +++ b/go/pkg/parser/yamlloder.go @@ -20,8 +20,8 @@ import ( "errors" "io" - "github.com/IBM/compliance-to-policy/pkg/types/placements" - "github.com/IBM/compliance-to-policy/pkg/types/policy" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" "gopkg.in/yaml.v3" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml" diff --git a/pkg/parser/yamlloder_test.go b/go/pkg/parser/yamlloder_test.go similarity index 92% rename from pkg/parser/yamlloder_test.go rename to go/pkg/parser/yamlloder_test.go index 435225b..eee4fba 100644 --- a/pkg/parser/yamlloder_test.go +++ b/go/pkg/parser/yamlloder_test.go @@ -19,8 +19,8 @@ package parser import ( "testing" - "github.com/IBM/compliance-to-policy/pkg/types/placements" - "github.com/IBM/compliance-to-policy/pkg/types/policy" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/placements" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policy" "gopkg.in/yaml.v3" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8syaml "k8s.io/apimachinery/pkg/runtime/serializer/yaml" diff --git a/pkg/policygenerator/policygenerator.go b/go/pkg/policygenerator/policygenerator.go similarity index 97% rename from pkg/policygenerator/policygenerator.go rename to go/pkg/policygenerator/policygenerator.go index 6f5a3c0..d098540 100644 --- a/pkg/policygenerator/policygenerator.go +++ b/go/pkg/policygenerator/policygenerator.go @@ -17,7 +17,7 @@ limitations under the License. package policygenerator import ( - "github.com/IBM/compliance-to-policy/pkg/types/policygenerator" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/policygenerator" "sigs.k8s.io/kustomize/api/krusty" "sigs.k8s.io/kustomize/api/resmap" kustomizetypes "sigs.k8s.io/kustomize/api/types" diff --git a/pkg/policygenerator/policygenerator_test.go b/go/pkg/policygenerator/policygenerator_test.go similarity index 96% rename from pkg/policygenerator/policygenerator_test.go rename to go/pkg/policygenerator/policygenerator_test.go index 319e124..3855c35 100644 --- a/pkg/policygenerator/policygenerator_test.go +++ b/go/pkg/policygenerator/policygenerator_test.go @@ -20,7 +20,7 @@ import ( "fmt" "testing" - "github.com/IBM/compliance-to-policy/pkg" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "sigs.k8s.io/kustomize/api/krusty" "sigs.k8s.io/kustomize/api/types" ) diff --git a/pkg/policygenerator/testdata/input-kustomize/base/kustomization.yaml b/go/pkg/policygenerator/testdata/input-kustomize/base/kustomization.yaml similarity index 100% rename from pkg/policygenerator/testdata/input-kustomize/base/kustomization.yaml rename to go/pkg/policygenerator/testdata/input-kustomize/base/kustomization.yaml diff --git a/pkg/policygenerator/testdata/input-kustomize/base/nginx-pod.yaml b/go/pkg/policygenerator/testdata/input-kustomize/base/nginx-pod.yaml similarity index 100% rename from pkg/policygenerator/testdata/input-kustomize/base/nginx-pod.yaml rename to go/pkg/policygenerator/testdata/input-kustomize/base/nginx-pod.yaml diff --git a/pkg/policygenerator/testdata/input-kustomize/dev/kustomization.yml b/go/pkg/policygenerator/testdata/input-kustomize/dev/kustomization.yml similarity index 100% rename from pkg/policygenerator/testdata/input-kustomize/dev/kustomization.yml rename to go/pkg/policygenerator/testdata/input-kustomize/dev/kustomization.yml diff --git a/pkg/policygenerator/testdata/input-kustomize/kustomization.yml b/go/pkg/policygenerator/testdata/input-kustomize/kustomization.yml similarity index 100% rename from pkg/policygenerator/testdata/input-kustomize/kustomization.yml rename to go/pkg/policygenerator/testdata/input-kustomize/kustomization.yml diff --git a/pkg/policygenerator/testdata/input-kustomize/prod/kustomization.yml b/go/pkg/policygenerator/testdata/input-kustomize/prod/kustomization.yml similarity index 100% rename from pkg/policygenerator/testdata/input-kustomize/prod/kustomization.yml rename to go/pkg/policygenerator/testdata/input-kustomize/prod/kustomization.yml diff --git a/pkg/policygenerator/testdata/kustomization.yml b/go/pkg/policygenerator/testdata/kustomization.yml similarity index 100% rename from pkg/policygenerator/testdata/kustomization.yml rename to go/pkg/policygenerator/testdata/kustomization.yml diff --git a/pkg/policygenerator/testdata/policyGenerator-kustomize.yaml b/go/pkg/policygenerator/testdata/policyGenerator-kustomize.yaml similarity index 100% rename from pkg/policygenerator/testdata/policyGenerator-kustomize.yaml rename to go/pkg/policygenerator/testdata/policyGenerator-kustomize.yaml diff --git a/pkg/pvpcommon/oscal2posture.go b/go/pkg/pvpcommon/oscal2posture.go similarity index 91% rename from pkg/pvpcommon/oscal2posture.go rename to go/pkg/pvpcommon/oscal2posture.go index 1ecf3cf..d3df0fa 100644 --- a/pkg/pvpcommon/oscal2posture.go +++ b/go/pkg/pvpcommon/oscal2posture.go @@ -25,11 +25,11 @@ import ( "go.uber.org/zap" - "github.com/IBM/compliance-to-policy/pkg/oscal" - tp "github.com/IBM/compliance-to-policy/pkg/pvpcommon/template" - typec2pcr "github.com/IBM/compliance-to-policy/pkg/types/c2pcr" - typear "github.com/IBM/compliance-to-policy/pkg/types/oscal/assessmentresults" - typecd "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + tp "github.com/oscal-compass/compliance-to-policy/go/pkg/pvpcommon/template" + typec2pcr "github.com/oscal-compass/compliance-to-policy/go/pkg/types/c2pcr" + typear "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/assessmentresults" + typecd "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" ) //go:embed template/*.md diff --git a/pkg/pvpcommon/template/model.go b/go/pkg/pvpcommon/template/model.go similarity index 100% rename from pkg/pvpcommon/template/model.go rename to go/pkg/pvpcommon/template/model.go diff --git a/pkg/pvpcommon/template/template.md b/go/pkg/pvpcommon/template/template.md similarity index 100% rename from pkg/pvpcommon/template/template.md rename to go/pkg/pvpcommon/template/template.md diff --git a/pkg/tables/resources/resource-table.go b/go/pkg/tables/resources/resource-table.go similarity index 98% rename from pkg/tables/resources/resource-table.go rename to go/pkg/tables/resources/resource-table.go index 6450dc1..d51cdae 100644 --- a/pkg/tables/resources/resource-table.go +++ b/go/pkg/tables/resources/resource-table.go @@ -22,8 +22,8 @@ import ( "os" "strings" - "github.com/IBM/compliance-to-policy/pkg" "github.com/olekukonko/tablewriter" + "github.com/oscal-compass/compliance-to-policy/go/pkg" "go.uber.org/zap" ) diff --git a/pkg/tables/table.go b/go/pkg/tables/table.go similarity index 100% rename from pkg/tables/table.go rename to go/pkg/tables/table.go diff --git a/pkg/testdata/compliance.yaml b/go/pkg/testdata/compliance.yaml similarity index 100% rename from pkg/testdata/compliance.yaml rename to go/pkg/testdata/compliance.yaml diff --git a/pkg/testdata/kyverno/c2p-config.yaml b/go/pkg/testdata/kyverno/c2p-config.yaml similarity index 100% rename from pkg/testdata/kyverno/c2p-config.yaml rename to go/pkg/testdata/kyverno/c2p-config.yaml diff --git a/pkg/testdata/kyverno/component-definition.json b/go/pkg/testdata/kyverno/component-definition.json similarity index 100% rename from pkg/testdata/kyverno/component-definition.json rename to go/pkg/testdata/kyverno/component-definition.json diff --git a/pkg/testdata/kyverno/policy-reports/clusterpolicies.kyverno.io.yaml b/go/pkg/testdata/kyverno/policy-reports/clusterpolicies.kyverno.io.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-reports/clusterpolicies.kyverno.io.yaml rename to go/pkg/testdata/kyverno/policy-reports/clusterpolicies.kyverno.io.yaml diff --git a/pkg/testdata/kyverno/policy-reports/clusterpolicyreports.wgpolicyk8s.io.yaml b/go/pkg/testdata/kyverno/policy-reports/clusterpolicyreports.wgpolicyk8s.io.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-reports/clusterpolicyreports.wgpolicyk8s.io.yaml rename to go/pkg/testdata/kyverno/policy-reports/clusterpolicyreports.wgpolicyk8s.io.yaml diff --git a/pkg/testdata/kyverno/policy-reports/policies.kyverno.io.yaml b/go/pkg/testdata/kyverno/policy-reports/policies.kyverno.io.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-reports/policies.kyverno.io.yaml rename to go/pkg/testdata/kyverno/policy-reports/policies.kyverno.io.yaml diff --git a/pkg/testdata/kyverno/policy-reports/policyreports.wgpolicyk8s.io.yaml b/go/pkg/testdata/kyverno/policy-reports/policyreports.wgpolicyk8s.io.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-reports/policyreports.wgpolicyk8s.io.yaml rename to go/pkg/testdata/kyverno/policy-reports/policyreports.wgpolicyk8s.io.yaml diff --git a/pkg/testdata/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml b/go/pkg/testdata/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml rename to go/pkg/testdata/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml diff --git a/pkg/testdata/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml b/go/pkg/testdata/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml similarity index 100% rename from pkg/testdata/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml rename to go/pkg/testdata/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml diff --git a/pkg/testdata/ocm/assessment-results.json b/go/pkg/testdata/ocm/assessment-results.json similarity index 100% rename from pkg/testdata/ocm/assessment-results.json rename to go/pkg/testdata/ocm/assessment-results.json diff --git a/pkg/testdata/ocm/catalog.json b/go/pkg/testdata/ocm/catalog.json similarity index 100% rename from pkg/testdata/ocm/catalog.json rename to go/pkg/testdata/ocm/catalog.json diff --git a/pkg/testdata/ocm/component-definition.json b/go/pkg/testdata/ocm/component-definition.json similarity index 100% rename from pkg/testdata/ocm/component-definition.json rename to go/pkg/testdata/ocm/component-definition.json diff --git a/pkg/testdata/ocm/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml b/go/pkg/testdata/ocm/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml rename to go/pkg/testdata/ocm/policies/add-chrony/add-chrony-worker/MachineConfig.50-worker-chrony.0.yaml diff --git a/pkg/testdata/ocm/policies/add-chrony/kustomization.yaml b/go/pkg/testdata/ocm/policies/add-chrony/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/add-chrony/kustomization.yaml rename to go/pkg/testdata/ocm/policies/add-chrony/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/add-chrony/policy-generator.yaml b/go/pkg/testdata/ocm/policies/add-chrony/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/add-chrony/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/add-chrony/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/kustomization.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/kustomization.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/odf-lvmcluster/LVMCluster.odf-lvmcluster.0.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-generator.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Namespace.openshift-storage.0.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/OperatorGroup.openshift-storage-operatorgroup.0.yaml diff --git a/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml b/go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml rename to go/pkg/testdata/ocm/policies/install-odf-lvm-operator/policy-odf-lvm-operator/Subscription.lvm-operator.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-deployment/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-deployment/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-deployment/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-deployment/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-deployment/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-deployment/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-deployment/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-deployment/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml b/go/pkg/testdata/ocm/policies/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml rename to go/pkg/testdata/ocm/policies/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-disallowed-roles/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-disallowed-roles/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-disallowed-roles/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-disallowed-roles/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml b/go/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml rename to go/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-disallowed-roles/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-disallowed-roles/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml b/go/pkg/testdata/ocm/policies/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml rename to go/pkg/testdata/ocm/policies/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml b/go/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml rename to go/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml b/go/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml rename to go/pkg/testdata/ocm/policies/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-high-scan/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-high-scan/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-high-scan/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-high-scan/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-high-scan/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-high-scan/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-high-scan/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-high-scan/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-generaterequest.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-generaterequest.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-generaterequest.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-generaterequest.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policies.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policies.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policies.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policies.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policyreport.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policyreport.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policyreport.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-policyreport.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-reports.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-reports.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-reports.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-reports.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-updaterequest.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-updaterequest.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-updaterequest.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:admin-updaterequest.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:events.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:events.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:events.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:events.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:generate.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:generate.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:generate.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:generate.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:policies.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:policies.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:policies.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:policies.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:userinfo.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:userinfo.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:userinfo.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:userinfo.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:view.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:view.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:view.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:view.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:webhook.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:webhook.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:webhook.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRole.kyverno:webhook.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRoleBinding.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRoleBinding.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRoleBinding.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ClusterRoleBinding.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno-metrics.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno-metrics.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno-metrics.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno-metrics.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ConfigMap.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.admissionreports.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.admissionreports.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.admissionreports.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.admissionreports.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.backgroundscanreports.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.backgroundscanreports.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.backgroundscanreports.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.backgroundscanreports.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusteradmissionreports.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusteradmissionreports.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusteradmissionreports.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusteradmissionreports.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterbackgroundscanreports.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterbackgroundscanreports.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterbackgroundscanreports.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterbackgroundscanreports.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicies.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicies.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicies.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicies.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicyreports.wgpolicyk8s.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicyreports.wgpolicyk8s.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicyreports.wgpolicyk8s.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.clusterpolicyreports.wgpolicyk8s.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.generaterequests.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.generaterequests.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.generaterequests.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.generaterequests.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policies.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policies.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policies.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policies.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policyreports.wgpolicyk8s.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policyreports.wgpolicyk8s.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policyreports.wgpolicyk8s.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.policyreports.wgpolicyk8s.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.updaterequests.kyverno.io.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.updaterequests.kyverno.io.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.updaterequests.kyverno.io.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/CustomResourceDefinition.updaterequests.kyverno.io.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Deployment.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Deployment.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Deployment.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Deployment.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Namespace.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Namespace.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Namespace.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Namespace.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Role.kyverno:leaderelection.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Role.kyverno:leaderelection.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Role.kyverno:leaderelection.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Role.kyverno:leaderelection.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/RoleBinding.kyverno:leaderelection.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/RoleBinding.kyverno:leaderelection.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/RoleBinding.kyverno:leaderelection.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/RoleBinding.kyverno:leaderelection.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc-metrics.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc-metrics.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc-metrics.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc-metrics.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/Service.kyverno-svc.yaml diff --git a/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ServiceAccount.kyverno.yaml b/go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ServiceAccount.kyverno.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ServiceAccount.kyverno.yaml rename to go/pkg/testdata/ocm/policies/policy-install-kyverno-from-manifests/policy-install-kyverno-from-manifests/ServiceAccount.kyverno.yaml diff --git a/pkg/testdata/ocm/policies/policy-kyverno-require-labels/check-kyverno-reports/require-lables.yaml b/go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/check-kyverno-reports/require-lables.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-kyverno-require-labels/check-kyverno-reports/require-lables.yaml rename to go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/check-kyverno-reports/require-lables.yaml diff --git a/pkg/testdata/ocm/policies/policy-kyverno-require-labels/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-kyverno-require-labels/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-kyverno-require-labels/ClusterPolicy.require-labels.0.yaml b/go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-kyverno-require-labels/ClusterPolicy.require-labels.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-kyverno-require-labels/ClusterPolicy.require-labels.0.yaml rename to go/pkg/testdata/ocm/policies/policy-kyverno-require-labels/policy-kyverno-require-labels/ClusterPolicy.require-labels.0.yaml diff --git a/pkg/testdata/ocm/policies/policy-nginx-deployment/kustomization.yaml b/go/pkg/testdata/ocm/policies/policy-nginx-deployment/kustomization.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-nginx-deployment/kustomization.yaml rename to go/pkg/testdata/ocm/policies/policy-nginx-deployment/kustomization.yaml diff --git a/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-generator.yaml b/go/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-generator.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-nginx-deployment/policy-generator.yaml rename to go/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-generator.yaml diff --git a/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml b/go/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml similarity index 100% rename from pkg/testdata/ocm/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml rename to go/pkg/testdata/ocm/policies/policy-nginx-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml diff --git a/pkg/testdata/ocm/policy-results/placementdecisions.cluster.open-cluster-management.io.yaml b/go/pkg/testdata/ocm/policy-results/placementdecisions.cluster.open-cluster-management.io.yaml similarity index 100% rename from pkg/testdata/ocm/policy-results/placementdecisions.cluster.open-cluster-management.io.yaml rename to go/pkg/testdata/ocm/policy-results/placementdecisions.cluster.open-cluster-management.io.yaml diff --git a/pkg/testdata/ocm/policy-results/policies.policy.open-cluster-management.io.yaml b/go/pkg/testdata/ocm/policy-results/policies.policy.open-cluster-management.io.yaml similarity index 100% rename from pkg/testdata/ocm/policy-results/policies.policy.open-cluster-management.io.yaml rename to go/pkg/testdata/ocm/policy-results/policies.policy.open-cluster-management.io.yaml diff --git a/pkg/testdata/ocm/policy-results/policysets.policy.open-cluster-management.io.yaml b/go/pkg/testdata/ocm/policy-results/policysets.policy.open-cluster-management.io.yaml similarity index 100% rename from pkg/testdata/ocm/policy-results/policysets.policy.open-cluster-management.io.yaml rename to go/pkg/testdata/ocm/policy-results/policysets.policy.open-cluster-management.io.yaml diff --git a/pkg/testdata/ocm/profile.json b/go/pkg/testdata/ocm/profile.json similarity index 100% rename from pkg/testdata/ocm/profile.json rename to go/pkg/testdata/ocm/profile.json diff --git a/pkg/testdata/oscal/catalog.json b/go/pkg/testdata/oscal/catalog.json similarity index 100% rename from pkg/testdata/oscal/catalog.json rename to go/pkg/testdata/oscal/catalog.json diff --git a/pkg/testdata/oscal/profile.json b/go/pkg/testdata/oscal/profile.json similarity index 100% rename from pkg/testdata/oscal/profile.json rename to go/pkg/testdata/oscal/profile.json diff --git a/pkg/types/c2pcr/c2pcr_type.go b/go/pkg/types/c2pcr/c2pcr_type.go similarity index 100% rename from pkg/types/c2pcr/c2pcr_type.go rename to go/pkg/types/c2pcr/c2pcr_type.go diff --git a/pkg/types/c2pcr/c2pcrparsed_type.go b/go/pkg/types/c2pcr/c2pcrparsed_type.go similarity index 79% rename from pkg/types/c2pcr/c2pcrparsed_type.go rename to go/pkg/types/c2pcr/c2pcrparsed_type.go index fed5385..885c6d8 100644 --- a/pkg/types/c2pcr/c2pcrparsed_type.go +++ b/go/pkg/types/c2pcr/c2pcrparsed_type.go @@ -17,9 +17,9 @@ limitations under the License. package c2pcr import ( - "github.com/IBM/compliance-to-policy/pkg/oscal" - typesoscal "github.com/IBM/compliance-to-policy/pkg/types/oscal" - typecd "github.com/IBM/compliance-to-policy/pkg/types/oscal/componentdefinition" + "github.com/oscal-compass/compliance-to-policy/go/pkg/oscal" + typesoscal "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal" + typecd "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/componentdefinition" ) type C2PCRParsed struct { diff --git a/pkg/types/configurationpolicy/configurationpolicy_types.go b/go/pkg/types/configurationpolicy/configurationpolicy_types.go similarity index 100% rename from pkg/types/configurationpolicy/configurationpolicy_types.go rename to go/pkg/types/configurationpolicy/configurationpolicy_types.go diff --git a/pkg/types/internalcompliance/compliance_type.go b/go/pkg/types/internalcompliance/compliance_type.go similarity index 100% rename from pkg/types/internalcompliance/compliance_type.go rename to go/pkg/types/internalcompliance/compliance_type.go diff --git a/pkg/types/oscal/assessmentresults/assessmentresult_types.go b/go/pkg/types/oscal/assessmentresults/assessmentresult_types.go similarity index 98% rename from pkg/types/oscal/assessmentresults/assessmentresult_types.go rename to go/pkg/types/oscal/assessmentresults/assessmentresult_types.go index 0496f0a..2572a66 100644 --- a/pkg/types/oscal/assessmentresults/assessmentresult_types.go +++ b/go/pkg/types/oscal/assessmentresults/assessmentresult_types.go @@ -19,7 +19,7 @@ package assessmentresults import ( "time" - "github.com/IBM/compliance-to-policy/pkg/types/oscal/common" + "github.com/oscal-compass/compliance-to-policy/go/pkg/types/oscal/common" ) type Metadata struct { diff --git a/pkg/types/oscal/catalog_types.go b/go/pkg/types/oscal/catalog_types.go similarity index 100% rename from pkg/types/oscal/catalog_types.go rename to go/pkg/types/oscal/catalog_types.go diff --git a/pkg/types/oscal/common/common_types.go b/go/pkg/types/oscal/common/common_types.go similarity index 100% rename from pkg/types/oscal/common/common_types.go rename to go/pkg/types/oscal/common/common_types.go diff --git a/pkg/types/oscal/componentdefinition/component-definition.template.json b/go/pkg/types/oscal/componentdefinition/component-definition.template.json similarity index 100% rename from pkg/types/oscal/componentdefinition/component-definition.template.json rename to go/pkg/types/oscal/componentdefinition/component-definition.template.json diff --git a/pkg/types/oscal/componentdefinition/componentdefinition_types.go b/go/pkg/types/oscal/componentdefinition/componentdefinition_types.go similarity index 100% rename from pkg/types/oscal/componentdefinition/componentdefinition_types.go rename to go/pkg/types/oscal/componentdefinition/componentdefinition_types.go diff --git a/pkg/types/oscal/profile_types.go b/go/pkg/types/oscal/profile_types.go similarity index 100% rename from pkg/types/oscal/profile_types.go rename to go/pkg/types/oscal/profile_types.go diff --git a/pkg/types/placementdecision/helper.go b/go/pkg/types/placementdecision/helper.go similarity index 100% rename from pkg/types/placementdecision/helper.go rename to go/pkg/types/placementdecision/helper.go diff --git a/pkg/types/placementdecision/placementdecision_types.go b/go/pkg/types/placementdecision/placementdecision_types.go similarity index 100% rename from pkg/types/placementdecision/placementdecision_types.go rename to go/pkg/types/placementdecision/placementdecision_types.go diff --git a/pkg/types/placements/placementbinding_types.go b/go/pkg/types/placements/placementbinding_types.go similarity index 100% rename from pkg/types/placements/placementbinding_types.go rename to go/pkg/types/placements/placementbinding_types.go diff --git a/pkg/types/placements/placementrule_types.go b/go/pkg/types/placements/placementrule_types.go similarity index 100% rename from pkg/types/placements/placementrule_types.go rename to go/pkg/types/placements/placementrule_types.go diff --git a/pkg/types/policy/helper.go b/go/pkg/types/policy/helper.go similarity index 100% rename from pkg/types/policy/helper.go rename to go/pkg/types/policy/helper.go diff --git a/pkg/types/policy/policy_types.go b/go/pkg/types/policy/policy_types.go similarity index 100% rename from pkg/types/policy/policy_types.go rename to go/pkg/types/policy/policy_types.go diff --git a/pkg/types/policy/policyset_types.go b/go/pkg/types/policy/policyset_types.go similarity index 100% rename from pkg/types/policy/policyset_types.go rename to go/pkg/types/policy/policyset_types.go diff --git a/pkg/types/policycomposition/policycomposition_type.go b/go/pkg/types/policycomposition/policycomposition_type.go similarity index 100% rename from pkg/types/policycomposition/policycomposition_type.go rename to go/pkg/types/policycomposition/policycomposition_type.go diff --git a/pkg/types/policygenerator/policygenerator_type.go b/go/pkg/types/policygenerator/policygenerator_type.go similarity index 100% rename from pkg/types/policygenerator/policygenerator_type.go rename to go/pkg/types/policygenerator/policygenerator_type.go diff --git a/pkg/types/report/report_type.go b/go/pkg/types/report/report_type.go similarity index 100% rename from pkg/types/report/report_type.go rename to go/pkg/types/report/report_type.go diff --git a/pkg/types/utils/utils.go b/go/pkg/types/utils/utils.go similarity index 100% rename from pkg/types/utils/utils.go rename to go/pkg/types/utils/utils.go diff --git a/pkg/utils.go b/go/pkg/utils.go similarity index 100% rename from pkg/utils.go rename to go/pkg/utils.go diff --git a/scripts/README.md b/go/scripts/README.md similarity index 100% rename from scripts/README.md rename to go/scripts/README.md diff --git a/scripts/cleanup-argocd.sh b/go/scripts/cleanup-argocd.sh similarity index 100% rename from scripts/cleanup-argocd.sh rename to go/scripts/cleanup-argocd.sh diff --git a/scripts/collect/cronjob.yaml b/go/scripts/collect/cronjob.yaml similarity index 100% rename from scripts/collect/cronjob.yaml rename to go/scripts/collect/cronjob.yaml diff --git a/scripts/collect/rbac.yaml b/go/scripts/collect/rbac.yaml similarity index 100% rename from scripts/collect/rbac.yaml rename to go/scripts/collect/rbac.yaml diff --git a/scripts/docker/Dockerfile b/go/scripts/docker/Dockerfile similarity index 100% rename from scripts/docker/Dockerfile rename to go/scripts/docker/Dockerfile diff --git a/scripts/docker/install-kubectl.sh b/go/scripts/docker/install-kubectl.sh similarity index 100% rename from scripts/docker/install-kubectl.sh rename to go/scripts/docker/install-kubectl.sh diff --git a/scripts/gitops/acm-webhook.yaml b/go/scripts/gitops/acm-webhook.yaml similarity index 100% rename from scripts/gitops/acm-webhook.yaml rename to go/scripts/gitops/acm-webhook.yaml diff --git a/scripts/gitops/channel.yaml b/go/scripts/gitops/channel.yaml similarity index 100% rename from scripts/gitops/channel.yaml rename to go/scripts/gitops/channel.yaml diff --git a/scripts/gitops/subscription-admin.yaml b/go/scripts/gitops/subscription-admin.yaml similarity index 100% rename from scripts/gitops/subscription-admin.yaml rename to go/scripts/gitops/subscription-admin.yaml diff --git a/scripts/gitops/subscription.yaml b/go/scripts/gitops/subscription.yaml similarity index 100% rename from scripts/gitops/subscription.yaml rename to go/scripts/gitops/subscription.yaml diff --git a/scripts/init.sh b/go/scripts/init.sh similarity index 100% rename from scripts/init.sh rename to go/scripts/init.sh diff --git a/scripts/install-argocd.sh b/go/scripts/install-argocd.sh similarity index 100% rename from scripts/install-argocd.sh rename to go/scripts/install-argocd.sh diff --git a/scripts/kyverno/README.md b/go/scripts/kyverno/README.md similarity index 100% rename from scripts/kyverno/README.md rename to go/scripts/kyverno/README.md diff --git a/scripts/kyverno/collect/cronjob.yaml b/go/scripts/kyverno/collect/cronjob.yaml similarity index 100% rename from scripts/kyverno/collect/cronjob.yaml rename to go/scripts/kyverno/collect/cronjob.yaml diff --git a/scripts/kyverno/collect/rbac.yaml b/go/scripts/kyverno/collect/rbac.yaml similarity index 100% rename from scripts/kyverno/collect/rbac.yaml rename to go/scripts/kyverno/collect/rbac.yaml diff --git a/scripts/pod.yaml b/go/scripts/pod.yaml similarity index 100% rename from scripts/pod.yaml rename to go/scripts/pod.yaml diff --git a/scripts/setup-argocd.sh b/go/scripts/setup-argocd.sh similarity index 100% rename from scripts/setup-argocd.sh rename to go/scripts/setup-argocd.sh diff --git a/scripts/uninstall-argocd.sh b/go/scripts/uninstall-argocd.sh similarity index 100% rename from scripts/uninstall-argocd.sh rename to go/scripts/uninstall-argocd.sh diff --git a/plugins_public/plugins/__init__.py b/plugins_public/plugins/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/plugins_public/plugins/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/plugins_public/plugins/kyverno.py b/plugins_public/plugins/kyverno.py new file mode 100644 index 0000000..ba12598 --- /dev/null +++ b/plugins_public/plugins/kyverno.py @@ -0,0 +1,153 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import pathlib +import shutil +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional + +import yaml +from jinja2 import Template +from pydantic import Field + +from c2p.common.err import C2PError +from c2p.common.logging import getLogger +from c2p.common.utils import get_datetime, get_dict_safely +from c2p.framework.models import Policy, PVPResult, RawResult +from c2p.framework.models.pvp_result import ( + ObservationByCheck, + PVPResult, + ResultEnum, + Subject, +) +from c2p.framework.plugin_spec import PluginConfig, PluginSpec + +logger = getLogger(__name__) + +status_dictionary = { + 'pass': ResultEnum.Pass, + 'fail': ResultEnum.Failure, + 'warn': ResultEnum.Failure, + 'skip': ResultEnum.Error, + 'error': ResultEnum.Error, +} + + +class PluginConfigKyverno(PluginConfig): + policy_template_dir: str = Field(..., title='Path to Policy template directory') + deliverable_policy_dir: str = Field(..., title='Path to deliverable (generated) policy directory') + + +class PluginKyverno(PluginSpec): + + def __init__(self, config: Optional[PluginConfigKyverno] = None) -> None: + super().__init__() + self.config = config + + 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()) + + results_per_policy = filter(lambda x: x['policy'] == policy_name, results) + subjects = [] + for rpp in results_per_policy: + result = rpp['result'] + result = status_dictionary[result] if result in status_dictionary else ResultEnum.Error + timestamp = get_dict_safely(rpp, ['timestamp', 'seconds'], get_datetime().second) + evaluated_on = datetime.fromtimestamp(timestamp, tz=timezone.utc) + message = rpp['message'] + + def to_subject(resource): + kind = get_dict_safely(resource, 'kind') + api_version = get_dict_safely(resource, 'apiVersion', '') + name = get_dict_safely(resource, 'name') + namespace = get_dict_safely(resource, 'namespace', '(ClusterScope)') + uid = get_dict_safely(resource, 'uid') + return Subject( + title=f'{api_version}/{kind} {name} {namespace}', + type='resource', + result=result, + resource_id=uid, + evaluated_on=evaluated_on, + reason=message, + ) + + subjects = subjects + list(map(to_subject, get_dict_safely(rpp, 'resources'))) + + observation.subjects = subjects + observations.append(observation) + + pvp_result.observations_by_check = observations + return pvp_result + + def generate_pvp_policy(self, policy: Policy): + rule_sets = policy.rule_sets + parameters = policy.parameters + policy_template_dir = self.config.policy_template_dir + deliverable_policy_dir = self.config.deliverable_policy_dir + if not pathlib.Path(deliverable_policy_dir).exists(): + logger.info(f"The deliverable policy directory '{deliverable_policy_dir}' is not found. Creating...") + pathlib.Path(deliverable_policy_dir).mkdir(parents=True) + else: + if not pathlib.Path(deliverable_policy_dir).is_dir(): + raise C2PError(f"The deliverable policy directory '{deliverable_policy_dir}' is not directory.") + for rule_set in rule_sets: + each_policy_template_dir = pathlib.Path(f'{policy_template_dir}/{rule_set.rule_id}') + each_deliverable_policy_dir = pathlib.Path(f'{deliverable_policy_dir}/{rule_set.rule_id}') + shutil.copytree(each_policy_template_dir, each_deliverable_policy_dir, dirs_exist_ok=True) + contents = each_deliverable_policy_dir.glob('**/*') + for path in list(contents): + tp_str = path.open('r').read() + yamldocs = yaml.safe_load_all(path.open('r')) + if not self.__is_policy_file(yamldocs): + tp = Template(source=tp_str) + kv = dict(map(lambda x: (x.id, x.value), parameters)) + rendered = tp.render(kv) + path.write_text(rendered) + + def __is_policy_file(self, yamldocs: List[Dict[str, Any]]) -> bool: + for yamldoc in yamldocs: + kind = get_dict_safely(yamldoc, 'kind', None) + api_version = get_dict_safely(yamldoc, 'apiVersion', None) + if kind in ['ClusterPolicy', 'Policy'] and api_version == 'kyverno.io/v1': + return True + return False diff --git a/plugins_public/plugins/ocm.py b/plugins_public/plugins/ocm.py new file mode 100644 index 0000000..7c1c068 --- /dev/null +++ b/plugins_public/plugins/ocm.py @@ -0,0 +1,294 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import json +import pathlib +import shutil +from datetime import datetime +from typing import Any, Dict, List, Optional, TypeVar + +import yaml +from pydantic import BaseModel, Field + +from c2p.common.err import C2PError +from c2p.common.logging import getLogger +from c2p.common.utils import get_datetime, get_dict_safely, remove_none +from c2p.framework.models import Policy, PVPResult, RawResult +from c2p.framework.models.pvp_result import ( + ObservationByCheck, + PVPResult, + ResultEnum, + Subject, +) +from c2p.framework.plugin_spec import PluginConfig, PluginSpec + +logger = getLogger(__name__) + +status_dictionary = { + 'Compliant': ResultEnum.Pass, + 'NonCompliant': ResultEnum.Failure, +} + +ANNOTATION_COMPONENT_TITLE = "compliance-to-policy.component-title" + + +class Manifest(BaseModel): + remediationAction: Optional[str] = None + severity: Optional[str] = None + complianceType: Optional[str] = None + metadataComplianceType: Optional[str] = None + evaluationInterval: Optional[Dict[str, Any]] = None + namespaceSelector: Optional[Dict[str, Any]] = None + pruneObjectBehavior: Optional[str] = None + patches: Optional[Dict[str, Any]] = None + path: Optional[str] = None + extraDependencies: Optional[List[Dict[str, str]]] = None + ignorePending: Optional[bool] = False + + +class PolicyConfig(BaseModel): + name: str + manifests: Optional[List[Manifest]] = [] + standards: Optional[List[str]] = [] + controls: Optional[List[str]] = [] + categories: Optional[List[str]] = [] + consolidateManifests: Optional[bool] = True + orderManifests: Optional[bool] = False + informGatekeeperPolicies: Optional[bool] = False + informKyvernoPolicies: Optional[bool] = False + remediationAction: Optional[str] = 'inform' + severity: Optional[str] = 'high' + complianceType: Optional[str] = 'mustnothave' + + +class PluginConfigOCM(PluginConfig): + policy_template_dir: str = Field(..., title='Path to Policy template directory') + deliverable_policy_dir: str = Field(..., title='Path to deliverable (generated) policy directory') + namespace: str = Field(..., title='Namespace in OCM Hub to which policies are delivered') + paremeters_configmap_name: str = Field('c2p-parameters', title='Name of configmap for parameters') + cluster_selectors: Dict[str, str] = Field( + ..., title='Pair of cluster label name and value to which policies are distributed to matched clusters' + ) + policy_set_name: str = 'test' + exclude_namespaces: List[str] = Field( + [ + 'kube-system', + 'open-cluster-management', + 'open-cluster-management-agent', + 'open-cluster-management-agent-addon', + ], + title='Namespaces that policy is not applied', + ) + include_namespaces: List[str] = Field(['*'], title='Namespaces that policy must be applied') + + +class PluginOCM(PluginSpec): + + def __init__(self, config: Optional[PluginConfigOCM] = None) -> None: + super().__init__() + self.config = config + + def generate_pvp_result(self, raw_result: RawResult) -> PVPResult: + pvp_result: PVPResult = PVPResult() + observations: List[ObservationByCheck] = [] + + policies = list( + filter( + lambda x: x['apiVersion'] == 'policy.open-cluster-management.io/v1' and x['kind'] == 'Policy', + raw_result.data, + ) + ) + + # Root policy resource on Hub + root_policies = list( + filter( + lambda x: get_dict_safely(x, ['metadata', 'labels', 'policy.open-cluster-management.io/cluster-name']) + == None, + policies, + ) + ) + + # Policy resources of each cluster to which the root policies are delivered + each_policies = list( + filter( + lambda x: get_dict_safely(x, ['metadata', 'labels', 'policy.open-cluster-management.io/cluster-name']) + != None, + policies, + ) + ) + + # policy_name is used as check_id + policy_namespace_names = list(map(lambda x: (x['metadata']['name'], x['metadata']['namespace']), root_policies)) + + for policy_name, root_namespace in policy_namespace_names: + observation = ObservationByCheck(check_id=policy_name, methods=['AUTOMATED'], collected=get_datetime()) + + results_per_policy = filter( + lambda x: x['metadata']['name'] == f'{root_namespace}.{policy_name}', each_policies + ) + subjects = [] + for rpp in results_per_policy: + name = get_dict_safely(rpp, ['metadata', 'name']) + cluster_name = get_dict_safely(rpp, ['metadata', 'namespace']) + result = get_dict_safely(rpp, ['status', 'compliant']) + result = status_dictionary[result] if result in status_dictionary else ResultEnum.Error + details = get_dict_safely(rpp, ['status', 'details']) + if isinstance(details, list) and len(details) > 0: + for detail in details: + history = detail['history'] + if isinstance(history, list) and len(history) > 0: + latest_history = history[0] + event_name = latest_history['eventName'] + last_timestamp = latest_history['lastTimestamp'] + message = latest_history['message'] + else: + logger.warn(f'"details" are not found for name "{name}" for "{cluster_name}"') + + evaluated_on = ( + datetime.fromisoformat(last_timestamp.replace('Z', '+00:00')) + if last_timestamp != None + else get_datetime() + ) + + event_name = event_name if event_name != None else '' + message = message if message != None else '' + reason = f'[{event_name}] {message}' if event_name != '' and message != '' else None + subject = Subject( + title=f'Cluster "{cluster_name}"', + type='cluster', + result=result, + resource_id=cluster_name, + evaluated_on=evaluated_on, + reason=reason, + ) + subjects.append(subject) + + observation.subjects = subjects + observations.append(observation) + + pvp_result.observations_by_check = observations + return pvp_result + + def generate_pvp_policy(self, policy: Policy): + rule_sets = policy.rule_sets + parameters = policy.parameters + policy_template_dir = pathlib.Path(self.config.policy_template_dir) + deliverable_policy_dir = pathlib.Path(self.config.deliverable_policy_dir) + if not deliverable_policy_dir.exists(): + logger.info( + f"The deliverable policy directory '{deliverable_policy_dir.as_posix()}' is not found. Creating..." + ) + deliverable_policy_dir.mkdir(parents=True) + else: + if not deliverable_policy_dir.is_dir(): + raise C2PError( + f"The deliverable policy directory '{deliverable_policy_dir.as_posix()}' is not directory." + ) + policy_config_map: Dict[str, PolicyConfig] = {} + for rule_set in rule_sets: + policy_id = rule_set.rule_id + each_policy_template_dir = policy_template_dir / policy_id + each_deliverable_policy_dir = deliverable_policy_dir / policy_id + shutil.copytree(each_policy_template_dir, each_deliverable_policy_dir, dirs_exist_ok=True) + standards = [] + controls = [] + categories = [] + policy_generator_path = each_deliverable_policy_dir / 'policy-generator.yaml' + policy_generator = yaml.safe_load(policy_generator_path.open('r')) + policy_generator['policyDefaults']['namespace'] = self.config.namespace + policy_generator['policyDefaults']['standards'] = standards + policy_generator['policyDefaults']['controls'] = controls + policy_generator['policyDefaults']['categories'] = categories + policy_generator['policyDefaults']['placement'] = {'clusterSelectors': self.config.cluster_selectors} + yaml.safe_dump(policy_generator, policy_generator_path.open('w')) + + pg_policy = policy_generator['policies'][0] + if policy_id in policy_config_map: + policy_config = policy_config_map[policy_id] + else: + policy_config = PolicyConfig.parse_obj(pg_policy) + for idx, m in enumerate(policy_config.manifests): + policy_config.manifests[idx].path = m.path.replace('./', f'./{policy_id}/') + policy_config.standards = self.__merge_uniquely(policy_config.standards, standards) + policy_config.categories = self.__merge_uniquely(policy_config.controls, categories) + policy_config.controls = self.__merge_uniquely(policy_config.categories, controls) + policy_config_map[policy_id] = policy_config + + policy_set_name_sanitized = self.config.policy_set_name.lower().replace(' ', '-') # DNS Compliant value + policy_set = { + 'name': policy_set_name_sanitized, + 'policies': list(policy_config_map.keys()), + } + + policy_set_generator = { + 'apiVersion': 'policy.open-cluster-management.io/v1', + 'kind': 'PolicyGenerator', + 'metadata': {'name': 'policy-set'}, + 'placementBindingDefaults': {'name': 'policy-set'}, + 'policyDefaults': { + 'placement': {'labelSelector': self.config.cluster_selectors}, + 'consolidateManifests': False, + 'orderManifests': False, + 'informGatekeeperPolicies': False, + 'informKyvernoPolicies': False, + 'namespaceSelector': { + 'exclude': self.config.exclude_namespaces, + 'include': self.config.include_namespaces, + }, + 'namespace': self.config.namespace, + }, + 'policySetDefaults': {'placement': {'labelSelector': self.config.cluster_selectors}}, + 'policies': list(map(lambda x: x.dict(), policy_config_map.values())), + 'policySets': [policy_set], + } + + parameters_configmap = { + 'apiVersion': 'v1', + 'kind': 'ConfigMap', + 'metadata': {'name': self.config.paremeters_configmap_name, 'namespace': self.config.namespace}, + 'data': dict(map(lambda x: (x.id, x.value), parameters)), + } + + kustomize_patch = { + 'target': {'kind': 'PolicySet', 'name': policy_set_name_sanitized}, + 'patch': json.dumps( + [ + { + 'op': 'replace', + 'path': f'/metadata/annotations/{ANNOTATION_COMPONENT_TITLE}', + 'value': self.config.policy_set_name, + } + ] + ), + } + + kustomize = { + 'generators': ['./policy-generator.yaml'], + 'patches': [kustomize_patch], + 'resources': ['./parameters.yaml'], + } + + yaml.safe_dump(remove_none(policy_set_generator), (deliverable_policy_dir / 'policy-generator.yaml').open('w')) + yaml.safe_dump(parameters_configmap, (deliverable_policy_dir / 'parameters.yaml').open('w')) + yaml.safe_dump(kustomize, (deliverable_policy_dir / 'kustomization.yaml').open('w')) + + T = TypeVar('T') + + def __merge_uniquely(self, targets: Optional[List[T]], value: List[T]) -> List[T]: + x = set(targets) if targets != None else set() + for _ in value: + x.add(value) + return list(set(x)) diff --git a/plugins_public/tests/__init__.py b/plugins_public/tests/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/plugins_public/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/plugins_public/tests/data/kyverno/clusterpolicyreports.wgpolicyk8s.io.yaml b/plugins_public/tests/data/kyverno/clusterpolicyreports.wgpolicyk8s.io.yaml new file mode 100644 index 0000000..ded9522 --- /dev/null +++ b/plugins_public/tests/data/kyverno/clusterpolicyreports.wgpolicyk8s.io.yaml @@ -0,0 +1,5 @@ +apiVersion: v1 +items: [] +kind: List +metadata: + resourceVersion: "" diff --git a/plugins_public/tests/data/kyverno/component-definition.csv b/plugins_public/tests/data/kyverno/component-definition.csv new file mode 100644 index 0000000..ea37134 --- /dev/null +++ b/plugins_public/tests/data/kyverno/component-definition.csv @@ -0,0 +1,6 @@ +$$Component_Title,$$Component_Description,$$Component_Type,$$Control_Id_List,$$Rule_Id,$$Rule_Description,$Parameter_Id,$Parameter_Description,$Parameter_Value_Alternatives,$Parameter_Value_Default,$$Profile_Source,$$Profile_Description,Rule_Actual_State_Data_Request_Evidence_Format_Reference_URL_list,Rule_Actual_State_TimeToLive,$Check_Id,$Check_Description,Fetcher_id,Fetcher_Description,Fix_id,Fix_Description,Rule_implementation_status,Rule_POAM_Reference_URL,$$Namespace +A human readable name for the component.,A description of the component including information about its function.,A category describing the purpose of the component. ALLOWED VALUES interconnection:software:hardware:service:physical:process-procedure:plan:guidance:standard:validation:,A list of textual labels that uniquely identify the controls or statements that the component implements.,A textual label that uniquely identifies a policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the policy (desired state) including information about its purpose and scope.,A textual label that uniquely identifies the parameter associated with that policy (desired state) or controls implemented by the policy (desired state).,A description of the parameter including the purpose and use of the parameter.,ONLY for the policy (desired state) parameters: A value or set of values the parameter can take. The catalog parameters values are defined in the catalog. ,"A value recommended by Compliance Team in this profile for the parameter of the control or policy (desired state). If a CIS-benchmark exists, the default default could be the CIS-benchmark recommanded value.",A URL reference to the source catalog or profile for which this component is implementing controls for. A profile designates a selection and configuration of controls from one or more catalogs,A description of the profile.,A list of URL references that contain the Actual State Data Model (eg schema or swager API or procedure template or terraform schema). Needed by the fetcher developer. ,A TimeToLive value of the duration of time the actual state is valid before it becomes stale or obsolite or overriden. Needed by the fetcher developer. ,A textual label that uniquely identifies a check of the policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the check of the policy (desired state) including the method (interview or examine or test) and procedure details.,A textual label that uniquely identifies a collector of the actual state (evidence) associated with the policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the collector of the actual state (evidence) associated with the policy (desired state) including the method (interview or examine or API) and questionaire or API details.,A textual label that uniquely identifies the fix of the failed policy.,A description of the fix to remediate the failed policy.,Indicates the degree to which the a given policy is implemented. ALLOWED VALUES: IMPLEMENTED: The control is fully implemented. PARTIAL: The control is partially implemented. PLANNED: There is a plan for implementing the control as explained in the remarks. ALTERNATIVE: There is an alternative implementation for this control as explained in the remarks. NOT-APPLICABLE: This control does not apply to this system as justified in the remarks.,A URL reference to the Plan of Action and Milestones this component may be subjected to for remediation or deviation or mitigation in case of the policy (desired state) non compliance or error or failure. ,"A namespace qualifying the property's name. This allows different organizations to associate distinct semantics with the same name. Used in conjunction with ""class"" as the ontology concept. " +Managed Kubernetes,Managed Kubernetes cluster,Service,cm-2,allowed-base-images,"Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.",allowed_baseimages,Allowed baseimages,gcr.io/distroless/static:root,gcr.io/distroless/static:root,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,allowed-base-images,"Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.",,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +Managed Kubernetes,Managed Kubernetes cluster,Service,cm-2.1,disallow-capabilities,"Images coming from certain registries require authentication in order to pull them, and the kubelet uses this information in the form of an imagePullSecret to pull those images on behalf of your Pod. This policy searches for images coming from a registry called `corp.reg.com` and, if found, will mutate the Pod to add an IimagePullSecret called `my-secret`.",,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,disallow-capabilities,Adding capabilities beyond those listed in the policy must be disallowed.,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +Kyverno,Kyverno as Policy Validation Point,Validation,na,allowed-base-images,"Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.",,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,allowed-base-images,"Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.",,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +Kyverno,Kyverno as Policy Validation Point,Validation,na,disallow-capabilities,"Images coming from certain registries require authentication in order to pull them, and the kubelet uses this information in the form of an imagePullSecret to pull those images on behalf of your Pod. This policy searches for images coming from a registry called `corp.reg.com` and, if found, will mutate the Pod to add an IimagePullSecret called `my-secret`.",,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,disallow-capabilities,Adding capabilities beyond those listed in the policy must be disallowed.,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/component-definition.json b/plugins_public/tests/data/kyverno/component-definition.json new file mode 100644 index 0000000..5aa060f --- /dev/null +++ b/plugins_public/tests/data/kyverno/component-definition.json @@ -0,0 +1,210 @@ +{ + "component-definition": { + "uuid": "a41933c9-2710-4492-9010-aadc1c602157", + "metadata": { + "title": "Component Definition for Kube", + "last-modified": "2024-04-14T07:18:19+00:00", + "version": "1.0", + "oscal-version": "1.0.4" + }, + "components": [ + { + "uuid": "b4087407-521b-4763-aebc-3a0099870d37", + "type": "Service", + "title": "Managed Kubernetes", + "description": "Managed Kubernetes cluster", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images", + "remarks": "rule_set_0" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed_baseimages", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Allowed baseimages", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Value_Alternatives", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "gcr.io/distroless/static:root", + "remarks": "rule_set_0" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images", + "remarks": "rule_set_0" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.", + "remarks": "rule_set_0" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities", + "remarks": "rule_set_1" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Images coming from certain registries require authentication in order to pull them, and the kubelet uses this information in the form of an imagePullSecret to pull those images on behalf of your Pod. This policy searches for images coming from a registry called `corp.reg.com` and, if found, will mutate the Pod to add an IimagePullSecret called `my-secret`.", + "remarks": "rule_set_1" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities", + "remarks": "rule_set_1" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Adding capabilities beyond those listed in the policy must be disallowed.", + "remarks": "rule_set_1" + } + ], + "control-implementations": [ + { + "uuid": "79fad5e8-f13f-413a-b3c2-b5ffed1d82ad", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "set-parameters": [ + { + "param-id": "allowed_baseimages", + "values": [ + "gcr.io/distroless/static:root" + ] + } + ], + "implemented-requirements": [ + { + "uuid": "552c000b-a4ee-4ba8-87d6-212cf95d120d", + "control-id": "cm-2", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images" + } + ] + }, + { + "uuid": "5512dbcb-cecf-42ae-9441-a1b000da8a27", + "control-id": "cm-2.1", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities" + } + ] + } + ] + } + ] + }, + { + "uuid": "79ddf370-dc3e-4a68-9d85-e1b1b83792fc", + "type": "Validation", + "title": "Kyverno", + "description": "Kyverno as Policy Validation Point", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images", + "remarks": "rule_set_2" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.", + "remarks": "rule_set_2" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images", + "remarks": "rule_set_2" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Building images which specify a base as their origin is a good start to improving supply chain security, but over time organizations may want to build an allow list of specific base images which are allowed to be used when constructing containers. This policy ensures that a container's base, found in an OCI annotation, is in a cluster-wide allow list.", + "remarks": "rule_set_2" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities", + "remarks": "rule_set_3" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Images coming from certain registries require authentication in order to pull them, and the kubelet uses this information in the form of an imagePullSecret to pull those images on behalf of your Pod. This policy searches for images coming from a registry called `corp.reg.com` and, if found, will mutate the Pod to add an IimagePullSecret called `my-secret`.", + "remarks": "rule_set_3" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities", + "remarks": "rule_set_3" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Adding capabilities beyond those listed in the policy must be disallowed.", + "remarks": "rule_set_3" + } + ], + "control-implementations": [ + { + "uuid": "6c215829-fe51-4ee9-a303-1d61301c24e2", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "implemented-requirements": [ + { + "uuid": "f06dbc3b-f486-40c1-8e25-6041a8697bd5", + "control-id": "na", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "allowed-base-images" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "disallow-capabilities" + } + ] + } + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/02-setup-cm.yaml b/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/02-setup-cm.yaml new file mode 100644 index 0000000..e1df625 --- /dev/null +++ b/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/02-setup-cm.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: platform +--- +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: platform + name: baseimages +data: + allowedbaseimages: 'gcr.io/distroless/static:root' \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/allowed-base-images.yaml b/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/allowed-base-images.yaml new file mode 100644 index 0000000..94bd200 --- /dev/null +++ b/plugins_public/tests/data/kyverno/deliverable-policy/allowed-base-images/allowed-base-images.yaml @@ -0,0 +1,58 @@ +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: allowed-base-images + annotations: + policies.kyverno.io/title: Allowed Base Images + policies.kyverno.io/category: Other + policies.kyverno.io/severity: medium + kyverno.io/kyverno-version: 1.7.0 + policies.kyverno.io/minversion: 1.7.0 + kyverno.io/kubernetes-version: "1.23" + policies.kyverno.io/subject: Pod + policies.kyverno.io/description: >- + Building images which specify a base as their origin is a good start + to improving supply chain security, but over time organizations + may want to build an allow list of specific base images which + are allowed to be used when constructing containers. This policy ensures + that a container's base, found in an OCI annotation, is in a cluster-wide + allow list. +spec: + validationFailureAction: audit + rules: + - name: allowed-base-images + match: + any: + - resources: + kinds: + - Pod + preconditions: + all: + - key: "{{request.operation || 'BACKGROUND'}}" + operator: NotEquals + value: DELETE + context: + - name: baseimages + configMap: + name: baseimages + namespace: platform + validate: + message: >- + This container image's base is not in the approved list or is not specified. Only pre-approved + base images may be used. Please contact the platform team for assistance. + foreach: + - list: "request.object.spec.containers" + context: + - name: imageData + imageRegistry: + reference: "{{ element.image }}" + - name: basename + variable: + jmesPath: imageData.manifest.annotations."org.opencontainers.image.base.name" + default: '' + deny: + conditions: + all: + - key: "{{ basename }}" + operator: AnyNotIn + value: "{{ baseimages.data.allowedbaseimages }}" diff --git a/plugins_public/tests/data/kyverno/deliverable-policy/disallow-capabilities/disallow-capabilities.yaml b/plugins_public/tests/data/kyverno/deliverable-policy/disallow-capabilities/disallow-capabilities.yaml new file mode 100644 index 0000000..857a4db --- /dev/null +++ b/plugins_public/tests/data/kyverno/deliverable-policy/disallow-capabilities/disallow-capabilities.yaml @@ -0,0 +1,53 @@ +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: disallow-capabilities + annotations: + policies.kyverno.io/title: Disallow Capabilities + policies.kyverno.io/category: Pod Security Standards (Baseline) + policies.kyverno.io/severity: medium + kyverno.io/kyverno-version: 1.6.0 + policies.kyverno.io/minversion: 1.6.0 + kyverno.io/kubernetes-version: "1.22-1.23" + policies.kyverno.io/subject: Pod + policies.kyverno.io/description: >- + Adding capabilities beyond those listed in the policy must be disallowed. +spec: + validationFailureAction: audit + background: true + rules: + - name: adding-capabilities + match: + any: + - resources: + kinds: + - Pod + preconditions: + all: + - key: "{{ request.operation || 'BACKGROUND' }}" + operator: NotEquals + value: DELETE + validate: + message: >- + Any capabilities added beyond the allowed list (AUDIT_WRITE, CHOWN, DAC_OVERRIDE, FOWNER, + FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, SETPCAP, SETUID, SYS_CHROOT) + are disallowed. + deny: + conditions: + all: + - key: "{{ request.object.spec.[ephemeralContainers, initContainers, containers][].securityContext.capabilities.add[] }}" + operator: AnyNotIn + value: + - AUDIT_WRITE + - CHOWN + - DAC_OVERRIDE + - FOWNER + - FSETID + - KILL + - MKNOD + - NET_BIND_SERVICE + - SETFCAP + - SETGID + - SETPCAP + - SETUID + - SYS_CHROOT \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/policy-resources/add-imagepullsecrets/add-imagepullsecrets.yaml b/plugins_public/tests/data/kyverno/policy-resources/add-imagepullsecrets/add-imagepullsecrets.yaml new file mode 100644 index 0000000..97da96e --- /dev/null +++ b/plugins_public/tests/data/kyverno/policy-resources/add-imagepullsecrets/add-imagepullsecrets.yaml @@ -0,0 +1,30 @@ +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: add-imagepullsecrets + annotations: + policies.kyverno.io/title: Add imagePullSecrets + policies.kyverno.io/category: Sample + policies.kyverno.io/subject: Pod + policies.kyverno.io/minversion: 1.6.0 + policies.kyverno.io/description: >- + Images coming from certain registries require authentication in order to pull them, + and the kubelet uses this information in the form of an imagePullSecret to pull + those images on behalf of your Pod. This policy searches for images coming from a + registry called `corp.reg.com` and, if found, will mutate the Pod to add an + imagePullSecret called `my-secret`. +spec: + rules: + - name: add-imagepullsecret + match: + any: + - resources: + kinds: + - Pod + mutate: + patchStrategicMerge: + spec: + containers: + - <(image): "corp.reg.com/*" + imagePullSecrets: + - name: my-secret \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml b/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml new file mode 100644 index 0000000..2cfaf1e --- /dev/null +++ b/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/02-setup-cm.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: platform +--- +apiVersion: v1 +kind: ConfigMap +metadata: + namespace: platform + name: baseimages +data: + allowedbaseimages: '{{ allowed_baseimages|default("path/to/base/image:tag", true) }}' \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml b/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml new file mode 100644 index 0000000..94bd200 --- /dev/null +++ b/plugins_public/tests/data/kyverno/policy-resources/allowed-base-images/allowed-base-images.yaml @@ -0,0 +1,58 @@ +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: allowed-base-images + annotations: + policies.kyverno.io/title: Allowed Base Images + policies.kyverno.io/category: Other + policies.kyverno.io/severity: medium + kyverno.io/kyverno-version: 1.7.0 + policies.kyverno.io/minversion: 1.7.0 + kyverno.io/kubernetes-version: "1.23" + policies.kyverno.io/subject: Pod + policies.kyverno.io/description: >- + Building images which specify a base as their origin is a good start + to improving supply chain security, but over time organizations + may want to build an allow list of specific base images which + are allowed to be used when constructing containers. This policy ensures + that a container's base, found in an OCI annotation, is in a cluster-wide + allow list. +spec: + validationFailureAction: audit + rules: + - name: allowed-base-images + match: + any: + - resources: + kinds: + - Pod + preconditions: + all: + - key: "{{request.operation || 'BACKGROUND'}}" + operator: NotEquals + value: DELETE + context: + - name: baseimages + configMap: + name: baseimages + namespace: platform + validate: + message: >- + This container image's base is not in the approved list or is not specified. Only pre-approved + base images may be used. Please contact the platform team for assistance. + foreach: + - list: "request.object.spec.containers" + context: + - name: imageData + imageRegistry: + reference: "{{ element.image }}" + - name: basename + variable: + jmesPath: imageData.manifest.annotations."org.opencontainers.image.base.name" + default: '' + deny: + conditions: + all: + - key: "{{ basename }}" + operator: AnyNotIn + value: "{{ baseimages.data.allowedbaseimages }}" diff --git a/plugins_public/tests/data/kyverno/policy-resources/disallow-capabilities/disallow-capabilities.yaml b/plugins_public/tests/data/kyverno/policy-resources/disallow-capabilities/disallow-capabilities.yaml new file mode 100644 index 0000000..857a4db --- /dev/null +++ b/plugins_public/tests/data/kyverno/policy-resources/disallow-capabilities/disallow-capabilities.yaml @@ -0,0 +1,53 @@ +apiVersion: kyverno.io/v1 +kind: ClusterPolicy +metadata: + name: disallow-capabilities + annotations: + policies.kyverno.io/title: Disallow Capabilities + policies.kyverno.io/category: Pod Security Standards (Baseline) + policies.kyverno.io/severity: medium + kyverno.io/kyverno-version: 1.6.0 + policies.kyverno.io/minversion: 1.6.0 + kyverno.io/kubernetes-version: "1.22-1.23" + policies.kyverno.io/subject: Pod + policies.kyverno.io/description: >- + Adding capabilities beyond those listed in the policy must be disallowed. +spec: + validationFailureAction: audit + background: true + rules: + - name: adding-capabilities + match: + any: + - resources: + kinds: + - Pod + preconditions: + all: + - key: "{{ request.operation || 'BACKGROUND' }}" + operator: NotEquals + value: DELETE + validate: + message: >- + Any capabilities added beyond the allowed list (AUDIT_WRITE, CHOWN, DAC_OVERRIDE, FOWNER, + FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, SETPCAP, SETUID, SYS_CHROOT) + are disallowed. + deny: + conditions: + all: + - key: "{{ request.object.spec.[ephemeralContainers, initContainers, containers][].securityContext.capabilities.add[] }}" + operator: AnyNotIn + value: + - AUDIT_WRITE + - CHOWN + - DAC_OVERRIDE + - FOWNER + - FSETID + - KILL + - MKNOD + - NET_BIND_SERVICE + - SETFCAP + - SETGID + - SETPCAP + - SETUID + - SYS_CHROOT \ No newline at end of file diff --git a/plugins_public/tests/data/kyverno/policyreports.wgpolicyk8s.io.yaml b/plugins_public/tests/data/kyverno/policyreports.wgpolicyk8s.io.yaml new file mode 100644 index 0000000..310a8f0 --- /dev/null +++ b/plugins_public/tests/data/kyverno/policyreports.wgpolicyk8s.io.yaml @@ -0,0 +1,1311 @@ +apiVersion: v1 +items: +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:19Z" + generation: 1 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/allowed-base-images: "22432" + name: cpol-allowed-base-images + namespace: kube-system + resourceVersion: "22649" + uid: 5d36af80-eaf8-432e-b7dd-c9c993e13c10 + results: + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kube-scheduler-kind-control-plane + namespace: kube-system + uid: 5c5d8e06-724c-439f-a9be-3ae34b0c6083 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: coredns-5d78c9869d-gc25q + namespace: kube-system + uid: 621caa1d-897d-4366-8906-841ba56c1fdd + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kindnet-pbb9l + namespace: kube-system + uid: 74db5c25-74ca-457d-96e3-0d7d0dc39b19 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: etcd-kind-control-plane + namespace: kube-system + uid: 8f2aebd7-7957-4037-8509-34596db786ac + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079156 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kube-apiserver-kind-control-plane + namespace: kube-system + uid: a0703256-75e4-4bba-83c8-c8df32866156 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kube-proxy-zbddb + namespace: kube-system + uid: aee2dfc5-9c05-4b6f-b7a7-6d87bdbd2eab + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: coredns-5d78c9869d-2rbnq + namespace: kube-system + uid: d053eefe-8d34-4ffa-9550-8d68e6f37e08 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kube-controller-manager-kind-control-plane + namespace: kube-system + uid: d420e878-2ba7-45e3-afb4-af859d0891af + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079158 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: DaemonSet + name: kindnet + namespace: kube-system + uid: 73917941-f4d3-444f-8d0f-be93ba1e4e2b + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: DaemonSet + name: kube-proxy + namespace: kube-system + uid: 78cf0d9f-c3b2-488d-b596-0e4729025aee + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: coredns-5d78c9869d + namespace: kube-system + uid: 919c840d-63cf-4293-8a64-0fd0de15121f + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079129 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: coredns + namespace: kube-system + uid: d7418bd6-4c02-4344-864b-d710ee03b7e2 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + summary: + error: 0 + fail: 12 + pass: 0 + skip: 0 + warn: 0 +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:19Z" + generation: 2 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/disallow-capabilities: "22434" + name: cpol-disallow-capabilities + namespace: kube-system + resourceVersion: "22763" + uid: 570a67ea-3fde-496c-afd7-5e9dfa417601 + results: + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kube-scheduler-kind-control-plane + namespace: kube-system + uid: 5c5d8e06-724c-439f-a9be-3ae34b0c6083 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: coredns-5d78c9869d-gc25q + namespace: kube-system + uid: 621caa1d-897d-4366-8906-841ba56c1fdd + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Pod Security Standards (Baseline) + message: Any capabilities added beyond the allowed list (AUDIT_WRITE, CHOWN, DAC_OVERRIDE, + FOWNER, FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, SETPCAP, SETUID, + SYS_CHROOT) are disallowed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kindnet-pbb9l + namespace: kube-system + uid: 74db5c25-74ca-457d-96e3-0d7d0dc39b19 + result: fail + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: etcd-kind-control-plane + namespace: kube-system + uid: 8f2aebd7-7957-4037-8509-34596db786ac + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079156 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kube-apiserver-kind-control-plane + namespace: kube-system + uid: a0703256-75e4-4bba-83c8-c8df32866156 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kube-proxy-zbddb + namespace: kube-system + uid: aee2dfc5-9c05-4b6f-b7a7-6d87bdbd2eab + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: coredns-5d78c9869d-2rbnq + namespace: kube-system + uid: d053eefe-8d34-4ffa-9550-8d68e6f37e08 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kube-controller-manager-kind-control-plane + namespace: kube-system + uid: d420e878-2ba7-45e3-afb4-af859d0891af + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079158 + - category: Pod Security Standards (Baseline) + message: Any capabilities added beyond the allowed list (AUDIT_WRITE, CHOWN, DAC_OVERRIDE, + FOWNER, FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, SETPCAP, SETUID, + SYS_CHROOT) are disallowed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: DaemonSet + name: kindnet + namespace: kube-system + uid: 73917941-f4d3-444f-8d0f-be93ba1e4e2b + result: fail + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: DaemonSet + name: kube-proxy + namespace: kube-system + uid: 78cf0d9f-c3b2-488d-b596-0e4729025aee + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: coredns-5d78c9869d + namespace: kube-system + uid: 919c840d-63cf-4293-8a64-0fd0de15121f + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: coredns + namespace: kube-system + uid: d7418bd6-4c02-4344-864b-d710ee03b7e2 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079150 + summary: + error: 0 + fail: 2 + pass: 10 + skip: 0 + warn: 0 +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:29Z" + generation: 1 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/allowed-base-images: "22432" + name: cpol-allowed-base-images + namespace: kyverno + resourceVersion: "22693" + uid: e1f75f6e-c64e-40e4-b162-5ab8f5831392 + results: + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-admission-controller-7cd788c8dd-gdnhp + namespace: kyverno + uid: 149a831c-bfbd-487e-83f5-59685cc3e7ae + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079155 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-reports-controller-7f94855747-tmnhr + namespace: kyverno + uid: 3113da8b-778d-4650-a00b-8244f46383b6 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-admission-reports-28551310-cc4k7 + namespace: kyverno + uid: 815cbb34-eeea-43ab-977a-ee509cd3c8b4 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-cluster-admission-reports-28551310-m4ld4 + namespace: kyverno + uid: ad02a4a0-765d-41fe-ba8d-4d8bc1f4bbb1 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-controller-ddf458755-9bnlb + namespace: kyverno + uid: d593fd38-2d90-4178-acd2-673a6b9dcbe7 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079156 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-background-controller-74599787cf-s6nm2 + namespace: kyverno + uid: dd188800-5da7-4449-8e97-4333b5c71762 + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079155 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-cleanup-controller + namespace: kyverno + uid: 0ec446db-1759-4c62-b08f-c56cd15ae133 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079152 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: batch/v1 + kind: Job + name: kyverno-cleanup-cluster-admission-reports-28551310 + namespace: kyverno + uid: 1bbefe68-2a6f-4f98-a578-7830ab2ddba7 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079153 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-admission-controller-7cd788c8dd + namespace: kyverno + uid: 2dce65ca-0421-4189-a2d9-c5b0f3509eb0 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079139 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: batch/v1 + kind: Job + name: kyverno-cleanup-admission-reports-28551310 + namespace: kyverno + uid: 7e7fd9ee-2663-45ec-8fc5-2b8224af97be + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-background-controller + namespace: kyverno + uid: a061c459-8d2d-4dfd-95a5-3a74d74be6ad + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079151 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-cleanup-controller-ddf458755 + namespace: kyverno + uid: b64c38ba-5d41-4b05-85c2-04a0fa92d671 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079140 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-background-controller-74599787cf + namespace: kyverno + uid: bdd4f14b-5f6b-463d-a5d2-3ee155150f41 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079138 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-reports-controller + namespace: kyverno + uid: c07941a1-6078-4f18-bd94-ad1ecbd401b0 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079152 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-reports-controller-7f94855747 + namespace: kyverno + uid: c50add3f-7021-4272-8b17-17dc894a1d14 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079140 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-admission-controller + namespace: kyverno + uid: d76bafdd-ff22-4179-a8b2-ee74991635fc + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079151 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: batch/v1 + kind: CronJob + name: kyverno-cleanup-cluster-admission-reports + namespace: kyverno + uid: 61fb66f3-6ae6-4502-9945-f82c37bf1a11 + result: fail + rule: autogen-cronjob-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079149 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: batch/v1 + kind: CronJob + name: kyverno-cleanup-admission-reports + namespace: kyverno + uid: 88974b3b-c9df-440f-aeb4-039221c8aa6c + result: fail + rule: autogen-cronjob-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079149 + summary: + error: 0 + fail: 18 + pass: 0 + skip: 0 + warn: 0 +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:29Z" + generation: 1 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/disallow-capabilities: "22434" + name: cpol-disallow-capabilities + namespace: kyverno + resourceVersion: "22694" + uid: 216df56b-52cb-4fdc-a356-263a0d03a6a4 + results: + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-admission-controller-7cd788c8dd-gdnhp + namespace: kyverno + uid: 149a831c-bfbd-487e-83f5-59685cc3e7ae + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079155 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-reports-controller-7f94855747-tmnhr + namespace: kyverno + uid: 3113da8b-778d-4650-a00b-8244f46383b6 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-admission-reports-28551310-cc4k7 + namespace: kyverno + uid: 815cbb34-eeea-43ab-977a-ee509cd3c8b4 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-cluster-admission-reports-28551310-m4ld4 + namespace: kyverno + uid: ad02a4a0-765d-41fe-ba8d-4d8bc1f4bbb1 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079157 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-cleanup-controller-ddf458755-9bnlb + namespace: kyverno + uid: d593fd38-2d90-4178-acd2-673a6b9dcbe7 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079156 + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: kyverno-background-controller-74599787cf-s6nm2 + namespace: kyverno + uid: dd188800-5da7-4449-8e97-4333b5c71762 + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079155 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-cleanup-controller + namespace: kyverno + uid: 0ec446db-1759-4c62-b08f-c56cd15ae133 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079152 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: batch/v1 + kind: Job + name: kyverno-cleanup-cluster-admission-reports-28551310 + namespace: kyverno + uid: 1bbefe68-2a6f-4f98-a578-7830ab2ddba7 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079153 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-admission-controller-7cd788c8dd + namespace: kyverno + uid: 2dce65ca-0421-4189-a2d9-c5b0f3509eb0 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079129 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: batch/v1 + kind: Job + name: kyverno-cleanup-admission-reports-28551310 + namespace: kyverno + uid: 7e7fd9ee-2663-45ec-8fc5-2b8224af97be + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079154 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-background-controller + namespace: kyverno + uid: a061c459-8d2d-4dfd-95a5-3a74d74be6ad + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079151 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-cleanup-controller-ddf458755 + namespace: kyverno + uid: b64c38ba-5d41-4b05-85c2-04a0fa92d671 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079140 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-background-controller-74599787cf + namespace: kyverno + uid: bdd4f14b-5f6b-463d-a5d2-3ee155150f41 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079139 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-reports-controller + namespace: kyverno + uid: c07941a1-6078-4f18-bd94-ad1ecbd401b0 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079152 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: kyverno-reports-controller-7f94855747 + namespace: kyverno + uid: c50add3f-7021-4272-8b17-17dc894a1d14 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079140 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: kyverno-admission-controller + namespace: kyverno + uid: d76bafdd-ff22-4179-a8b2-ee74991635fc + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079151 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-cronjob-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: batch/v1 + kind: CronJob + name: kyverno-cleanup-cluster-admission-reports + namespace: kyverno + uid: 61fb66f3-6ae6-4502-9945-f82c37bf1a11 + result: pass + rule: autogen-cronjob-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079149 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-cronjob-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: batch/v1 + kind: CronJob + name: kyverno-cleanup-admission-reports + namespace: kyverno + uid: 88974b3b-c9df-440f-aeb4-039221c8aa6c + result: pass + rule: autogen-cronjob-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079149 + summary: + error: 0 + fail: 0 + pass: 18 + skip: 0 + warn: 0 +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:22Z" + generation: 1 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/allowed-base-images: "22432" + name: cpol-allowed-base-images + namespace: local-path-storage + resourceVersion: "22670" + uid: 7475e833-54a2-413c-b54a-648ce5d9abf9 + results: + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: v1 + kind: Pod + name: local-path-provisioner-6bc4bddd6b-vlmww + namespace: local-path-storage + uid: 5863d467-1533-4721-8387-d620c959800e + result: fail + rule: allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079160 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: local-path-provisioner-6bc4bddd6b + namespace: local-path-storage + uid: 5bc38239-ae62-4d6c-bd51-ffda62e44843 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079132 + - category: Other + message: 'validation failure: This container image''s base is not in the approved + list or is not specified. Only pre-approved base images may be used. Please + contact the platform team for assistance.' + policy: allowed-base-images + resources: + - apiVersion: apps/v1 + kind: Deployment + name: local-path-provisioner + namespace: local-path-storage + uid: 94957b8f-76ce-457e-a3ed-628e4403ebc5 + result: fail + rule: autogen-allowed-base-images + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079153 + summary: + error: 0 + fail: 3 + pass: 0 + skip: 0 + warn: 0 +- apiVersion: wgpolicyk8s.io/v1alpha2 + kind: PolicyReport + metadata: + creationTimestamp: "2024-04-14T07:19:22Z" + generation: 1 + labels: + app.kubernetes.io/managed-by: kyverno + cpol.kyverno.io/disallow-capabilities: "22434" + name: cpol-disallow-capabilities + namespace: local-path-storage + resourceVersion: "22671" + uid: adcdbdac-c1cc-4bd3-9077-ba67684e35f3 + results: + - category: Pod Security Standards (Baseline) + message: validation rule 'adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: v1 + kind: Pod + name: local-path-provisioner-6bc4bddd6b-vlmww + namespace: local-path-storage + uid: 5863d467-1533-4721-8387-d620c959800e + result: pass + rule: adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079160 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: ReplicaSet + name: local-path-provisioner-6bc4bddd6b + namespace: local-path-storage + uid: 5bc38239-ae62-4d6c-bd51-ffda62e44843 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079159 + - category: Pod Security Standards (Baseline) + message: validation rule 'autogen-adding-capabilities' passed. + policy: disallow-capabilities + resources: + - apiVersion: apps/v1 + kind: Deployment + name: local-path-provisioner + namespace: local-path-storage + uid: 94957b8f-76ce-457e-a3ed-628e4403ebc5 + result: pass + rule: autogen-adding-capabilities + scored: true + severity: medium + source: kyverno + timestamp: + nanos: 0 + seconds: 1713079153 + summary: + error: 0 + fail: 0 + pass: 3 + skip: 0 + warn: 0 +kind: List +metadata: + resourceVersion: "" diff --git a/plugins_public/tests/data/ocm/component-definition.csv b/plugins_public/tests/data/ocm/component-definition.csv new file mode 100644 index 0000000..917ed12 --- /dev/null +++ b/plugins_public/tests/data/ocm/component-definition.csv @@ -0,0 +1,8 @@ +$$Component_Title,$$Component_Description,$$Component_Type,$$Control_Id_List,$$Rule_Id,$$Rule_Description,$Parameter_Id,$Parameter_Description,$Parameter_Value_Alternatives,$Parameter_Value_Default,$$Profile_Source,$$Profile_Description,Rule_Actual_State_Data_Request_Evidence_Format_Reference_URL_list,Rule_Actual_State_TimeToLive,$Check_Id,$Check_Description,Fetcher_id,Fetcher_Description,Fix_id,Fix_Description,Rule_implementation_status,Rule_POAM_Reference_URL,$$Namespace +A human readable name for the component.,A description of the component including information about its function.,A category describing the purpose of the component. ALLOWED VALUES interconnection:software:hardware:service:physical:process-procedure:plan:guidance:standard:validation:,A list of textual labels that uniquely identify the controls or statements that the component implements.,A textual label that uniquely identifies a policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the policy (desired state) including information about its purpose and scope.,A textual label that uniquely identifies the parameter associated with that policy (desired state) or controls implemented by the policy (desired state).,A description of the parameter including the purpose and use of the parameter.,ONLY for the policy (desired state) parameters: A value or set of values the parameter can take. The catalog parameters values are defined in the catalog. ,"A value recommended by Compliance Team in this profile for the parameter of the control or policy (desired state). If a CIS-benchmark exists, the default default could be the CIS-benchmark recommanded value.",A URL reference to the source catalog or profile for which this component is implementing controls for. A profile designates a selection and configuration of controls from one or more catalogs,A description of the profile.,A list of URL references that contain the Actual State Data Model (eg schema or swager API or procedure template or terraform schema). Needed by the fetcher developer. ,A TimeToLive value of the duration of time the actual state is valid before it becomes stale or obsolite or overriden. Needed by the fetcher developer. ,A textual label that uniquely identifies a check of the policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the check of the policy (desired state) including the method (interview or examine or test) and procedure details.,A textual label that uniquely identifies a collector of the actual state (evidence) associated with the policy (desired state) that can be used to reference it elsewhere in this or other documents.,A description of the collector of the actual state (evidence) associated with the policy (desired state) including the method (interview or examine or API) and questionaire or API details.,A textual label that uniquely identifies the fix of the failed policy.,A description of the fix to remediate the failed policy.,Indicates the degree to which the a given policy is implemented. ALLOWED VALUES: IMPLEMENTED: The control is fully implemented. PARTIAL: The control is partially implemented. PLANNED: There is a plan for implementing the control as explained in the remarks. ALTERNATIVE: There is an alternative implementation for this control as explained in the remarks. NOT-APPLICABLE: This control does not apply to this system as justified in the remarks.,A URL reference to the Plan of Action and Milestones this component may be subjected to for remediation or deviation or mitigation in case of the policy (desired state) non compliance or error or failure. ,"A namespace qualifying the property's name. This allows different organizations to associate distinct semantics with the same name. Used in conjunction with ""class"" as the ontology concept. " +Managed Kubernetes,Managed Kubernetes cluster,Service,cm-2,policy-deployment,Ensure deployment configuration is securely set up,minimum_nginx_deployment_replicas,Minimum number of NGINX pod,3,3,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-deployment,Ensure NGINX is deployed and running with given minimum instances,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +Managed Kubernetes,Managed Kubernetes cluster,Service,ac-1,policy-disallowed-roles,Ensure roles are set to only allowed values,,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-disallowed-roles,Ensure roles are set to only allowed values,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +Managed Kubernetes,Managed Kubernetes cluster,Service,cm-6,policy-high-scan,Ensure scan is enabled with high level,,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-high-scan,Ensure scan is enabled with high level,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +OCM,OCM as Policy Validation Point,Validation,na,policy-deployment,Ensure NGINX is deployed and running with given minimum instances,,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-deployment,Ensure NGINX is deployed and running with given minimum instances,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +OCM,OCM as Policy Validation Point,Validation,na,policy-disallowed-roles,Ensure roles are set to only allowed values,,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-disallowed-roles,Ensure roles are set to only allowed values,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud +OCM,OCM as Policy Validation Point,Validation,na,policy-high-scan,Ensure scan is enabled with high level,,,,,https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json,NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE,,,policy-high-scan,Ensure scan is enabled with high level,,,,,,,http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud \ No newline at end of file diff --git a/plugins_public/tests/data/ocm/component-definition.json b/plugins_public/tests/data/ocm/component-definition.json new file mode 100644 index 0000000..538d755 --- /dev/null +++ b/plugins_public/tests/data/ocm/component-definition.json @@ -0,0 +1,275 @@ +{ + "component-definition": { + "uuid": "f78115b4-0d04-4324-b78a-31d8f25407ce", + "metadata": { + "title": "Component Definition for managed clusters", + "last-modified": "2024-04-14T08:51:31+00:00", + "version": "1.0", + "oscal-version": "1.0.4" + }, + "components": [ + { + "uuid": "c740b275-7c18-44fa-aa1d-ff5d99d569c5", + "type": "Service", + "title": "Managed Kubernetes", + "description": "Managed Kubernetes cluster", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment", + "remarks": "rule_set_0" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure deployment configuration is securely set up", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "minimum_nginx_deployment_replicas", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Minimum number of NGINX pod", + "remarks": "rule_set_0" + }, + { + "name": "Parameter_Value_Alternatives", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "3", + "remarks": "rule_set_0" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment", + "remarks": "rule_set_0" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure NGINX is deployed and running with given minimum instances", + "remarks": "rule_set_0" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles", + "remarks": "rule_set_1" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure roles are set to only allowed values", + "remarks": "rule_set_1" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles", + "remarks": "rule_set_1" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure roles are set to only allowed values", + "remarks": "rule_set_1" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_2" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure scan is enabled with high level", + "remarks": "rule_set_2" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_2" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure scan is enabled with high level", + "remarks": "rule_set_2" + } + ], + "control-implementations": [ + { + "uuid": "524a1e8e-284b-43d8-b220-5ce9177119f6", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "set-parameters": [ + { + "param-id": "minimum_nginx_deployment_replicas", + "values": [ + "3" + ] + } + ], + "implemented-requirements": [ + { + "uuid": "f241525c-83f6-4f3d-b114-b5e3e466a81d", + "control-id": "cm-2", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment" + } + ] + }, + { + "uuid": "712186cc-785d-4dee-84bd-2377d04735ab", + "control-id": "ac-1", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles" + } + ] + }, + { + "uuid": "232e98d5-1c3f-4f53-b0d6-e60a7fa70ac5", + "control-id": "cm-6", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan" + } + ] + } + ] + } + ] + }, + { + "uuid": "87ce7ffa-b432-4c2f-9780-b9aa67c8fb5c", + "type": "Validation", + "title": "OCM", + "description": "OCM as Policy Validation Point", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment", + "remarks": "rule_set_3" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure NGINX is deployed and running with given minimum instances", + "remarks": "rule_set_3" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment", + "remarks": "rule_set_3" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure NGINX is deployed and running with given minimum instances", + "remarks": "rule_set_3" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles", + "remarks": "rule_set_4" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure roles are set to only allowed values", + "remarks": "rule_set_4" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles", + "remarks": "rule_set_4" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure roles are set to only allowed values", + "remarks": "rule_set_4" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_5" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure scan is enabled with high level", + "remarks": "rule_set_5" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_5" + }, + { + "name": "Check_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure scan is enabled with high level", + "remarks": "rule_set_5" + } + ], + "control-implementations": [ + { + "uuid": "2b342e42-7c5f-429f-835d-d3c8a5edd8fc", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "implemented-requirements": [ + { + "uuid": "bec41a64-d9ab-408f-bc6c-d00bf95b5b36", + "control-id": "na", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-deployment" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-disallowed-roles" + }, + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan" + } + ] + } + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/plugins_public/tests/data/ocm/deliverable-policy/kustomization.yaml b/plugins_public/tests/data/ocm/deliverable-policy/kustomization.yaml new file mode 100644 index 0000000..50d97fb --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/kustomization.yaml @@ -0,0 +1,10 @@ +generators: +- ./policy-generator.yaml +patches: +- patch: '[{"op": "replace", "path": "/metadata/annotations/compliance-to-policy.component-title", + "value": "c2p test"}]' + target: + kind: PolicySet + name: c2p-test +resources: +- ./parameters.yaml diff --git a/plugins_public/tests/data/ocm/deliverable-policy/parameters.yaml b/plugins_public/tests/data/ocm/deliverable-policy/parameters.yaml new file mode 100644 index 0000000..31f13ef --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/parameters.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +data: + minimum_nginx_deployment_replicas: '3' +kind: ConfigMap +metadata: + name: c2p-parameters + namespace: c2p diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/kustomization.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-generator.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-generator.yaml new file mode 100755 index 0000000..89c829a --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-generator.yaml @@ -0,0 +1,23 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policies: +- complianceType: musthave + consolidateManifests: true + manifests: + - path: ./policy-nginx-deployment + name: policy-deployment + orderManifests: false + remediationAction: inform + severity: low +policyDefaults: + categories: [] + consolidateManifests: false + controls: [] + namespace: c2p + orderManifests: false + placement: + clusterSelectors: + environment: dev + standards: [] diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml new file mode 100755 index 0000000..8d59ace --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: nginx + name: nginx-deployment +spec: + replicas: '{{hub fromConfigMap "c2p" "c2p-parameters" "minimum_nginx_deployment_replicas" | toInt hub}}' + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.21.4 + name: nginx + ports: + - containerPort: 80 diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/kustomization.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml new file mode 100755 index 0000000..bb259be --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml @@ -0,0 +1,9 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +rules: +- apiGroups: + - '*' + resources: + - '*' + verbs: + - '*' diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-generator.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-generator.yaml new file mode 100755 index 0000000..8bd0ef7 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-disallowed-roles/policy-generator.yaml @@ -0,0 +1,23 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policies: +- complianceType: mustnothave + consolidateManifests: true + manifests: + - path: ./policy-disallowed-roles-sample-role + name: policy-disallowed-roles + orderManifests: false + remediationAction: inform + severity: high +policyDefaults: + categories: [] + consolidateManifests: false + controls: [] + namespace: c2p + orderManifests: false + placement: + clusterSelectors: + environment: dev + standards: [] diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-generator.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-generator.yaml new file mode 100644 index 0000000..56a38ed --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-generator.yaml @@ -0,0 +1,89 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-set +placementBindingDefaults: + name: policy-set +policies: +- categories: [] + complianceType: musthave + consolidateManifests: true + controls: [] + informGatekeeperPolicies: false + informKyvernoPolicies: false + manifests: + - ignorePending: false + path: ./policy-deployment/policy-nginx-deployment + name: policy-deployment + orderManifests: false + remediationAction: inform + severity: low + standards: [] +- categories: [] + complianceType: mustnothave + consolidateManifests: true + controls: [] + informGatekeeperPolicies: false + informKyvernoPolicies: false + manifests: + - ignorePending: false + path: ./policy-disallowed-roles/policy-disallowed-roles-sample-role + name: policy-disallowed-roles + orderManifests: false + remediationAction: inform + severity: high + standards: [] +- categories: [] + complianceType: mustnothave + consolidateManifests: false + controls: [] + informGatekeeperPolicies: false + informKyvernoPolicies: false + manifests: + - complianceType: musthave + ignorePending: false + path: ./policy-high-scan/compliance-high-scan + remediationAction: inform + severity: high + - complianceType: musthave + ignorePending: false + path: ./policy-high-scan/compliance-suite-high + remediationAction: inform + severity: high + - complianceType: mustnothave + ignorePending: false + path: ./policy-high-scan/compliance-suite-high-results + remediationAction: inform + severity: high + name: policy-high-scan + orderManifests: false + remediationAction: inform + severity: high + standards: [] +policyDefaults: + consolidateManifests: false + informGatekeeperPolicies: false + informKyvernoPolicies: false + namespace: c2p + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + orderManifests: false + placement: + labelSelector: + environment: dev +policySetDefaults: + placement: + labelSelector: + environment: dev +policySets: +- name: c2p-test + policies: + - policy-deployment + - policy-disallowed-roles + - policy-high-scan diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml new file mode 100755 index 0000000..620bcd0 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml @@ -0,0 +1,16 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ScanSettingBinding +metadata: + name: high + namespace: openshift-compliance +profiles: +- apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high +- apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high-node +settingsRef: + apiGroup: compliance.openshift.io/v1alpha1 + kind: ScanSetting + name: default diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml new file mode 100755 index 0000000..e1cba9b --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml @@ -0,0 +1,7 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ComplianceCheckResult +metadata: + labels: + compliance.openshift.io/check-status: FAIL + compliance.openshift.io/suite: high + namespace: openshift-compliance diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml new file mode 100755 index 0000000..cdc5b90 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml @@ -0,0 +1,7 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ComplianceSuite +metadata: + name: high + namespace: openshift-compliance +status: + phase: DONE diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/kustomization.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/policy-generator.yaml b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/policy-generator.yaml new file mode 100755 index 0000000..e6df871 --- /dev/null +++ b/plugins_public/tests/data/ocm/deliverable-policy/policy-high-scan/policy-generator.yaml @@ -0,0 +1,31 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policies: +- consolidateManifests: false + manifests: + - complianceType: musthave + path: ./compliance-high-scan + remediationAction: inform + severity: high + - complianceType: musthave + path: ./compliance-suite-high + remediationAction: inform + severity: high + - complianceType: mustnothave + path: ./compliance-suite-high-results + remediationAction: inform + severity: high + name: policy-high-scan + orderManifests: false +policyDefaults: + categories: [] + consolidateManifests: false + controls: [] + namespace: c2p + orderManifests: false + placement: + clusterSelectors: + environment: dev + standards: [] diff --git a/plugins_public/tests/data/ocm/placementdecisions.cluster.open-cluster-management.io.yaml b/plugins_public/tests/data/ocm/placementdecisions.cluster.open-cluster-management.io.yaml new file mode 100644 index 0000000..1175676 --- /dev/null +++ b/plugins_public/tests/data/ocm/placementdecisions.cluster.open-cluster-management.io.yaml @@ -0,0 +1,29 @@ +apiVersion: v1 +items: +- apiVersion: cluster.open-cluster-management.io/v1beta1 + kind: PlacementDecision + metadata: + creationTimestamp: "2023-07-05T16:10:56Z" + generation: 1 + labels: + cluster.open-cluster-management.io/placement: placement-managed-kubernetes + name: placement-managed-kubernetes-decision-1 + namespace: c2p + ownerReferences: + - apiVersion: cluster.open-cluster-management.io/v1beta1 + blockOwnerDeletion: true + controller: true + kind: Placement + name: placement-managed-kubernetes + uid: fb698906-ffbc-4483-afc1-e87cd6048858 + resourceVersion: "127345" + uid: 78e9e593-8ca7-48f2-86af-0306238cdedc + status: + decisions: + - clusterName: cluster1 + reason: "" + - clusterName: cluster2 + reason: "" +kind: List +metadata: + resourceVersion: "" diff --git a/plugins_public/tests/data/ocm/policies.policy.open-cluster-management.io.yaml b/plugins_public/tests/data/ocm/policies.policy.open-cluster-management.io.yaml new file mode 100644 index 0000000..b822566 --- /dev/null +++ b/plugins_public/tests/data/ocm/policies.policy.open-cluster-management.io.yaml @@ -0,0 +1,901 @@ +apiVersion: v1 +items: +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-2","policy.open-cluster-management.io/standards":""},"name":"policy-deployment","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-deployment"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"labels":{"app":"nginx"},"name":"nginx-deployment"},"spec":{"replicas":3,"selector":{"matchLabels":{"app":"nginx"}},"template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"containers":[{"image":"nginx:1.21.4","name":"nginx","ports":[{"containerPort":80}]}]}}}}}],"remediationAction":"inform","severity":"low"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-2 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T16:10:56Z" + generation: 2 + name: policy-deployment + namespace: c2p + resourceVersion: "58942" + uid: 55fb6d11-cdf5-43a6-8848-7076ea3c02ba + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-deployment + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: apps/v1 + kind: Deployment + metadata: + labels: + app: nginx + name: nginx-deployment + spec: + replicas: 3 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.21.4 + name: nginx + ports: + - containerPort: 80 + remediationAction: inform + severity: low + remediationAction: inform + status: + compliant: NonCompliant + placement: + - placement: placement-managed-kubernetes + placementBinding: policy-set + policySet: managed-kubernetes + status: + - clustername: cluster1 + clusternamespace: cluster1 + compliant: NonCompliant + - clustername: cluster2 + clusternamespace: cluster2 + compliant: NonCompliant +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"ac-6","policy.open-cluster-management.io/standards":""},"name":"policy-disallowed-roles","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-disallowed-roles"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","rules":[{"apiGroups":["*"],"resources":["*"],"verbs":["*"]}]}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: ac-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T16:10:56Z" + generation: 2 + name: policy-disallowed-roles + namespace: c2p + resourceVersion: "58945" + uid: 3aa8b4b0-6aa0-4635-a55d-342a9f38660e + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-disallowed-roles + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + rules: + - apiGroups: + - '*' + resources: + - '*' + verbs: + - '*' + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: Compliant + placement: + - placement: placement-managed-kubernetes + placementBinding: policy-set + policySet: managed-kubernetes + status: + - clustername: cluster1 + clusternamespace: cluster1 + compliant: Compliant + - clustername: cluster2 + clusternamespace: cluster2 + compliant: Compliant +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-6","policy.open-cluster-management.io/standards":""},"name":"policy-high-scan","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ScanSettingBinding","metadata":{"name":"high","namespace":"openshift-compliance"},"profiles":[{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high"},{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high-node"}],"settingsRef":{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"ScanSetting","name":"default"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan2"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceSuite","metadata":{"name":"high","namespace":"openshift-compliance"},"status":{"phase":"DONE"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan3"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceCheckResult","metadata":{"labels":{"compliance.openshift.io/check-status":"FAIL","compliance.openshift.io/suite":"high"},"namespace":"openshift-compliance"}}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T16:10:56Z" + generation: 2 + name: policy-high-scan + namespace: c2p + resourceVersion: "58952" + uid: 1e829f28-a2e6-4b5b-9b58-d18c11730841 + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ScanSettingBinding + metadata: + name: high + namespace: openshift-compliance + profiles: + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high-node + settingsRef: + apiGroup: compliance.openshift.io/v1alpha1 + kind: ScanSetting + name: default + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan2 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceSuite + metadata: + name: high + namespace: openshift-compliance + status: + phase: DONE + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan3 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceCheckResult + metadata: + labels: + compliance.openshift.io/check-status: FAIL + compliance.openshift.io/suite: high + namespace: openshift-compliance + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: NonCompliant + placement: + - placement: placement-managed-kubernetes + placementBinding: policy-set + policySet: managed-kubernetes + status: + - clustername: cluster1 + clusternamespace: cluster1 + compliant: NonCompliant + - clustername: cluster2 + clusternamespace: cluster2 + compliant: NonCompliant +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-2","policy.open-cluster-management.io/standards":""},"name":"policy-deployment","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-deployment"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"labels":{"app":"nginx"},"name":"nginx-deployment"},"spec":{"replicas":3,"selector":{"matchLabels":{"app":"nginx"}},"template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"containers":[{"image":"nginx:1.21.4","name":"nginx","ports":[{"containerPort":80}]}]}}}}}],"remediationAction":"inform","severity":"low"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-2 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:52:32Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster1 + policy.open-cluster-management.io/cluster-namespace: cluster1 + policy.open-cluster-management.io/root-policy: c2p.policy-deployment + name: c2p.policy-deployment + namespace: cluster1 + resourceVersion: "58997" + uid: 3d7bf6b3-4332-4195-81b4-d343a847c3f8 + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-deployment + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: apps/v1 + kind: Deployment + metadata: + labels: + app: nginx + name: nginx-deployment + spec: + replicas: 3 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.21.4 + name: nginx + ports: + - containerPort: 80 + remediationAction: inform + severity: low + remediationAction: inform + status: + compliant: NonCompliant + details: + - compliant: NonCompliant + history: + - eventName: c2p.policy-deployment.176f1ddc5591cb1c + lastTimestamp: "2023-07-05T23:53:37Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster1 missing; [nginx-deployment] in namespace kube-node-lease + missing; [nginx-deployment] in namespace kube-public missing; [nginx-deployment] + in namespace local-path-storage missing' + - eventName: c2p.policy-deployment.176f1dc090333b1b + lastTimestamp: "2023-07-05T23:51:38Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster1 missing; [nginx-deployment] in namespace kube-node-lease + missing; [nginx-deployment] in namespace kube-public missing; [nginx-deployment] + in namespace local-path-storage missing' + - eventName: c2p.policy-deployment.176f1bee3daf20de + lastTimestamp: "2023-07-05T23:18:15Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster1 missing; [nginx-deployment] in namespace kube-node-lease + missing; [nginx-deployment] in namespace kube-public missing; [nginx-deployment] + in namespace local-path-storage missing' + templateMeta: + creationTimestamp: null + name: policy-deployment +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"ac-6","policy.open-cluster-management.io/standards":""},"name":"policy-disallowed-roles","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-disallowed-roles"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","rules":[{"apiGroups":["*"],"resources":["*"],"verbs":["*"]}]}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: ac-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:52:32Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster1 + policy.open-cluster-management.io/cluster-namespace: cluster1 + policy.open-cluster-management.io/root-policy: c2p.policy-disallowed-roles + name: c2p.policy-disallowed-roles + namespace: cluster1 + resourceVersion: "58962" + uid: dea67078-25f4-4c45-9e55-01796af1999e + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-disallowed-roles + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + rules: + - apiGroups: + - '*' + resources: + - '*' + verbs: + - '*' + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: Compliant + details: + - compliant: Compliant + history: + - eventName: c2p.policy-disallowed-roles.176f1dcdc4c8d17e + lastTimestamp: "2023-07-05T23:52:34Z" + message: Compliant; notification - roles in namespace cluster1; in namespace + default; in namespace kube-node-lease; in namespace kube-public; in namespace + local-path-storage missing as expected, therefore this Object template is + compliant + - eventName: c2p.policy-disallowed-roles.176f1cd7a1623786 + lastTimestamp: "2023-07-05T23:34:57Z" + message: Compliant; notification - roles in namespace cluster1; in namespace + default; in namespace kube-node-lease; in namespace kube-public; in namespace + local-path-storage missing as expected, therefore this Object template is + compliant + - eventName: c2p.policy-disallowed-roles.176f1bee3d61b1f3 + lastTimestamp: "2023-07-05T23:18:15Z" + message: Compliant; notification - roles in namespace cluster1; in namespace + default; in namespace kube-node-lease; in namespace kube-public; in namespace + local-path-storage missing as expected, therefore this Object template is + compliant + templateMeta: + creationTimestamp: null + name: policy-disallowed-roles +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-6","policy.open-cluster-management.io/standards":""},"name":"policy-high-scan","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ScanSettingBinding","metadata":{"name":"high","namespace":"openshift-compliance"},"profiles":[{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high"},{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high-node"}],"settingsRef":{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"ScanSetting","name":"default"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan2"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceSuite","metadata":{"name":"high","namespace":"openshift-compliance"},"status":{"phase":"DONE"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan3"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceCheckResult","metadata":{"labels":{"compliance.openshift.io/check-status":"FAIL","compliance.openshift.io/suite":"high"},"namespace":"openshift-compliance"}}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:52:32Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster1 + policy.open-cluster-management.io/cluster-namespace: cluster1 + policy.open-cluster-management.io/root-policy: c2p.policy-high-scan + name: c2p.policy-high-scan + namespace: cluster1 + resourceVersion: "58991" + uid: 4007f281-2977-42c4-ab42-cf0fb8563f56 + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ScanSettingBinding + metadata: + name: high + namespace: openshift-compliance + profiles: + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high-node + settingsRef: + apiGroup: compliance.openshift.io/v1alpha1 + kind: ScanSetting + name: default + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan2 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceSuite + metadata: + name: high + namespace: openshift-compliance + status: + phase: DONE + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan3 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceCheckResult + metadata: + labels: + compliance.openshift.io/check-status: FAIL + compliance.openshift.io/suite: high + namespace: openshift-compliance + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: NonCompliant + details: + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1dcdc2b51b01 + lastTimestamp: "2023-07-05T23:52:34Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ScanSettingBinding, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1cd79ed5ce45 + lastTimestamp: "2023-07-05T23:34:57Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ScanSettingBinding, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1bef5d9a8c7c + lastTimestamp: "2023-07-05T23:18:20Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ScanSettingBinding, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1ddc44adf035 + lastTimestamp: "2023-07-05T23:53:37Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceSuite, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1dc08583a394 + lastTimestamp: "2023-07-05T23:51:37Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceSuite, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1bef5e40c973 + lastTimestamp: "2023-07-05T23:18:20Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceSuite, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan2 + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1ddc441457e5 + lastTimestamp: "2023-07-05T23:53:37Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceCheckResult, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1dc085241b09 + lastTimestamp: "2023-07-05T23:51:37Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceCheckResult, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1bf01c04e351 + lastTimestamp: "2023-07-05T23:18:23Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceCheckResult, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan3 +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-2","policy.open-cluster-management.io/standards":""},"name":"policy-deployment","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-deployment"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"labels":{"app":"nginx"},"name":"nginx-deployment"},"spec":{"replicas":3,"selector":{"matchLabels":{"app":"nginx"}},"template":{"metadata":{"labels":{"app":"nginx"}},"spec":{"containers":[{"image":"nginx:1.21.4","name":"nginx","ports":[{"containerPort":80}]}]}}}}}],"remediationAction":"inform","severity":"low"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-2 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:51:43Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster2 + policy.open-cluster-management.io/cluster-namespace: cluster2 + policy.open-cluster-management.io/root-policy: c2p.policy-deployment + name: c2p.policy-deployment + namespace: cluster2 + resourceVersion: "58322" + uid: 25080d0e-e6cf-4f39-94cb-04a7d01d6cfe + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-deployment + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: apps/v1 + kind: Deployment + metadata: + labels: + app: nginx + name: nginx-deployment + spec: + replicas: 3 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.21.4 + name: nginx + ports: + - containerPort: 80 + remediationAction: inform + severity: low + remediationAction: inform + status: + compliant: NonCompliant + details: + - compliant: NonCompliant + history: + - eventName: c2p.policy-deployment.176f1dc4e7de17cb + lastTimestamp: "2023-07-05T23:51:56Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster2 missing; [nginx-deployment] in namespace default missing; + [nginx-deployment] in namespace kube-node-lease missing; [nginx-deployment] + in namespace kube-public missing; [nginx-deployment] in namespace local-path-storage + missing' + - eventName: c2p.policy-deployment.176f1bf28b594e3c + lastTimestamp: "2023-07-05T23:18:33Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster2 missing; [nginx-deployment] in namespace default missing; + [nginx-deployment] in namespace kube-node-lease missing; [nginx-deployment] + in namespace kube-public missing; [nginx-deployment] in namespace local-path-storage + missing' + - eventName: c2p.policy-deployment.176f1bf06f3be6c5 + lastTimestamp: "2023-07-05T23:18:24Z" + message: 'NonCompliant; violation - deployments not found: [nginx-deployment] + in namespace cluster2 missing; [nginx-deployment] in namespace default missing; + [nginx-deployment] in namespace kube-node-lease missing; [nginx-deployment] + in namespace kube-public missing; [nginx-deployment] in namespace local-path-storage + missing' + templateMeta: + creationTimestamp: null + name: policy-deployment +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"ac-6","policy.open-cluster-management.io/standards":""},"name":"policy-disallowed-roles","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-disallowed-roles"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","rules":[{"apiGroups":["*"],"resources":["*"],"verbs":["*"]}]}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: ac-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:51:43Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster2 + policy.open-cluster-management.io/cluster-namespace: cluster2 + policy.open-cluster-management.io/root-policy: c2p.policy-disallowed-roles + name: c2p.policy-disallowed-roles + namespace: cluster2 + resourceVersion: "58171" + uid: fb2bed28-f7be-4ad3-9df2-00f26600feb7 + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-disallowed-roles + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: rbac.authorization.k8s.io/v1 + kind: Role + rules: + - apiGroups: + - '*' + resources: + - '*' + verbs: + - '*' + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: Compliant + details: + - compliant: Compliant + history: + - eventName: c2p.policy-disallowed-roles.176f1dc36e36b7b2 + lastTimestamp: "2023-07-05T23:51:50Z" + message: Compliant; notification - roles in namespace cluster2; in namespace + default; in namespace kube-node-lease; in namespace kube-public; in namespace + local-path-storage missing as expected, therefore this Object template is + compliant + - eventName: c2p.policy-disallowed-roles.176f1bf28b48947f + lastTimestamp: "2023-07-05T23:18:33Z" + message: Compliant; notification - roles in namespace cluster2; in namespace + default; in namespace kube-node-lease; in namespace kube-public; in namespace + local-path-storage missing as expected, therefore this Object template is + compliant + templateMeta: + creationTimestamp: null + name: policy-disallowed-roles +- apiVersion: policy.open-cluster-management.io/v1 + kind: Policy + metadata: + annotations: + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1","kind":"Policy","metadata":{"annotations":{"policy.open-cluster-management.io/categories":"","policy.open-cluster-management.io/controls":"cm-6","policy.open-cluster-management.io/standards":""},"name":"policy-high-scan","namespace":"c2p"},"spec":{"disabled":false,"policy-templates":[{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ScanSettingBinding","metadata":{"name":"high","namespace":"openshift-compliance"},"profiles":[{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high"},{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"Profile","name":"ocp4-high-node"}],"settingsRef":{"apiGroup":"compliance.openshift.io/v1alpha1","kind":"ScanSetting","name":"default"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan2"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"musthave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceSuite","metadata":{"name":"high","namespace":"openshift-compliance"},"status":{"phase":"DONE"}}}],"remediationAction":"inform","severity":"high"}}},{"objectDefinition":{"apiVersion":"policy.open-cluster-management.io/v1","kind":"ConfigurationPolicy","metadata":{"name":"policy-high-scan3"},"spec":{"namespaceSelector":{"exclude":["kube-system","open-cluster-management","open-cluster-management-agent","open-cluster-management-agent-addon"],"include":["*"]},"object-templates":[{"complianceType":"mustnothave","objectDefinition":{"apiVersion":"compliance.openshift.io/v1alpha1","kind":"ComplianceCheckResult","metadata":{"labels":{"compliance.openshift.io/check-status":"FAIL","compliance.openshift.io/suite":"high"},"namespace":"openshift-compliance"}}}],"remediationAction":"inform","severity":"high"}}}],"remediationAction":"inform"}} + policy.open-cluster-management.io/categories: "" + policy.open-cluster-management.io/controls: cm-6 + policy.open-cluster-management.io/standards: "" + creationTimestamp: "2023-07-05T23:51:43Z" + generation: 1 + labels: + policy.open-cluster-management.io/cluster-name: cluster2 + policy.open-cluster-management.io/cluster-namespace: cluster2 + policy.open-cluster-management.io/root-policy: c2p.policy-high-scan + name: c2p.policy-high-scan + namespace: cluster2 + resourceVersion: "58319" + uid: 38eb6af4-5b3f-4a8b-aa1b-f066cd7a3ed8 + spec: + disabled: false + policy-templates: + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ScanSettingBinding + metadata: + name: high + namespace: openshift-compliance + profiles: + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high + - apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high-node + settingsRef: + apiGroup: compliance.openshift.io/v1alpha1 + kind: ScanSetting + name: default + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan2 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: musthave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceSuite + metadata: + name: high + namespace: openshift-compliance + status: + phase: DONE + remediationAction: inform + severity: high + - objectDefinition: + apiVersion: policy.open-cluster-management.io/v1 + kind: ConfigurationPolicy + metadata: + name: policy-high-scan3 + spec: + namespaceSelector: + exclude: + - kube-system + - open-cluster-management + - open-cluster-management-agent + - open-cluster-management-agent-addon + include: + - '*' + object-templates: + - complianceType: mustnothave + objectDefinition: + apiVersion: compliance.openshift.io/v1alpha1 + kind: ComplianceCheckResult + metadata: + labels: + compliance.openshift.io/check-status: FAIL + compliance.openshift.io/suite: high + namespace: openshift-compliance + remediationAction: inform + severity: high + remediationAction: inform + status: + compliant: NonCompliant + details: + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1dc3684f9eb6 + lastTimestamp: "2023-07-05T23:51:50Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ScanSettingBinding, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1ccd9a7768a0 + lastTimestamp: "2023-07-05T23:34:14Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ScanSettingBinding, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1dc426d20948 + lastTimestamp: "2023-07-05T23:51:53Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceSuite, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1ccd9a7af3da + lastTimestamp: "2023-07-05T23:34:14Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceSuite, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan2 + - compliant: NonCompliant + history: + - eventName: c2p.policy-high-scan.176f1dc4e29e1221 + lastTimestamp: "2023-07-05T23:51:56Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceCheckResult, please check if you have CRD deployed + - eventName: c2p.policy-high-scan.176f1cce592bc71e + lastTimestamp: "2023-07-05T23:34:17Z" + message: NonCompliant; violation - couldn't find mapping resource with kind + ComplianceCheckResult, please check if you have CRD deployed + templateMeta: + creationTimestamp: null + name: policy-high-scan3 +kind: List +metadata: + resourceVersion: "" diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-deployment/kustomization.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-generator.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-generator.yaml new file mode 100755 index 0000000..a862b0e --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-generator.yaml @@ -0,0 +1,17 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policyDefaults: + consolidateManifests: false + orderManifests: false + namespace: namespace +policies: + - consolidateManifests: true + orderManifests: false + remediationAction: inform + severity: low + complianceType: musthave + name: policy-deployment + manifests: + - path: ./policy-nginx-deployment diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml new file mode 100755 index 0000000..8d59ace --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-deployment/policy-nginx-deployment/Deployment.nginx-deployment.0.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + labels: + app: nginx + name: nginx-deployment +spec: + replicas: '{{hub fromConfigMap "c2p" "c2p-parameters" "minimum_nginx_deployment_replicas" | toInt hub}}' + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - image: nginx:1.21.4 + name: nginx + ports: + - containerPort: 80 diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/kustomization.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml new file mode 100755 index 0000000..bb259be --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-disallowed-roles-sample-role/Role.noname.0.yaml @@ -0,0 +1,9 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +rules: +- apiGroups: + - '*' + resources: + - '*' + verbs: + - '*' diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-generator.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-generator.yaml new file mode 100755 index 0000000..b3ef68e --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-disallowed-roles/policy-generator.yaml @@ -0,0 +1,17 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policyDefaults: + consolidateManifests: false + orderManifests: false + namespace: namespace +policies: + - consolidateManifests: true + orderManifests: false + remediationAction: inform + severity: high + complianceType: mustnothave + name: policy-disallowed-roles + manifests: + - path: ./policy-disallowed-roles-sample-role diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml new file mode 100755 index 0000000..620bcd0 --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-high-scan/ScanSettingBinding.high.0.yaml @@ -0,0 +1,16 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ScanSettingBinding +metadata: + name: high + namespace: openshift-compliance +profiles: +- apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high +- apiGroup: compliance.openshift.io/v1alpha1 + kind: Profile + name: ocp4-high-node +settingsRef: + apiGroup: compliance.openshift.io/v1alpha1 + kind: ScanSetting + name: default diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml new file mode 100755 index 0000000..e1cba9b --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high-results/ComplianceCheckResult.noname.0.yaml @@ -0,0 +1,7 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ComplianceCheckResult +metadata: + labels: + compliance.openshift.io/check-status: FAIL + compliance.openshift.io/suite: high + namespace: openshift-compliance diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml new file mode 100755 index 0000000..cdc5b90 --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/compliance-suite-high/ComplianceSuite.high.0.yaml @@ -0,0 +1,7 @@ +apiVersion: compliance.openshift.io/v1alpha1 +kind: ComplianceSuite +metadata: + name: high + namespace: openshift-compliance +status: + phase: DONE diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/kustomization.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/kustomization.yaml new file mode 100755 index 0000000..0573618 --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/kustomization.yaml @@ -0,0 +1,2 @@ +generators: +- ./policy-generator.yaml diff --git a/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/policy-generator.yaml b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/policy-generator.yaml new file mode 100755 index 0000000..3fad8fc --- /dev/null +++ b/plugins_public/tests/data/ocm/policy-resources/policy-high-scan/policy-generator.yaml @@ -0,0 +1,25 @@ +apiVersion: policy.open-cluster-management.io/v1 +kind: PolicyGenerator +metadata: + name: policy-generator +policyDefaults: + consolidateManifests: false + orderManifests: false + namespace: namespace +policies: + - consolidateManifests: false + orderManifests: false + name: policy-high-scan + manifests: + - remediationAction: inform + severity: high + complianceType: musthave + path: ./compliance-high-scan + - remediationAction: inform + severity: high + complianceType: musthave + path: ./compliance-suite-high + - remediationAction: inform + severity: high + complianceType: mustnothave + path: ./compliance-suite-high-results diff --git a/plugins_public/tests/data/ocm/policysets.policy.open-cluster-management.io.yaml b/plugins_public/tests/data/ocm/policysets.policy.open-cluster-management.io.yaml new file mode 100644 index 0000000..1c8acb0 --- /dev/null +++ b/plugins_public/tests/data/ocm/policysets.policy.open-cluster-management.io.yaml @@ -0,0 +1,30 @@ +apiVersion: v1 +items: +- apiVersion: policy.open-cluster-management.io/v1beta1 + kind: PolicySet + metadata: + annotations: + compliance-to-policy.component-title: Managed Kubernetes + kubectl.kubernetes.io/last-applied-configuration: | + {"apiVersion":"policy.open-cluster-management.io/v1beta1","kind":"PolicySet","metadata":{"annotations":{"compliance-to-policy.component-title":"Managed Kubernetes"},"name":"managed-kubernetes","namespace":"c2p"},"spec":{"description":"","policies":["policy-deployment","policy-disallowed-roles","policy-high-scan"]}} + creationTimestamp: "2023-07-05T16:10:56Z" + generation: 1 + name: managed-kubernetes + namespace: c2p + resourceVersion: "80787" + uid: 1ac57f03-4782-4ef8-8b65-08384e36971f + spec: + description: "" + policies: + - policy-deployment + - policy-disallowed-roles + - policy-high-scan + status: + compliant: NonCompliant + placement: + - placement: placement-managed-kubernetes + placementBinding: policy-set + statusMessage: All policies are reporting status +kind: List +metadata: + resourceVersion: "" diff --git a/plugins_public/tests/plugins/__init__.py b/plugins_public/tests/plugins/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/plugins_public/tests/plugins/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/plugins_public/tests/plugins/test_kyverno.py b/plugins_public/tests/plugins/test_kyverno.py new file mode 100644 index 0000000..3871d92 --- /dev/null +++ b/plugins_public/tests/plugins/test_kyverno.py @@ -0,0 +1,76 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import os +import pathlib + +from c2p.framework.models import Parameter, Policy, RawResult, RuleSet +from plugins_public.plugins.kyverno import PluginConfigKyverno, PluginKyverno +from plugins_public.tests.utils import load_yaml, load_yamls + +TEST_DATA_DIR = os.getenv('TEST_DATA_DIR', 'plugins_public/tests/data/kyverno') + + +def test_kyverno_pvp_result_to_compliance(): + cpolr = load_yaml(f'{TEST_DATA_DIR}/clusterpolicyreports.wgpolicyk8s.io.yaml') + polr = load_yaml(f'{TEST_DATA_DIR}/policyreports.wgpolicyk8s.io.yaml') + raw = cpolr['items'] + polr['items'] + raw_result = RawResult(data=raw) + pvp_result = PluginKyverno().generate_pvp_result(raw_result) + assert 2 == len(pvp_result.observations_by_check) + assert 33 == len(pvp_result.observations_by_check[0].subjects) + assert 33 == len(pvp_result.observations_by_check[1].subjects) + + +def test_kyverno_compliance_to_policy(): + policy_template_dir = f'{TEST_DATA_DIR}/policy-resources' + deliverable_policy_dir = f'{TEST_DATA_DIR}/deliverable-policy' + config = PluginConfigKyverno(policy_template_dir=policy_template_dir, deliverable_policy_dir=deliverable_policy_dir) + rule_sets = [ + RuleSet(rule_id='allowed-base-images', check_id=''), + RuleSet(rule_id='disallow-capabilities', check_id=''), + ] + parameters = [Parameter(id='allowed_baseimages', value='gcr.io/distroless/static:root')] + policy = Policy(rule_sets=rule_sets, parameters=parameters) + + PluginKyverno(config).generate_pvp_policy(policy) + + policy_template_dir = pathlib.Path(policy_template_dir) + deliverable_policy_dir = pathlib.Path(deliverable_policy_dir) + policy_dirs = filter(lambda x: x.is_dir(), deliverable_policy_dir.iterdir()) + assert set(['disallow-capabilities', 'allowed-base-images']) == set(map(lambda x: x.name, policy_dirs)) + + # disallow-capabilities + policy_dir = deliverable_policy_dir / 'disallow-capabilities' + assert set(['disallow-capabilities.yaml']) == set(map(lambda x: x.name, policy_dir.iterdir())) + + policy = load_yaml(policy_dir / 'disallow-capabilities.yaml') + expected = load_yaml(policy_template_dir / 'disallow-capabilities' / 'disallow-capabilities.yaml') + assert expected == policy + + # allowed-base-images + policy_dir = deliverable_policy_dir / 'allowed-base-images' + assert set(['allowed-base-images.yaml', '02-setup-cm.yaml']) == set(map(lambda x: x.name, policy_dir.iterdir())) + + setup_yaml_path = policy_dir / '02-setup-cm.yaml' + setup_yamls = load_yamls(setup_yaml_path) + configmap = next(filter(lambda x: x['kind'] == 'ConfigMap', setup_yamls), None) + assert 'gcr.io/distroless/static:root' == configmap['data']['allowedbaseimages'] + + policy_path = policy_dir / 'allowed-base-images.yaml' + policy = load_yaml(policy_path) + expected = load_yaml(policy_template_dir / 'allowed-base-images' / 'allowed-base-images.yaml') + assert expected == policy diff --git a/plugins_public/tests/plugins/test_ocm.py b/plugins_public/tests/plugins/test_ocm.py new file mode 100644 index 0000000..88f1964 --- /dev/null +++ b/plugins_public/tests/plugins/test_ocm.py @@ -0,0 +1,130 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import os +import pathlib +import shutil +import tempfile +from distutils.util import strtobool + +from c2p.framework.models import Parameter, Policy, RawResult, RuleSet +from plugins_public.plugins.ocm import PluginConfigOCM, PluginOCM +from plugins_public.tests.utils import load_yaml + +TEST_DATA_DIR = os.getenv('TEST_DATA_DIR', 'plugins_public/tests/data/ocm') +OVERWRITE_EXPECTED_DATA = os.getenv('OVERWRITE_EXPECTED_DATA', 'false') +KEEP_TEMP_FILE_AND_DIR = os.getenv('KEEP_TEMP_FILE_AND_DIR', 'false') + + +def test_ocm_pvp_result_to_compliance(): + pds = load_yaml(f'{TEST_DATA_DIR}/placementdecisions.cluster.open-cluster-management.io.yaml') + policies = load_yaml(f'{TEST_DATA_DIR}/policies.policy.open-cluster-management.io.yaml') + policy_sets = load_yaml(f'{TEST_DATA_DIR}/policysets.policy.open-cluster-management.io.yaml') + raw = pds['items'] + policies['items'] + policy_sets['items'] + raw_result = RawResult(data=raw) + pvp_result = PluginOCM().generate_pvp_result(raw_result) + assert len(pvp_result.observations_by_check) == 3 + assert len(pvp_result.observations_by_check[0].subjects) == 2 + + +def test_ocm_compliance_to_policy(): + tmpdir = tempfile.mkdtemp() + policy_template_dir = pathlib.Path(f'{TEST_DATA_DIR}/policy-resources') + deliverable_policy_dir = pathlib.Path(f'{tmpdir}/deliverable-policy') + expected_deliverable_policy_dir = pathlib.Path(f'{TEST_DATA_DIR}/deliverable-policy') + config = PluginConfigOCM( + policy_template_dir=policy_template_dir.as_posix(), + deliverable_policy_dir=deliverable_policy_dir.as_posix(), + namespace='c2p', + paremeters_configmap_name='c2p-parameters', + cluster_selectors={'environment': 'dev'}, + policy_set_name='c2p test', + ) + rule_sets = [ + RuleSet(rule_id='policy-deployment', check_id=''), + RuleSet(rule_id='policy-disallowed-roles', check_id=''), + RuleSet(rule_id='policy-high-scan', check_id=''), + ] + parameters = [Parameter(id='minimum_nginx_deployment_replicas', value='3')] + policy = Policy(rule_sets=rule_sets, parameters=parameters) + + PluginOCM(config).generate_pvp_policy(policy) + + policy_dirs = filter(lambda x: x.is_dir(), deliverable_policy_dir.iterdir()) + assert set(['policy-disallowed-roles', 'policy-deployment', 'policy-high-scan']) == set( + map(lambda x: x.name, policy_dirs) + ) + assert set(['kustomization.yaml', 'parameters.yaml', 'policy-generator.yaml']) == set( + map(lambda x: x.name, filter(lambda x1: x1.is_file(), deliverable_policy_dir.iterdir())) + ) + + expected = load_yaml(expected_deliverable_policy_dir / 'policy-generator.yaml') + actual = load_yaml(deliverable_policy_dir / 'policy-generator.yaml') + assert expected == actual + + expected = load_yaml(expected_deliverable_policy_dir / 'kustomization.yaml') + actual = load_yaml(deliverable_policy_dir / 'kustomization.yaml') + assert expected == actual + + expected = load_yaml(expected_deliverable_policy_dir / 'policy-generator.yaml') + actual = load_yaml(deliverable_policy_dir / 'policy-generator.yaml') + assert expected == actual + + # policy-disallowed-roles + policy_dir = deliverable_policy_dir / 'policy-disallowed-roles' + assert set(['policy-disallowed-roles-sample-role', 'kustomization.yaml', 'policy-generator.yaml']) == set( + map(lambda x: x.name, policy_dir.iterdir()) + ) + assert set(['Role.noname.0.yaml']) == set( + map(lambda x: x.name, (policy_dir / 'policy-disallowed-roles-sample-role').iterdir()) + ) + + # policy-deployment + policy_dir = deliverable_policy_dir / 'policy-deployment' + assert set(['policy-nginx-deployment', 'kustomization.yaml', 'policy-generator.yaml']) == set( + map(lambda x: x.name, policy_dir.iterdir()) + ) + assert set(['Deployment.nginx-deployment.0.yaml']) == set( + map(lambda x: x.name, (policy_dir / 'policy-nginx-deployment').iterdir()) + ) + + # policy-high-scan + policy_dir = deliverable_policy_dir / 'policy-high-scan' + assert set( + [ + 'compliance-high-scan', + 'compliance-suite-high', + 'compliance-suite-high-results', + 'kustomization.yaml', + 'policy-generator.yaml', + ] + ) == set(map(lambda x: x.name, policy_dir.iterdir())) + assert set(['ScanSettingBinding.high.0.yaml']) == set( + map(lambda x: x.name, (policy_dir / 'compliance-high-scan').iterdir()) + ) + assert set(['ComplianceSuite.high.0.yaml']) == set( + map(lambda x: x.name, (policy_dir / 'compliance-suite-high').iterdir()) + ) + assert set(['ComplianceCheckResult.noname.0.yaml']) == set( + map(lambda x: x.name, (policy_dir / 'compliance-suite-high-results').iterdir()) + ) + + if strtobool(OVERWRITE_EXPECTED_DATA): + shutil.rmtree(expected_deliverable_policy_dir) + shutil.copytree(deliverable_policy_dir, expected_deliverable_policy_dir) + + if not strtobool(KEEP_TEMP_FILE_AND_DIR): + shutil.rmtree(tmpdir) diff --git a/plugins_public/tests/utils.py b/plugins_public/tests/utils.py new file mode 100644 index 0000000..4d4f356 --- /dev/null +++ b/plugins_public/tests/utils.py @@ -0,0 +1,32 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import pathlib +from typing import Dict, Union, List + +import yaml + + +def load_yaml(path: Union[str, pathlib.Path]) -> Dict: + if isinstance(path, str): + path = pathlib.Path(path) + return yaml.safe_load(path.open('r')) + + +def load_yamls(path: Union[str, pathlib.Path]) -> List[Dict]: + if isinstance(path, str): + path = pathlib.Path(path) + return yaml.safe_load_all(path.open('r')) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..f883c03 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,95 @@ +[build-system] +requires = ["setuptools", "setuptools-git-versioning"] +build-backend = "setuptools.build_meta" + +[tool.setuptools-git-versioning] +enabled = true +count_commits_from_version_file = true +dev_template = "{tag}.post{ccount}+git.{sha}.dirty" +dirty_template = "{tag}.post{ccount}+git.{sha}.dirty" + +[tool.setuptools] +package-dir = { "c2p" = "c2p" } + +[tool.setuptools.packages.find] +include = ["c2p*"] + +[project] +dynamic = ["version"] +name = "compliance-to-policy" +authors = [{ name = "Takumi Yanagawa", email = "yana1205dev@gmail.com" }] +description = "Tools to bridge Compliance and Policy" +readme = "README.md" +license = { file = "LICENSE" } +requires-python = ">=3.9" +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", +] +dependencies = [ + "compliance-trestle==2.2.1", + "PyGithub==1.58.0", + "jq==1.6.0", + "pluggy", +] + +[project.scripts] +c2p = "c2p.cli:run" + +[project.optional-dependencies] +dev = [ + "build>=1.0.3", + "pyclean", + "pytest>=8.0.0", + "pre-commit>=2.4.0", + "pep8-naming", + "types-PyYAML", + "types-setuptools", + ## Docs website + "mkdocs", + "mkdocs-redirects", + "mkdocstrings-python", + ## Constrain system + "black", + "isort", + "pylint", + ## Security tools + "detect-secrets@git+https://github.com/ibm/detect-secrets.git@master#egg=detect-secrets" +] + +[project.urls] +Homepage = "https://github.com/oscal-compass/compliance-to-policy" +Issues = "https://github.com/oscal-compass/compliance-to-policy/issues" + +[tool.pytest.ini_options] +log_cli = true +log_cli_level = "INFO" +log_cli_format = "%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)" +log_cli_date_format = "%Y-%m-%d %H:%M:%S" +minversion = "6.0" +addopts = "-ra -q" +testpaths = ["tests", "plugins_public/tests"] +pythonpath = ["c2p", "plugins_public/tests"] + +[tool.isort] +profile = "black" +extend_skip_glob = "go" + +[tool.black] +line-length = 120 +skip-string-normalization = true +extend-exclude = "go" + +[tool.pylint.master] +ignore = "oscal" +extension-pkg-whitelist = "pydantic" + +[tool.pylint.messages_control] +disable = ["W1203", "W1201"] + +[tool.pylint.format] +max-line-length = 120 diff --git a/samples_public/__init__.py b/samples_public/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/samples_public/kyverno/compliance_to_policy.py b/samples_public/kyverno/compliance_to_policy.py new file mode 100644 index 0000000..4a42e95 --- /dev/null +++ b/samples_public/kyverno/compliance_to_policy.py @@ -0,0 +1,56 @@ +import argparse +import os +import pathlib +import sys +import tempfile + +from c2p.framework.c2p import C2P +from c2p.framework.models.c2p_config import C2PConfig, ComplianceOscal + +sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) +from plugins_public.plugins.kyverno import PluginConfigKyverno, PluginKyverno + +TEST_DATA_DIR = 'plugins_public/tests/data/kyverno' + +parser = argparse.ArgumentParser() +parser.add_argument( + '-o', '--out', type=str, help='Path to output directory (default: system temporary directory)', required=False +) +args = parser.parse_args() + +tmpdirname = args.out if args.out != None else tempfile.mkdtemp() + +# Setup c2p_config +c2p_config = C2PConfig() +c2p_config.compliance = ComplianceOscal() +c2p_config.compliance.component_definition = f'{TEST_DATA_DIR}/component-definition.json' +c2p_config.pvp_name = 'Kyverno' +c2p_config.result_title = 'Kyverno Assessment Results' +c2p_config.result_description = 'OSCAL Assessment Results from Kyverno' + +# Construct C2P +c2p = C2P(c2p_config) + +# Transform OSCAL (Compliance) to Policy +policy_template_dir = f'{TEST_DATA_DIR}/policy-resources' +config = PluginConfigKyverno(policy_template_dir=policy_template_dir, deliverable_policy_dir=tmpdirname) +PluginKyverno(config).generate_pvp_policy(c2p.get_policy()) + + +def tree(path: pathlib.Path, texts: list[str] = [], depth=0) -> list[str]: + prefix = '' + if depth > 0: + for _ in range(depth): + prefix = prefix + '-' + prefix = prefix + ' ' + for item in path.iterdir(): + texts.append(f'{prefix}{item.name}') + if item.is_dir(): + tree(item, texts, depth=depth + 1) + return texts + + +print('') +print(f'tree {tmpdirname}') +for text in tree(pathlib.Path(tmpdirname)): + print(text) diff --git a/samples_public/kyverno/result_to_compliance.py b/samples_public/kyverno/result_to_compliance.py new file mode 100644 index 0000000..6b145b3 --- /dev/null +++ b/samples_public/kyverno/result_to_compliance.py @@ -0,0 +1,58 @@ +import argparse +import os +import pathlib +import sys + +import yaml + +from c2p.framework.c2p import C2P +from c2p.framework.models import RawResult +from c2p.framework.models.c2p_config import C2PConfig, ComplianceOscal +from c2p.framework.models.raw_result import RawResult + +sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) +from plugins_public.plugins.kyverno import PluginKyverno + +TEST_DATA_DIR = 'plugins_public/tests/data/kyverno' + +parser = argparse.ArgumentParser() +parser.add_argument( + '-polr', + '--policy-report', + type=str, + default=f'{TEST_DATA_DIR}/policyreports.wgpolicyk8s.io.yaml', + help='Path to policy report', + required=False, +) +parser.add_argument( + '-cpolr', + '--cluster-policy-report', + type=str, + default=f'{TEST_DATA_DIR}/clusterpolicyreports.wgpolicyk8s.io.yaml', + help='Path to cluster policy report', + required=False, +) +args = parser.parse_args() + +# Setup c2p_config +c2p_config = C2PConfig() +c2p_config.compliance = ComplianceOscal() +c2p_config.compliance.component_definition = f'{TEST_DATA_DIR}/component-definition.json' +c2p_config.pvp_name = 'Kyverno' +c2p_config.result_title = 'Kyverno Assessment Results' +c2p_config.result_description = 'OSCAL Assessment Results from Kyverno' + +# Construct C2P +c2p = C2P(c2p_config) + +# Create pvp_result from raw result via plugin +cpolr = yaml.safe_load(pathlib.Path(args.cluster_policy_report).open('r')) +polr = yaml.safe_load(pathlib.Path(args.policy_report).open('r')) +pvp_raw_result = RawResult(data=cpolr['items'] + polr['items']) +pvp_result = PluginKyverno().generate_pvp_result(pvp_raw_result) + +# Transform pvp_result to OSCAL Assessment Result +c2p.set_pvp_result(pvp_result) +oscal_assessment_results = c2p.result_to_oscal() + +print(oscal_assessment_results.oscal_serialize_json(pretty=True)) diff --git a/samples_public/ocm/compliance_to_policy.py b/samples_public/ocm/compliance_to_policy.py new file mode 100644 index 0000000..88684fa --- /dev/null +++ b/samples_public/ocm/compliance_to_policy.py @@ -0,0 +1,61 @@ +import argparse +import os +import pathlib +import sys +import tempfile + +from c2p.framework.c2p import C2P +from c2p.framework.models.c2p_config import C2PConfig, ComplianceOscal + +sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) +from plugins_public.plugins.ocm import PluginOCM, PluginConfigOCM + +TEST_DATA_DIR = 'plugins_public/tests/data/ocm' + +parser = argparse.ArgumentParser() +parser.add_argument( + '-o', '--out', type=str, help='Path to output directory (default: system temporary directory)', required=False +) +args = parser.parse_args() + +tmpdirname = args.out if args.out != None else tempfile.mkdtemp() + +# Setup c2p_config +c2p_config = C2PConfig() +c2p_config.compliance = ComplianceOscal() +c2p_config.compliance.component_definition = 'plugins_public/tests/data/ocm/component-definition.json' +c2p_config.pvp_name = 'OCM' + +# Construct C2P +c2p = C2P(c2p_config) + +# Transform OSCAL (Compliance) to Policy +policy_template_dir = f'{TEST_DATA_DIR}/policy-resources' +config = PluginConfigOCM( + policy_template_dir=policy_template_dir, + deliverable_policy_dir=tmpdirname, + namespace='c2p', + paremeters_configmap_name='c2p-parameters', + cluster_selectors={'environment': 'dev'}, + policy_set_name='c2p test', +) +PluginOCM(config).generate_pvp_policy(c2p.get_policy()) + + +def tree(path: pathlib.Path, texts: list[str] = [], depth=0) -> list[str]: + prefix = '' + if depth > 0: + for _ in range(depth - 1): + prefix = prefix + ' ' + prefix = prefix + '- ' + for item in path.iterdir(): + texts.append(f'{prefix}{item.name}') + if item.is_dir(): + tree(item, texts, depth=depth + 1) + return texts + + +print('') +print(f'tree {tmpdirname}') +for text in tree(pathlib.Path(tmpdirname)): + print(text) diff --git a/samples_public/ocm/result_to_compliance.py b/samples_public/ocm/result_to_compliance.py new file mode 100644 index 0000000..8b83e27 --- /dev/null +++ b/samples_public/ocm/result_to_compliance.py @@ -0,0 +1,45 @@ +import argparse +import os +import pathlib +import sys + +import yaml + +from c2p.framework.c2p import C2P +from c2p.framework.models.c2p_config import C2PConfig, ComplianceOscal +from c2p.framework.models.raw_result import RawResult + +sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) +from plugins_public.plugins.ocm import PluginOCM + +TEST_DATA_DIR = 'plugins_public/tests/data/ocm' + +parser = argparse.ArgumentParser() +parser.add_argument( + '-p', + '--policy-result', + type=str, + default=f'{TEST_DATA_DIR}/policies.policy.open-cluster-management.io.yaml', + help='Path to a yaml file in which policies.policy.open-cluster-management.io resources are dumped.', + required=False, +) +args = parser.parse_args() + +# Setup c2p_config +c2p_config = C2PConfig() +c2p_config.compliance = ComplianceOscal() +c2p_config.compliance.component_definition = 'plugins_public/tests/data/ocm/component-definition.json' +c2p_config.pvp_name = 'OCM' +c2p_config.result_title = 'OCM Assessment Results' +c2p_config.result_description = 'OSCAL Assessment Results from OCM' + +# Create pvp_result from raw result via plugin +policies = yaml.safe_load(pathlib.Path(args.policy_result).open('r')) +pvp_raw_result = RawResult(data=policies['items']) +c2p_config.pvp_result = PluginOCM().generate_pvp_result(pvp_raw_result) + +# Transform pvp_result to OSCAL Assessment Result +c2p = C2P(c2p_config) +oscal_assessment_results = c2p.result_to_oscal() + +print(oscal_assessment_results.oscal_serialize_json(pretty=True)) diff --git a/scripts/shell/license.sh b/scripts/shell/license.sh new file mode 100755 index 0000000..7f16ff9 --- /dev/null +++ b/scripts/shell/license.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +license_file=./scripts/shell/license.txt + +directory=$1 + +function add_license() { + find $directory -name '*.py' | while read name + do + cat $license_file > /tmp/newfile + cat $name >> /tmp/newfile + cp /tmp/newfile $name + done +} + +add_license $directory \ No newline at end of file diff --git a/scripts/shell/license.txt b/scripts/shell/license.txt new file mode 100644 index 0000000..0e18e08 --- /dev/null +++ b/scripts/shell/license.txt @@ -0,0 +1,16 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/tests/c2p/__init__.py b/tests/c2p/__init__.py new file mode 100644 index 0000000..9d5e84d --- /dev/null +++ b/tests/c2p/__init__.py @@ -0,0 +1,32 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import os +import pathlib +from distutils.util import strtobool + +from c2p.common import logging + +logger = logging.getLogger(__name__) + + +def write_test_result_to_file(output_path: pathlib.Path, data: str): + enabled = os.getenv('ENABLE_WRITE_TEST_RESULT_TO_FILE', 'false') + if strtobool(enabled): + try: + output_path.write_text(data) + except Exception as e: + logger.error(f'Failed to write test results to {output_path.as_posix()}\n {str(e)}') diff --git a/tests/c2p/framework/__init__.py b/tests/c2p/framework/__init__.py new file mode 100644 index 0000000..bd26775 --- /dev/null +++ b/tests/c2p/framework/__init__.py @@ -0,0 +1,15 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. diff --git a/tests/c2p/framework/test_c2p.py b/tests/c2p/framework/test_c2p.py new file mode 100644 index 0000000..9766ded --- /dev/null +++ b/tests/c2p/framework/test_c2p.py @@ -0,0 +1,94 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +import json +import pathlib +from typing import Any, Dict, Tuple + +from pydantic import BaseModel +from trestle.oscal.assessment_results import AssessmentResults + +from c2p.framework.c2p import C2P +from c2p.framework.models.c2p_config import C2PConfig, ComplianceOscal +from c2p.framework.models.pvp_result import PVPResult +from tests.c2p import write_test_result_to_file + +COMPONENT_DEFINITION_TEST_DATA = pathlib.Path('tests/data/framework/c2p/component-definition.json') +PVP_RESULT_TEST_DATA = pathlib.Path('tests/data/framework/c2p/pvp-result.json') +EXPECTED_ASSESSMENT_RESULTS_DATA = pathlib.Path('tests/data/framework/c2p/assessment-results.json') +OUTPUT_PATH = EXPECTED_ASSESSMENT_RESULTS_DATA + + +def extract_dicts(d: Dict[str, Any], excludes=[]) -> Tuple[Dict[str, Any], Dict[str, Any]]: + primitives = [] + nested = [] + for key, value in d.items(): + if key in excludes: + continue + if isinstance(value, list) or isinstance(value, dict): + nested.append((key, value)) + else: + primitives.append((key, value)) + + return dict(primitives), dict(nested) + + +def assert_pydantic_object(actual: BaseModel, expect: BaseModel, exludes=[]): + actual, _ = extract_dicts(actual.dict(), excludes=exludes) + expect, _ = extract_dicts(expect.dict(), excludes=exludes) + assert actual == expect + + +def test_result_to_oscal(): + c2p_config = C2PConfig() + c2p_config.compliance = ComplianceOscal() + c2p_config.compliance.component_definition = COMPONENT_DEFINITION_TEST_DATA.as_posix() + c2p_config.pvp_name = 'OCM' + c2p_config.result_title = 'TEST Assessment Results' + c2p_config.result_description = 'OSCAL Assessment Results from TEST' + + pvp_result = json.load(PVP_RESULT_TEST_DATA.open('r')) + c2p_config.pvp_result = PVPResult.parse_obj(pvp_result) + + c2p = C2P(c2p_config) + assessment_results = c2p.result_to_oscal() + expect = AssessmentResults.parse_file(EXPECTED_ASSESSMENT_RESULTS_DATA) + + assert_pydantic_object(assessment_results.metadata, expect.metadata, exludes=['last_modified']) + assert_pydantic_object(assessment_results.import_ap, expect.import_ap) + actual_result = assessment_results.results[0] + expect_result = expect.results[0] + assert_pydantic_object(actual_result, expect_result, exludes=['uuid', 'start']) + actual_reviewed_controls = actual_result.reviewed_controls + expect_reviewed_controls = expect_result.reviewed_controls + assert expect_reviewed_controls == actual_reviewed_controls + + actual_observations = actual_result.observations + expect_observations = expect_result.observations + + assert len(actual_observations) == len(expect_observations) + for expect_o in expect_observations: + actual_o = next(filter(lambda x: x.title == expect_o.title, actual_observations), None) + assert actual_o != None + assert expect_o.props == actual_o.props + for expect_s in expect_o.subjects: + actual_s = next(filter(lambda x: x.title == expect_s.title, actual_o.subjects), None) + assert actual_s != None + assert expect_s.type == actual_s.type + assert list(filter(lambda x: x.name != 'evaluated-on', expect_s.props)) == list( + filter(lambda x: x.name != 'evaluated-on', actual_s.props) + ) + write_test_result_to_file(OUTPUT_PATH, assessment_results.json(exclude_none=True, indent=2)) diff --git a/tests/c2p/test_cli.py b/tests/c2p/test_cli.py new file mode 100644 index 0000000..950b311 --- /dev/null +++ b/tests/c2p/test_cli.py @@ -0,0 +1,47 @@ +# -*- mode:python; coding:utf-8 -*- + +# Copyright 2024 IBM Corporation +# +# 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. + +"""Tests for cli module.""" + +import sys + +import pytest +from _pytest.monkeypatch import MonkeyPatch + +from c2p import cli +from c2p.common import logging + +logger = logging.getLogger(__name__) + + +def test_run(monkeypatch: MonkeyPatch) -> None: + """Test cli call.""" + testargs = ['c2p'] + monkeypatch.setattr(sys, 'argv', testargs) + with pytest.raises(SystemExit) as pytest_wrapped_e: + cli.run() + assert pytest_wrapped_e.type == SystemExit + assert pytest_wrapped_e.value.code > 0 + + +def test_version(monkeypatch: MonkeyPatch) -> None: + """Test cli call.""" + testargs = ['c2p', 'version'] + monkeypatch.setattr(sys, 'argv', testargs) + with pytest.raises(SystemExit) as pytest_wrapped_e: + cli.run() + assert pytest_wrapped_e.type == SystemExit + assert pytest_wrapped_e.value.code == 0 diff --git a/tests/data/framework/c2p/assessment-results.json b/tests/data/framework/c2p/assessment-results.json new file mode 100644 index 0000000..bb6dac2 --- /dev/null +++ b/tests/data/framework/c2p/assessment-results.json @@ -0,0 +1,97 @@ +{ + "uuid": "490aa57a-b508-46f4-9552-1231d9468805", + "metadata": { + "title": "TEST Assessment Results", + "last_modified": "2024-03-22T08:28:11.000+00:00", + "version": "2.2.1", + "oscal_version": "1.0.4" + }, + "import_ap": { + "href": "https://not-available-for-now" + }, + "results": [ + { + "uuid": "2dc21238-a61e-48b4-9794-9d12f999c73c", + "title": "TEST Assessment Results", + "description": "OSCAL Assessment Results from TEST", + "start": "2024-03-22T08:28:11.000+00:00", + "reviewed_controls": { + "control_selections": [ + { + "include_controls": [ + { + "control_id": "cm-6", + "statement_ids": [] + } + ] + } + ] + }, + "observations": [ + { + "uuid": "c282e204-0f8f-4311-9c37-8dfe56464993", + "title": "policy-high-scan", + "description": "policy-high-scan", + "props": [ + { + "name": "assessment-rule-id", + "value": "test_configuration_check" + } + ], + "methods": [ + "AUTOMATED" + ], + "subjects": [ + { + "subject_uuid": "58ecbe30-9416-4804-a1aa-a3553fb21099", + "type": "cluster", + "title": "Cluster \"cluster1\"", + "props": [ + { + "name": "resource-id", + "value": "cluster1" + }, + { + "name": "result", + "value": "failure" + }, + { + "name": "evaluated-on", + "value": "2023-07-05T23:53:37+00:00" + }, + { + "name": "reason", + "value": "[c2p.policy-high-scan.176f1ddc441457e5] NonCompliant; violation - couldn't find mapping resource with kind ComplianceCheckResult, please check if you have CRD deployed" + } + ] + }, + { + "subject_uuid": "a4f602d7-acf1-428d-8f03-79855ea6aafb", + "type": "cluster", + "title": "Cluster \"cluster2\"", + "props": [ + { + "name": "resource-id", + "value": "cluster2" + }, + { + "name": "result", + "value": "failure" + }, + { + "name": "evaluated-on", + "value": "2023-07-05T23:51:56+00:00" + }, + { + "name": "reason", + "value": "[c2p.policy-high-scan.176f1dc4e29e1221] NonCompliant; violation - couldn't find mapping resource with kind ComplianceCheckResult, please check if you have CRD deployed" + } + ] + } + ], + "collected": "2024-03-22T08:17:46.000+00:00" + } + ] + } + ] +} \ No newline at end of file diff --git a/tests/data/framework/c2p/component-definition.json b/tests/data/framework/c2p/component-definition.json new file mode 100644 index 0000000..06179f3 --- /dev/null +++ b/tests/data/framework/c2p/component-definition.json @@ -0,0 +1,107 @@ +{ + "component-definition": { + "uuid": "fba79b7a-9a3d-4326-a657-71562985dbfc", + "metadata": { + "title": "Unit test based on OCM", + "last-modified": "2024-03-22T08:00:02+00:00", + "version": "1.0", + "oscal-version": "1.0.4" + }, + "components": [ + { + "uuid": "d69bf3b4-8eba-4543-8489-55dc8ed86e64", + "type": "Service", + "title": "Managed Kubernetes", + "description": "Managed Kubernetes cluster", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "test_configuration_check", + "remarks": "rule_set_0" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure deployment configuration is securely set up", + "remarks": "rule_set_0" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_0" + } + ], + "control-implementations": [ + { + "uuid": "57135f73-8f2b-43ea-9f9c-8ef3b3a62400", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "implemented-requirements": [ + { + "uuid": "c8eb7deb-f73d-44d6-96cc-e4e1497b10b7", + "control-id": "cm-6", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "test_configuration_check" + } + ] + } + ] + } + ] + }, + { + "uuid": "7e0e2270-0978-48d7-a413-691b3699c6dc", + "type": "Validation", + "title": "OCM", + "description": "OCM", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "test_configuration_check", + "remarks": "rule_set_1" + }, + { + "name": "Rule_Description", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "Ensure deployment configuration is securely set up", + "remarks": "rule_set_1" + }, + { + "name": "Check_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "policy-high-scan", + "remarks": "rule_set_1" + } + ], + "control-implementations": [ + { + "uuid": "20837a2b-db9f-4222-8cdc-55a4573be1c7", + "source": "https://github.com/usnistgov/oscal-content/blob/main/nist.gov/SP800-53/rev5/json/NIST_SP-800-53_rev5_HIGH-baseline_profile.json", + "description": "NIST Special Publication 800-53 Revision 5 HIGH IMPACT BASELINE", + "implemented-requirements": [ + { + "uuid": "ca0eb376-9ca9-4d20-988b-45f94c42aefd", + "control-id": "na", + "description": "", + "props": [ + { + "name": "Rule_Id", + "ns": "http://ibm.github.io/compliance-trestle/schemas/oscal/cd/ibmcloud", + "value": "test_configuration_check" + } + ] + } + ] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/tests/data/framework/c2p/pvp-result.json b/tests/data/framework/c2p/pvp-result.json new file mode 100644 index 0000000..684ef60 --- /dev/null +++ b/tests/data/framework/c2p/pvp-result.json @@ -0,0 +1,79 @@ +{ + "observations_by_check": [ + { + "check_id": "policy-deployment", + "methods": [ + "AUTOMATED" + ], + "subjects": [ + { + "title": "Cluster \"cluster1\"", + "type": "cluster", + "resource_id": "cluster1", + "result": "failure", + "evaluated_on": "2023-07-05T23:53:37.000+00:00", + "reason": "[c2p.policy-deployment.176f1ddc5591cb1c] NonCompliant; violation - deployments not found: [nginx-deployment] in namespace cluster1 missing; [nginx-deployment] in namespace kube-node-lease missing; [nginx-deployment] in namespace kube-public missing; [nginx-deployment] in namespace local-path-storage missing" + }, + { + "title": "Cluster \"cluster2\"", + "type": "cluster", + "resource_id": "cluster2", + "result": "failure", + "evaluated_on": "2023-07-05T23:51:56.000+00:00", + "reason": "[c2p.policy-deployment.176f1dc4e7de17cb] NonCompliant; violation - deployments not found: [nginx-deployment] in namespace cluster2 missing; [nginx-deployment] in namespace default missing; [nginx-deployment] in namespace kube-node-lease missing; [nginx-deployment] in namespace kube-public missing; [nginx-deployment] in namespace local-path-storage missing" + } + ], + "collected": "2024-03-22T08:17:46.000+00:00" + }, + { + "check_id": "policy-disallowed-roles", + "methods": [ + "AUTOMATED" + ], + "subjects": [ + { + "title": "Cluster \"cluster1\"", + "type": "cluster", + "resource_id": "cluster1", + "result": "pass", + "evaluated_on": "2023-07-05T23:52:34.000+00:00", + "reason": "[c2p.policy-disallowed-roles.176f1dcdc4c8d17e] Compliant; notification - roles in namespace cluster1; in namespace default; in namespace kube-node-lease; in namespace kube-public; in namespace local-path-storage missing as expected, therefore this Object template is compliant" + }, + { + "title": "Cluster \"cluster2\"", + "type": "cluster", + "resource_id": "cluster2", + "result": "pass", + "evaluated_on": "2023-07-05T23:51:50.000+00:00", + "reason": "[c2p.policy-disallowed-roles.176f1dc36e36b7b2] Compliant; notification - roles in namespace cluster2; in namespace default; in namespace kube-node-lease; in namespace kube-public; in namespace local-path-storage missing as expected, therefore this Object template is compliant" + } + ], + "collected": "2024-03-22T08:17:46.000+00:00" + }, + { + "check_id": "policy-high-scan", + "methods": [ + "AUTOMATED" + ], + "subjects": [ + { + "title": "Cluster \"cluster1\"", + "type": "cluster", + "resource_id": "cluster1", + "result": "failure", + "evaluated_on": "2023-07-05T23:53:37.000+00:00", + "reason": "[c2p.policy-high-scan.176f1ddc441457e5] NonCompliant; violation - couldn't find mapping resource with kind ComplianceCheckResult, please check if you have CRD deployed" + }, + { + "title": "Cluster \"cluster2\"", + "type": "cluster", + "resource_id": "cluster2", + "result": "failure", + "evaluated_on": "2023-07-05T23:51:56.000+00:00", + "reason": "[c2p.policy-high-scan.176f1dc4e29e1221] NonCompliant; violation - couldn't find mapping resource with kind ComplianceCheckResult, please check if you have CRD deployed" + } + ], + "collected": "2024-03-22T08:17:46.000+00:00" + } + ] +} \ No newline at end of file