├── .cargo └── audit.toml ├── .chglog ├── CHANGELOG.tpl.md └── config.yml ├── .clomonitor.yml ├── .github ├── release-drafter.yml └── workflows │ ├── build.yml │ ├── ci.yml │ ├── fossa.yml │ ├── openssf.yml │ ├── release-drafter.yml │ ├── release.yml │ ├── security-audit-cron.yml │ ├── security-audit-reactive.yml │ └── update-rust-toolchain.yaml ├── .gitignore ├── .taplo.toml ├── CODEOWNERS ├── CONTRIBUTING.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── SECURITY-INSIGHTS.yml ├── cli-docs.md ├── config.toml ├── coverage ├── integration-tests │ └── .gitignore └── unit-tests │ └── .gitignore ├── renovate.json ├── rust-toolchain.toml ├── scripts ├── kubewarden-load-policies.sh └── kubewarden-save-policies.sh ├── src ├── annotate.rs ├── backend.rs ├── bench.rs ├── callback_handler │ ├── mod.rs │ └── proxy.rs ├── cli.rs ├── completions.rs ├── info.rs ├── inspect.rs ├── load.rs ├── main.rs ├── policies.rs ├── pull.rs ├── push.rs ├── rm.rs ├── run.rs ├── save.rs ├── scaffold.rs ├── scaffold │ ├── admission_request.rs │ ├── artifacthub.rs │ ├── kubewarden_crds.rs │ ├── manifest.rs │ ├── vap.rs │ └── verification_config.rs ├── utils.rs └── verify.rs ├── tests ├── airgap.rs ├── common │ └── mod.rs ├── data │ ├── airgap │ │ └── policies.txt │ ├── artifacthub │ │ └── metadata.yml │ ├── context-aware-policy-request-pod-creation-all-labels.json │ ├── host-capabilities-sessions │ │ ├── context-aware-demo-namespace-found.yml │ │ ├── context-aware-demo-namespace-not-found.yml │ │ ├── context-aware-unique-ingress-duplicate.yml │ │ └── context-aware-unique-ingress-no-duplicate.yml │ ├── ingress.json │ ├── privileged-pod-admission-review.json │ ├── privileged-pod.json │ ├── raw.json │ ├── rego-annotate │ │ ├── metadata-correct.yml │ │ ├── metadata-wrong.yml │ │ └── no-default-namespace-rego.wasm │ ├── sigstore │ │ ├── README.md │ │ ├── cosign1.key │ │ ├── cosign1.pub │ │ ├── cosign2.key │ │ ├── cosign2.pub │ │ ├── cosign3.key │ │ ├── cosign3.pub │ │ ├── verification-config-keyless.yml │ │ └── verification-config.yml │ ├── unprivileged-pod-admission-review.json │ ├── unprivileged-pod.json │ └── vap │ │ ├── vap-binding.yml │ │ ├── vap-with-variables.yml │ │ └── vap-without-variables.yml ├── e2e.rs └── secure_supply_chain_e2e.rs └── updatecli ├── DEVELOP.md ├── updatecli.d └── update-rust-toolchain.yaml └── values.yaml /.cargo/audit.toml: -------------------------------------------------------------------------------- 1 | [advisories] 2 | ignore = [ 3 | "RUSTSEC-2020-0071", # `time` localtime_r segfault -- https://rustsec.org/advisories/RUSTSEC-2020-0071 4 | # Ignored because there are not known workarounds or dependency version bump 5 | # at this time. The call to localtime_r is not protected by any lock and can 6 | # cause unsoundness. Read the previous link for more information. 7 | "RUSTSEC-2020-0168", # This is about "mach" being unmaintained. 8 | # This is a transitive dependency of wasmtime. This is 9 | # being tracked upstream via https://github.com/bytecodealliance/wasmtime/issues/6000 10 | # This is a transitive depependency of sigstore 11 | "RUSTSEC-2023-0071", # "Classic" RSA timing sidechannel attack from non-constant-time implementation. 12 | # Okay for local use. 13 | # https://rustsec.org/advisories/RUSTSEC-2023-0071.html 14 | "RUSTSEC-2023-0081", # This is about `safemem` being unmaintained. 15 | # This is a transitive dependency of syntect. This bug is tracked upstream inside of 16 | # https://github.com/trishume/syntect/issues/521 17 | "RUSTSEC-2024-0370", # This is a warning about `proc-macro-errors` being unmaintained. It's a transitive dependency of `sigstore` and `oci-spec`. 18 | "RUSTSEC-2023-0055", # This is a warning about `lexical` having multiple soundness issues. It's a transitive dependency of `sigstore`. 19 | ] 20 | -------------------------------------------------------------------------------- /.chglog/CHANGELOG.tpl.md: -------------------------------------------------------------------------------- 1 | {{ if .Versions -}} 2 | 3 | ## [Unreleased] 4 | 5 | {{ if .Unreleased.CommitGroups -}} 6 | {{ range .Unreleased.CommitGroups -}} 7 | ### {{ .Title }} 8 | {{ range .Commits -}} 9 | - {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} 10 | {{ end }} 11 | {{ end -}} 12 | {{ end -}} 13 | {{ end -}} 14 | 15 | {{ range .Versions }} 16 | 17 | ## {{ if .Tag.Previous }}[{{ .Tag.Name }}]{{ else }}{{ .Tag.Name }}{{ end }} - {{ datetime "2006-01-02" .Tag.Date }} 18 | {{ range .CommitGroups -}} 19 | ### {{ .Title }} 20 | {{ range .Commits -}} 21 | - {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} 22 | {{ end }} 23 | {{ end -}} 24 | 25 | {{- if .RevertCommits -}} 26 | ### Reverts 27 | {{ range .RevertCommits -}} 28 | - {{ .Revert.Header }} 29 | {{ end }} 30 | {{ end -}} 31 | 32 | {{- if .MergeCommits -}} 33 | ### Pull Requests 34 | {{ range .MergeCommits -}} 35 | - {{ .Header }} 36 | {{ end }} 37 | {{ end -}} 38 | 39 | {{- if .NoteGroups -}} 40 | {{ range .NoteGroups -}} 41 | ### {{ .Title }} 42 | {{ range .Notes }} 43 | {{ .Body }} 44 | {{ end }} 45 | {{ end -}} 46 | {{ end -}} 47 | {{ end -}} 48 | 49 | {{- if .Versions }} 50 | [Unreleased]: {{ .Info.RepositoryURL }}/compare/{{ $latest := index .Versions 0 }}{{ $latest.Tag.Name }}...HEAD 51 | {{ range .Versions -}} 52 | {{ if .Tag.Previous -}} 53 | [{{ .Tag.Name }}]: {{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }} 54 | {{ end -}} 55 | {{ end -}} 56 | {{ end -}} -------------------------------------------------------------------------------- /.chglog/config.yml: -------------------------------------------------------------------------------- 1 | style: github 2 | template: CHANGELOG.tpl.md 3 | info: 4 | title: CHANGELOG 5 | repository_url: https://github.com/kubewarden/kwctl 6 | options: 7 | commits: 8 | filters: 9 | Type: 10 | - feat 11 | - fix 12 | - perf 13 | - refactor 14 | commit_groups: 15 | title_maps: 16 | feat: Features 17 | fix: Bug Fixes 18 | perf: Performance Improvements 19 | refactor: Code Refactoring 20 | header: 21 | pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$" 22 | pattern_maps: 23 | - Type 24 | - Scope 25 | - Subject 26 | notes: 27 | keywords: 28 | - BREAKING CHANGE 29 | -------------------------------------------------------------------------------- /.clomonitor.yml: -------------------------------------------------------------------------------- 1 | # CLOMonitor metadata file 2 | # This file must be located at the root of the repository 3 | 4 | # Checks exemptions 5 | exemptions: 6 | - check: artifacthub_badge # Check identifier (see https://github.com/cncf/clomonitor/blob/main/docs/checks.md#exemptions) 7 | reason: "kwctl is a cli binary, can't be published in ArtifactHub" # Justification of this exemption (mandatory, it will be displayed on the UI) 8 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | categories: 2 | - title: '⚠️ Breaking changes' 3 | labels: 4 | - 'kind/major' 5 | - 'kind/breaking-change' 6 | - title: '🚀 Features' 7 | labels: 8 | - 'kind/enhancement' 9 | - 'kind/feature' 10 | - title: '🐛 Bug Fixes' 11 | labels: 12 | - 'kind/bug' 13 | - title: '🧰 Maintenance' 14 | labels: 15 | - 'kind/chore' 16 | - 'area/dependencies' 17 | 18 | exclude-labels: 19 | - duplicate 20 | - invalid 21 | - later 22 | - wontfix 23 | - kind/question 24 | - release/skip-changelog 25 | 26 | change-template: '- $TITLE (#$NUMBER)' 27 | change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks. 28 | name-template: 'v$RESOLVED_VERSION' 29 | template: | 30 | $CHANGES 31 | 32 | autolabeler: 33 | # Tag any PR with "!" in the subject as major update. In other words, breaking change 34 | - label: 'kind/breaking-change' 35 | title: '/.*!:.*/' 36 | - label: 'area/dependencies' 37 | title: 'chore(deps)' 38 | - label: 'area/dependencies' 39 | title: 'fix(deps)' 40 | - label: 'area/dependencies' 41 | title: 'build(deps)' 42 | - label: 'kind/feature' 43 | title: 'feat' 44 | - label: 'kind/bug' 45 | title: 'fix' 46 | - label: 'kind/chore' 47 | title: 'chore' 48 | 49 | version-resolver: 50 | major: 51 | labels: 52 | - 'kind/major' 53 | - 'kind/breaking-change' 54 | minor: 55 | labels: 56 | - 'kind/minor' 57 | - 'kind/feature' 58 | - 'kind/enhancement' 59 | patch: 60 | labels: 61 | - 'kind/patch' 62 | - 'kind/fix' 63 | - 'kind/bug' 64 | - 'kind/chore' 65 | - 'area/dependencies' 66 | default: patch 67 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: kwctl build 2 | on: 3 | workflow_call: 4 | push: 5 | branches: 6 | - "main" 7 | - "feat-**" 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build-linux-binaries: 14 | name: Build linux binaries 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | targetarch: 19 | - aarch64 20 | - x86_64 21 | permissions: 22 | id-token: write 23 | attestations: write 24 | steps: 25 | - uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2 26 | 27 | - name: checkout code 28 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 29 | 30 | - name: Install cross-rs 31 | run: | 32 | set -e 33 | 34 | echo "$CROSS_CHECKSUM cross-x86_64-unknown-linux-musl.tar.gz" > checksum 35 | curl -L -O https://github.com/cross-rs/cross/releases/download/$CROSS_VERSION/cross-x86_64-unknown-linux-musl.tar.gz 36 | sha512sum -c checksum 37 | tar -xvf cross-x86_64-unknown-linux-musl.tar.gz 38 | env: 39 | CROSS_CHECKSUM: "70b31b207e981aa31925a7519a0ad125c5d97b84afe0e8e81b0664df5c3a7978558d83f9fcd0c36dc2176fc2a4d0caed67f8cf9fd689f9935f84449cd4922ceb" 40 | CROSS_VERSION: "v0.2.5" 41 | 42 | - name: Build kwctl 43 | shell: bash 44 | run: | 45 | ./cross build --release --target ${{matrix.targetarch}}-unknown-linux-musl 46 | 47 | - run: mv target/${{ matrix.targetarch }}-unknown-linux-musl/release/kwctl kwctl-linux-${{ matrix.targetarch }} 48 | 49 | - name: Smoke test build 50 | if: matrix.targetarch == 'x86_64' 51 | run: ./kwctl-linux-x86_64 --help 52 | 53 | - name: Generate attestations 54 | uses: actions/attest-build-provenance@db473fddc028af60658334401dc6fa3ffd8669fd # v2.3.0 55 | id: attestations 56 | with: 57 | subject-path: kwctl-linux-${{ matrix.targetarch }} 58 | 59 | - name: Sign kwctl 60 | run: | 61 | cosign sign-blob --yes kwctl-linux-${{ matrix.targetarch }} --output-certificate kwctl-linux-${{ matrix.targetarch}}.pem --output-signature kwctl-linux-${{ matrix.targetarch }}.sig 62 | 63 | - run: zip -j9 kwctl-linux-${{ matrix.targetarch }}.zip kwctl-linux-${{ matrix.targetarch }} kwctl-linux-${{ matrix.targetarch }}.sig kwctl-linux-${{ matrix.targetarch }}.pem 64 | 65 | - name: Upload binary 66 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 67 | with: 68 | name: kwctl-linux-${{ matrix.targetarch }} 69 | path: kwctl-linux-${{ matrix.targetarch }}.zip 70 | 71 | - name: Install the syft command 72 | uses: kubewarden/github-actions/syft-installer@7195340a122321bf547fda2ffc07eed6f6ae43f6 # v4.5.1 73 | 74 | - name: Create SBOM file 75 | shell: bash 76 | run: | 77 | syft \ 78 | --file kwctl-linux-${{ matrix.targetarch }}-sbom.spdx \ 79 | --output spdx-json \ 80 | --source-name kwctl-linux-${{ matrix.targetarch }} \ 81 | --source-version ${{ github.sha }} \ 82 | -vv \ 83 | dir:. # use dir default catalogers, which includes Cargo.toml 84 | 85 | - name: Sign SBOM file 86 | run: | 87 | cosign sign-blob --yes \ 88 | --output-certificate kwctl-linux-${{ matrix.targetarch }}-sbom.spdx.cert \ 89 | --output-signature kwctl-linux-${{ matrix.targetarch }}-sbom.spdx.sig \ 90 | kwctl-linux-${{ matrix.targetarch }}-sbom.spdx 91 | 92 | - name: Upload kwctl SBOM files 93 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 94 | with: 95 | name: kwctl-linux-${{ matrix.targetarch }}-sbom 96 | path: | 97 | kwctl-linux-${{ matrix.targetarch }}-sbom.spdx 98 | kwctl-linux-${{ matrix.targetarch }}-sbom.spdx.cert 99 | kwctl-linux-${{ matrix.targetarch }}-sbom.spdx.sig 100 | 101 | - name: Upload kwctl air gap scripts 102 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 103 | if: matrix.targetarch == 'x86_64' # only upload the scripts once 104 | with: 105 | name: kwctl-airgap-scripts 106 | path: | 107 | scripts/kubewarden-load-policies.sh 108 | scripts/kubewarden-save-policies.sh 109 | 110 | build-darwin-binaries: 111 | name: Build darwin binary 112 | strategy: 113 | matrix: 114 | targetarch: ["aarch64", "x86_64"] 115 | runs-on: macos-latest 116 | permissions: 117 | id-token: write 118 | attestations: write 119 | steps: 120 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 121 | 122 | - uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2 123 | 124 | - run: rustup target add ${{ matrix.targetarch }}-apple-darwin 125 | 126 | - name: Build kwctl 127 | run: cargo build --target=${{ matrix.targetarch }}-apple-darwin --release 128 | 129 | - run: mv target/${{ matrix.targetarch }}-apple-darwin/release/kwctl kwctl-darwin-${{ matrix.targetarch }} 130 | 131 | - name: Smoke test build 132 | if: matrix.targetarch == 'x86_64' 133 | run: ./kwctl-darwin-x86_64 --help 134 | 135 | - name: Generate attestations 136 | uses: actions/attest-build-provenance@db473fddc028af60658334401dc6fa3ffd8669fd # v2.3.0 137 | id: attestations 138 | with: 139 | subject-path: kwctl-darwin-${{ matrix.targetarch }} 140 | 141 | - name: Sign kwctl 142 | run: cosign sign-blob --yes kwctl-darwin-${{ matrix.targetarch }} --output-certificate kwctl-darwin-${{ matrix.targetarch }}.pem --output-signature kwctl-darwin-${{ matrix.targetarch }}.sig 143 | 144 | - run: zip -j9 kwctl-darwin-${{ matrix.targetarch }}.zip kwctl-darwin-${{ matrix.targetarch }} kwctl-darwin-${{ matrix.targetarch }}.sig kwctl-darwin-${{ matrix.targetarch }}.pem 145 | 146 | - name: Upload binary 147 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 148 | with: 149 | name: kwctl-darwin-${{ matrix.targetarch }} 150 | path: kwctl-darwin-${{ matrix.targetarch }}.zip 151 | 152 | - name: Install the syft command 153 | uses: kubewarden/github-actions/syft-installer@7195340a122321bf547fda2ffc07eed6f6ae43f6 # v4.5.1 154 | with: 155 | arch: darwin_amd64 156 | 157 | - name: Create SBOM file 158 | shell: bash 159 | run: | 160 | syft \ 161 | --file kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx \ 162 | --output spdx-json \ 163 | --source-name kwctl-darwin-${{ matrix.targetarch }} \ 164 | --source-version ${{ github.sha }} \ 165 | -vv \ 166 | dir:. # use dir default catalogers, which includes Cargo.toml 167 | 168 | - name: Sign SBOM file 169 | run: | 170 | cosign sign-blob --yes \ 171 | --output-certificate kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx.cert \ 172 | --output-signature kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx.sig \ 173 | kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx 174 | 175 | - name: Upload kwctl SBOM files 176 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 177 | with: 178 | name: kwctl-darwin-${{ matrix.targetarch }}-sbom 179 | path: | 180 | kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx 181 | kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx.cert 182 | kwctl-darwin-${{ matrix.targetarch }}-sbom.spdx.sig 183 | 184 | build-windows-x86_64: 185 | name: Build windows (x86_64) binary 186 | strategy: 187 | matrix: 188 | # workaround to have the same GH UI for all jobs 189 | targetarch: ["x86_64"] 190 | os: ["windows-latest"] 191 | runs-on: ${{ matrix.os }} 192 | permissions: 193 | id-token: write 194 | attestations: write 195 | steps: 196 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 197 | 198 | - uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2 199 | 200 | - name: enable git long paths on Windows 201 | if: matrix.os == 'windows-latest' 202 | run: | 203 | echo 'CMAKE_POLICY_VERSION_MINIMUM="3.5"' >> $GITHUB_ENV 204 | 205 | # aws-lc-sys CMakefile contains a directive that has been removed from 206 | # cmake v4 that has just been released (march 2025). The build failure 207 | # can be fixed by setting an environment variable 208 | - name: fix aws-lc-sys building with cmake 4.0.0 209 | run: set CMAKE_POLICY_VERSION_MINIMUM="3.5" 210 | 211 | - name: Build kwctl 212 | run: cargo build --target=x86_64-pc-windows-msvc --release 213 | 214 | - run: mv target/x86_64-pc-windows-msvc/release/kwctl.exe kwctl-windows-x86_64.exe 215 | 216 | - name: Smoke test build 217 | run: .\kwctl-windows-x86_64.exe --help 218 | 219 | - name: Generate attestations 220 | uses: actions/attest-build-provenance@db473fddc028af60658334401dc6fa3ffd8669fd # v2.3.0 221 | id: attestations 222 | with: 223 | subject-path: kwctl-windows-${{ matrix.targetarch }}.exe 224 | 225 | - name: Sign kwctl 226 | run: cosign sign-blob --yes kwctl-windows-x86_64.exe --output-certificate kwctl-windows-x86_64.pem --output-signature kwctl-windows-x86_64.sig 227 | 228 | - run: | 229 | "/c/Program Files/7-Zip/7z.exe" a kwctl-windows-x86_64.exe.zip kwctl-windows-x86_64.exe kwctl-windows-x86_64.sig kwctl-windows-x86_64.pem 230 | shell: bash 231 | 232 | - name: Upload binary 233 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 234 | with: 235 | name: kwctl-windows-x86_64 236 | path: kwctl-windows-x86_64.exe.zip 237 | 238 | - name: Install the syft command 239 | uses: kubewarden/github-actions/syft-installer@7195340a122321bf547fda2ffc07eed6f6ae43f6 # v4.5.1 240 | with: 241 | arch: windows_amd64 242 | 243 | - name: Create SBOM file 244 | shell: bash 245 | run: | 246 | syft \ 247 | --file kwctl-windows-x86_64-sbom.spdx \ 248 | --output spdx-json \ 249 | --source-name kwctl-windows-x86_64 \ 250 | --source-version ${{ github.sha }} \ 251 | -vv \ 252 | dir:. # use dir default catalogers, which includes Cargo.toml 253 | 254 | - name: Sign SBOM file 255 | shell: bash 256 | run: | 257 | cosign sign-blob --yes \ 258 | --output-certificate kwctl-windows-x86_64-sbom.spdx.cert \ 259 | --output-signature kwctl-windows-x86_64-sbom.spdx.sig \ 260 | kwctl-windows-x86_64-sbom.spdx 261 | 262 | - name: Upload kwctl SBOM files 263 | uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 264 | with: 265 | name: kwctl-windows-x86_64-sbom 266 | path: | 267 | kwctl-windows-x86_64-sbom.spdx 268 | kwctl-windows-x86_64-sbom.spdx.cert 269 | kwctl-windows-x86_64-sbom.spdx.sig 270 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | - push 3 | - pull_request 4 | - workflow_call 5 | 6 | name: Continuous integration 7 | 8 | # Declare default permissions as read only. 9 | permissions: read-all 10 | 11 | env: 12 | CARGO_TERM_COLOR: always 13 | 14 | jobs: 15 | check: 16 | name: Cargo check 17 | runs-on: ${{ matrix.os }} 18 | strategy: 19 | matrix: 20 | os: [ubuntu-latest, macos-latest, windows-latest] 21 | steps: 22 | - name: enable git long paths on Windows 23 | if: matrix.os == 'windows-latest' 24 | run: git config --global core.longpaths true 25 | 26 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 27 | 28 | # aws-lc-sys CMakefile contains a directive that has been removed from 29 | # cmake v4 that has just been released (march 2025). The build failure 30 | # can be fixed by setting an environment variable 31 | - name: fix aws-lc-sys building with cmake 4.0.0 32 | if: matrix.os == 'windows-latest' 33 | run: | 34 | echo 'CMAKE_POLICY_VERSION_MINIMUM="3.5"' >> $GITHUB_ENV 35 | 36 | - name: Run cargo check 37 | run: cargo check 38 | 39 | version-check: 40 | name: Check Cargo.toml version 41 | if: github.ref_type == 'tag' 42 | runs-on: ubuntu-latest 43 | steps: 44 | - name: Download source code 45 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 46 | - name: Check cargo file version 47 | run: | 48 | CARGO_VERSION=$(sed -n 's,^version\s*= \"\(.*\)\",\1,p' Cargo.toml) 49 | TAG_VERSION=$(echo ${{ github.ref_name }} | sed 's/v//') 50 | 51 | if [ "$CARGO_VERSION" != "$TAG_VERSION" ];then 52 | echo "::error title=Invalid Cargo.toml version::Cargo.toml version does not match the tag version" 53 | exit 1 54 | fi 55 | 56 | test: 57 | name: Unit tests 58 | runs-on: ubuntu-latest 59 | steps: 60 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 61 | - name: Run cargo test 62 | run: cargo test --workspace --bins 63 | 64 | e2e-tests: 65 | name: E2E tests 66 | runs-on: ubuntu-latest 67 | steps: 68 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 69 | - uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2 70 | - name: run e2e tests 71 | run: make e2e-tests 72 | 73 | coverage: 74 | name: coverage 75 | runs-on: ubuntu-latest 76 | continue-on-error: true 77 | steps: 78 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 79 | 80 | - name: Install cargo-llvm-cov 81 | uses: taiki-e/install-action@7bf3bbf3104a2e9a77906ccbdf6d4aa6a87b0210 # v2.52.5 82 | with: 83 | tool: cargo-llvm-cov 84 | 85 | - name: Install cosign # this is needed by some of the e2e tests 86 | uses: sigstore/cosign-installer@3454372f43399081ed03b604cb2d021dabca52bb # v3.8.2 87 | 88 | - name: Generate tests coverage 89 | run: cargo llvm-cov --lcov --output-path lcov.info 90 | 91 | - name: Upload unit-tests coverage to Codecov 92 | uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5.4.3 93 | with: 94 | files: lcov.info 95 | fail_ci_if_error: true 96 | name: unit-tests and e2e-tests 97 | verbose: true 98 | token: ${{ secrets.CODECOV_ORG_TOKEN }} 99 | 100 | fmt: 101 | name: Rustfmt 102 | runs-on: ubuntu-latest 103 | steps: 104 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 105 | - run: rustup component add rustfmt 106 | - name: Run cargo fmt 107 | run: cargo fmt --all -- --check 108 | 109 | clippy: 110 | name: Clippy 111 | runs-on: ubuntu-latest 112 | steps: 113 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 114 | - run: rustup component add clippy 115 | - name: Run cargo clippy 116 | run: cargo clippy -- -D warnings 117 | 118 | shellcheck: 119 | name: Shellcheck 120 | runs-on: ubuntu-latest 121 | steps: 122 | - name: Checkout 123 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 124 | 125 | - run: shellcheck $(find scripts/ -name '*.sh') 126 | 127 | docs: 128 | name: Update documentation 129 | runs-on: ubuntu-latest 130 | steps: 131 | - name: Checkout 132 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 133 | 134 | - run: | 135 | make build-docs 136 | if ! git diff --quiet cli-docs.md; then 137 | echo "Changes detected in cli-docs.md. Please run `make build-docs` and commit the changes." 138 | gh run cancel ${{ github.run_id }} 139 | fi 140 | 141 | spelling: 142 | name: Spell Check with Typos 143 | runs-on: ubuntu-latest 144 | steps: 145 | - name: Checkout Actions Repository 146 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 147 | - name: Spell Check Repo 148 | uses: crate-ci/typos@b1ae8d918b6e85bd611117d3d9a3be4f903ee5e4 # v1.33.1 149 | -------------------------------------------------------------------------------- /.github/workflows/fossa.yml: -------------------------------------------------------------------------------- 1 | name: fossa scanning 2 | on: 3 | push: 4 | tags: 5 | - "v*" 6 | branches: 7 | - "main" 8 | 9 | # Declare default permissions as read only. 10 | permissions: read-all 11 | 12 | jobs: 13 | fossa-scan: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 17 | - uses: fossas/fossa-action@3ebcea1862c6ffbd5cf1b4d0bd6b3fe7bd6f2cac # v1.7.0 18 | with: 19 | api-key: ${{secrets.FOSSA_API_TOKEN}} 20 | -------------------------------------------------------------------------------- /.github/workflows/openssf.yml: -------------------------------------------------------------------------------- 1 | name: Scorecards supply-chain security 2 | on: 3 | push: 4 | branches: [main] 5 | 6 | # Declare default permissions as read only. 7 | permissions: read-all 8 | 9 | jobs: 10 | analysis: 11 | name: Scorecards analysis 12 | runs-on: ubuntu-latest 13 | permissions: 14 | # Needed to upload the results to code-scanning dashboard. 15 | security-events: write 16 | # Used to receive a badge. (Upcoming feature) 17 | id-token: write 18 | 19 | steps: 20 | - name: "Checkout code" 21 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 22 | with: 23 | persist-credentials: false 24 | 25 | - name: "Run analysis" 26 | uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2 27 | with: 28 | results_file: results.sarif 29 | results_format: sarif 30 | # Publish the results for public repositories to enable scorecard badges. For more details, see 31 | # https://github.com/ossf/scorecard-action#publishing-results. 32 | publish_results: true 33 | -------------------------------------------------------------------------------- /.github/workflows/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | # branches to consider in the event; optional, defaults to all 7 | branches: 8 | - main 9 | # pull_request event is required only for autolabeler 10 | pull_request: 11 | # Only following types are handled by the action, but one can default to all as well 12 | types: [opened, reopened, synchronize, edited] 13 | # pull_request_target event is required for autolabeler to support PRs from forks 14 | pull_request_target: 15 | types: [opened, reopened, synchronize, edited] 16 | 17 | permissions: 18 | contents: read 19 | 20 | jobs: 21 | update_release_draft: 22 | permissions: 23 | # write permission is required to create a github release 24 | contents: write 25 | # write permission is required for autolabeler 26 | # otherwise, read permission is required at least 27 | pull-requests: write 28 | runs-on: ubuntu-latest 29 | steps: 30 | # Drafts your next Release notes as Pull Requests are merged into "master" 31 | - uses: release-drafter/release-drafter@b1476f6e6eb133afa41ed8589daba6dc69b4d3f5 # v6.1.0 32 | # (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml 33 | # with: 34 | # config-name: my-config.yml 35 | # disable-autolabeler: true 36 | env: 37 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: kwctl release 2 | on: 3 | push: 4 | tags: 5 | - "v*" 6 | 7 | # Declare default permissions as read only. 8 | permissions: read-all 9 | 10 | env: 11 | CARGO_TERM_COLOR: always 12 | 13 | jobs: 14 | ci: 15 | uses: ./.github/workflows/ci.yml 16 | permissions: read-all 17 | 18 | build: 19 | name: Build kwctl, sign it, and generate SBOMs 20 | uses: ./.github/workflows/build.yml 21 | permissions: 22 | id-token: write 23 | packages: write 24 | actions: read 25 | contents: write 26 | attestations: write 27 | 28 | release: 29 | name: Create release 30 | 31 | needs: 32 | - ci 33 | - build 34 | 35 | permissions: 36 | contents: write 37 | 38 | runs-on: ubuntu-latest 39 | 40 | steps: 41 | - name: Retrieve tag name 42 | if: ${{ startsWith(github.ref, 'refs/tags/') }} 43 | run: | 44 | echo TAG_NAME=$(echo ${{ github.ref_name }}) >> $GITHUB_ENV 45 | 46 | - name: Get latest release tag 47 | id: get_last_release_tag 48 | uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 49 | with: 50 | script: | 51 | let release = await github.rest.repos.getLatestRelease({ 52 | owner: context.repo.owner, 53 | repo: context.repo.repo, 54 | }); 55 | 56 | if (release.status === 200 ) { 57 | core.setOutput('old_release_tag', release.data.tag_name) 58 | return 59 | } 60 | core.setFailed("Cannot find latest release") 61 | 62 | - name: Get release ID from the release created by release drafter 63 | uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 64 | with: 65 | script: | 66 | let releases = await github.rest.repos.listReleases({ 67 | owner: context.repo.owner, 68 | repo: context.repo.repo, 69 | }); 70 | for (const release of releases.data) { 71 | if (release.draft) { 72 | core.info(release) 73 | core.exportVariable('RELEASE_ID', release.id) 74 | return 75 | } 76 | } 77 | core.setFailed(`Draft release not found`) 78 | 79 | - name: Download all artifacts 80 | uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 81 | # no name provided, download all artifacts. Puts them in folders. 82 | 83 | - name: Display structure of downloaded files 84 | run: ls -R 85 | 86 | - name: Upload release assets 87 | id: upload_release_assets 88 | uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 89 | with: 90 | script: | 91 | let fs = require('fs'); 92 | let path = require('path'); 93 | 94 | let files = [ 95 | './kwctl-airgap-scripts/kubewarden-load-policies.sh', 96 | './kwctl-airgap-scripts/kubewarden-save-policies.sh', 97 | './kwctl-darwin-aarch64/kwctl-darwin-aarch64.zip', 98 | './kwctl-darwin-aarch64-sbom/kwctl-darwin-aarch64-sbom.spdx', 99 | './kwctl-darwin-aarch64-sbom/kwctl-darwin-aarch64-sbom.spdx.cert', 100 | './kwctl-darwin-aarch64-sbom/kwctl-darwin-aarch64-sbom.spdx.sig', 101 | './kwctl-darwin-x86_64/kwctl-darwin-x86_64.zip', 102 | './kwctl-darwin-x86_64-sbom/kwctl-darwin-x86_64-sbom.spdx', 103 | './kwctl-darwin-x86_64-sbom/kwctl-darwin-x86_64-sbom.spdx.cert', 104 | './kwctl-darwin-x86_64-sbom/kwctl-darwin-x86_64-sbom.spdx.sig', 105 | './kwctl-linux-aarch64/kwctl-linux-aarch64.zip', 106 | './kwctl-linux-aarch64-sbom/kwctl-linux-aarch64-sbom.spdx', 107 | './kwctl-linux-aarch64-sbom/kwctl-linux-aarch64-sbom.spdx.cert', 108 | './kwctl-linux-aarch64-sbom/kwctl-linux-aarch64-sbom.spdx.sig', 109 | './kwctl-linux-x86_64/kwctl-linux-x86_64.zip', 110 | './kwctl-linux-x86_64-sbom/kwctl-linux-x86_64-sbom.spdx', 111 | './kwctl-linux-x86_64-sbom/kwctl-linux-x86_64-sbom.spdx.cert', 112 | './kwctl-linux-x86_64-sbom/kwctl-linux-x86_64-sbom.spdx.sig', 113 | './kwctl-windows-x86_64/kwctl-windows-x86_64.exe.zip', 114 | './kwctl-windows-x86_64-sbom/kwctl-windows-x86_64-sbom.spdx', 115 | './kwctl-windows-x86_64-sbom/kwctl-windows-x86_64-sbom.spdx.cert', 116 | './kwctl-windows-x86_64-sbom/kwctl-windows-x86_64-sbom.spdx.sig', 117 | ] 118 | const {RELEASE_ID} = process.env 119 | 120 | for (const file of files) { 121 | let file_data = fs.readFileSync(file); 122 | 123 | let response = await github.rest.repos.uploadReleaseAsset({ 124 | owner: context.repo.owner, 125 | repo: context.repo.repo, 126 | release_id: `${RELEASE_ID}`, 127 | name: path.basename(file), 128 | data: file_data, 129 | }); 130 | } 131 | 132 | - name: Publish release 133 | uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1 134 | with: 135 | script: | 136 | const {RELEASE_ID} = process.env 137 | const {TAG_NAME} = process.env 138 | isPreRelease = ${{ contains(github.ref_name, '-alpha') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-rc') }} 139 | github.rest.repos.updateRelease({ 140 | owner: context.repo.owner, 141 | repo: context.repo.repo, 142 | release_id: `${RELEASE_ID}`, 143 | draft: false, 144 | tag_name: `${TAG_NAME}`, 145 | name: `${TAG_NAME}`, 146 | prerelease: isPreRelease, 147 | make_latest: !isPreRelease 148 | }); 149 | 150 | - name: Trigger chart update 151 | env: 152 | GH_TOKEN: ${{ secrets.WORKFLOW_PAT }} 153 | run: | 154 | echo '{ 155 | "event_type": "update-chart", 156 | "client_payload": { 157 | "version": "${{ github.ref_name }}", 158 | "oldVersion": "${{ steps.get_last_release_tag.outputs.old_release_tag }}", 159 | "repository": "${{ github.repository }}" 160 | } 161 | }' > payload.json 162 | gh api repos/${{ github.repository_owner }}/helm-charts/dispatches \ 163 | -X POST \ 164 | --input payload.json 165 | -------------------------------------------------------------------------------- /.github/workflows/security-audit-cron.yml: -------------------------------------------------------------------------------- 1 | name: Security audit cron job 2 | on: 3 | schedule: 4 | - cron: "0 0 * * *" 5 | 6 | # Declare default permissions as read only. 7 | permissions: read-all 8 | 9 | jobs: 10 | audit: 11 | permissions: 12 | checks: write # for rustsec/audit-check to create check 13 | contents: read # for actions/checkout to fetch code 14 | issues: write # for rustsec/audit-check to create issues 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 18 | - uses: rustsec/audit-check@69366f33c96575abad1ee0dba8212993eecbe998 # v2.0.0 19 | with: 20 | token: ${{ secrets.GITHUB_TOKEN }} 21 | -------------------------------------------------------------------------------- /.github/workflows/security-audit-reactive.yml: -------------------------------------------------------------------------------- 1 | name: Security audit 2 | on: 3 | push: 4 | paths: 5 | - "**/Cargo.toml" 6 | - "**/Cargo.lock" 7 | 8 | # Declare default permissions as read only. 9 | permissions: read-all 10 | 11 | jobs: 12 | security_audit: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | checks: write # for rustsec/audit-check to create check 16 | contents: read # for actions/checkout to fetch code 17 | issues: write # for rustsec/audit-check to create issues 18 | steps: 19 | - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 20 | - uses: rustsec/audit-check@69366f33c96575abad1ee0dba8212993eecbe998 # v2.0.0 21 | with: 22 | token: ${{ secrets.GITHUB_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/workflows/update-rust-toolchain.yaml: -------------------------------------------------------------------------------- 1 | name: Update rust-toolchain 2 | 3 | on: 4 | workflow_dispatch: 5 | schedule: 6 | - cron: "30 3 * * 1" # 3:30 on Monday 7 | 8 | jobs: 9 | update-rust-toolchain: 10 | name: Update Rust toolchain 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 15 | 16 | - name: Install Updatecli in the runner 17 | uses: updatecli/updatecli-action@307ce72e224b82157cc31c78828f168b8e55d47d # v2.84.0 18 | 19 | - name: Update rust version inside of rust-toolchain file 20 | id: update_rust_toolchain 21 | env: 22 | UPDATECLI_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | UPDATECLI_GITHUB_OWNER: ${{ github.repository_owner }} 24 | run: |- 25 | updatecli apply --config ./updatecli/updatecli.d/update-rust-toolchain.yaml \ 26 | --values updatecli/values.yaml 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /bin 3 | bom-cargo.json 4 | 5 | # coverage instrumentation: 6 | *.profraw 7 | -------------------------------------------------------------------------------- /.taplo.toml: -------------------------------------------------------------------------------- 1 | [formatting] 2 | align_entries = true 3 | reorder_arrays = true 4 | reorder_keys = true 5 | sort_keys = true 6 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @kubewarden/kubewarden-developers 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Making a new release 4 | 5 | 1. Bump to `version = "X.Y.Z"` on `cargo.toml`. 6 | 2. Format if needed, commit and open PR (as `main` branch is protected). 7 | 3. Wait for PR to be merged. 8 | 4. Once the PR is in `main`, create an annotated signed tag on the merge commit 9 | of the PR in `main`: 10 | `git tag -s -a -m "vX.Y.Z" vX.Y.Z`. This will trigger the GH Action for 11 | release. Wait for it to complete and check that it is created. 12 | 5. If needed, edit the GH release description. 13 | 14 | ## GitHub Actions 15 | 16 | For some workflows, GITHUB_TOKEN needs read and write permissions (e.g: to 17 | perform cosign signatures); if you have forked the repository, you may need to 18 | change "settings -> actions -> general -> workflow permissions" to "Read and 19 | write permissions". 20 | 21 | Also, given how the release and release-drafter workflows work, they need git 22 | tags present; push the tags from origin to your fork. 23 | 24 | ## Code conventions 25 | 26 | 27 | Check out our global [CONTRIBUTING guidelines](https://github.com/kubewarden/.github/blob/main/CONTRIBUTING.md) for Rust code conventions 28 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | authors = ["Kubewarden Developers "] 3 | description = "Tool to manage Kubewarden policies" 4 | edition = "2021" 5 | name = "kwctl" 6 | version = "1.25.0" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | anyhow = "1.0" 12 | clap = { version = "4.5", features = ["cargo", "env"] } 13 | clap-markdown = "0.1.4" 14 | clap_complete = "4.5" 15 | directories = "6.0.0" 16 | flate2 = "1.1" 17 | humansize = "2.1" 18 | indicatif = "0.17" 19 | is-terminal = "0.4.16" 20 | itertools = "0.14.0" 21 | k8s-openapi = { version = "0.25.0", default-features = false, features = [ 22 | "v1_30", 23 | ] } 24 | lazy_static = "1.4.0" 25 | pem = "3" 26 | policy-evaluator = { git = "https://github.com/kubewarden/policy-evaluator", tag = "v0.25.2" } 27 | prettytable-rs = "^0.10" 28 | regex = "1" 29 | rustls-pki-types = { version = "1", features = ["alloc"] } 30 | semver = { version = "1.0.22", features = ["serde"] } 31 | serde = { version = "1.0", features = ["derive"] } 32 | serde_json = "1.0" 33 | serde_yaml = "0.9.34" 34 | tar = "0.4.40" 35 | termimad = "0.33.0" 36 | thiserror = "2.0" 37 | time = "0.3.36" 38 | tiny-bench = "0.4" 39 | tokio = { version = "^1.42.0", features = ["full"] } 40 | tracing = "0.1" 41 | tracing-subscriber = { version = "0.3", features = ["fmt"] } 42 | url = "2.5.0" 43 | walrus = "0.23.0" 44 | wasmparser = "0.232" 45 | 46 | hostname-validator = "1.1.1" 47 | # This is required to have reqwest built using the `rustls-tls-native-roots` 48 | # feature across all the transitive dependencies of kwctl 49 | # This is required to have kwctl use the system certificates instead of the 50 | # ones bundled inside of rustls 51 | reqwest = { version = "0", default-features = false, features = [ 52 | "rustls-tls-native-roots", 53 | ] } 54 | 55 | [dev-dependencies] 56 | assert_cmd = "2.0.14" 57 | hyper = { version = "1.5.0" } 58 | predicates = "3.1" 59 | rstest = "0.25" 60 | tempfile = "3.17" 61 | testcontainers = { version = "0.24", features = ["blocking"] } 62 | tower-test = "0.4" 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: build-release build-docs 3 | 4 | .PHONY: build-release 5 | build-release: 6 | cargo build --release 7 | 8 | .PHONY:build-docs 9 | build-docs: 10 | cargo run --release -- docs --output cli-docs.md 11 | 12 | .PHONY: fmt 13 | fmt: 14 | cargo fmt --all -- --check 15 | 16 | .PHONY: lint 17 | lint: 18 | cargo clippy -- -D warnings 19 | 20 | .PHONY: typos 21 | typos: 22 | typos # run typo checker from crate-ci/typos 23 | 24 | .PHONY: test 25 | test: fmt lint 26 | cargo test --workspace --bins 27 | 28 | .PHONY: e2e-tests 29 | e2e-tests: 30 | cargo test --test '*' 31 | 32 | .PHONY: coverage 33 | coverage: 34 | cargo llvm-cov --html 35 | 36 | .PHONY: clean 37 | clean: 38 | cargo clean 39 | 40 | .PHONY: tag 41 | tag: 42 | @git tag "${TAG}" || (echo "Tag ${TAG} already exists. If you want to retag, delete it manually and re-run this command" && exit 1) 43 | @git-chglog --output CHANGELOG.md 44 | @git commit -m 'Update CHANGELOG.md' -- CHANGELOG.md 45 | @git tag -f "${TAG}" 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Kubewarden Core Repository](https://github.com/kubewarden/community/blob/main/badges/kubewarden-core.svg)](https://github.com/kubewarden/community/blob/main/REPOSITORIES.md#core-scope) 2 | [![Stable](https://img.shields.io/badge/status-stable-brightgreen?style=for-the-badge)](https://github.com/kubewarden/community/blob/main/REPOSITORIES.md#stable) 3 | [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/9180/badge)](https://www.bestpractices.dev/projects/9180) 4 | [![FOSSA Status](https://app.fossa.com/api/projects/custom%2B25850%2Fgithub.com%2Fkubewarden%2Fkwctl.svg?type=shield)](https://app.fossa.com/projects/cjustom%2B25850%2Fgithub.com%2Fkubewarden%2Fkwctl?ref=badge_shield) 5 | [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/kubewarden/kwctl/badge)](https://scorecard.dev/viewer/?uri=github.com/kubewarden/kwctl) 6 | 7 | # `kwctl` 8 | 9 | `kwctl` is the go-to CLI tool for [Kubewarden](https://kubewarden.io) 10 | users. 11 | 12 | Think of it as the `docker` CLI tool if you were working with 13 | containers. 14 | 15 | ## How does `kwctl` help me? 16 | 17 | ### As a policy author 18 | 19 | - e2e testing of your policy. Test your policy against crafted 20 | Kubernetes requests, and ensure your policy behaves as you 21 | expect. You can even test context-aware policies, that require 22 | access to a running cluster. 23 | 24 | - Embed metadata in your Wasm module, so the binary is annotated with 25 | the permissions it needs to execute. 26 | 27 | - Publish policies to OCI registries. 28 | 29 | - Generate initial `ClusterAdmissionPolicy` scaffolding for your 30 | policy. 31 | 32 | ### As a cluster administrator 33 | 34 | - Inspect remote policies. Given a policy in an OCI registry, or in an 35 | HTTP server, show all static information about the policy. 36 | 37 | - Dry-run of a policy in your cluster. Test the policy against crafted 38 | Kubernetes requests, and ensure the policy behaves as you expect 39 | given the input data you provide. You can even test context-aware 40 | policies, that require access to a running cluster, also in a 41 | dry-run mode. 42 | 43 | - Generate `ClusterAdmissionPolicy` scaffolding for a given policy. 44 | 45 | ### Everyone 46 | 47 | - The UX of this tool is intended to be as easy and intuitive as 48 | possible. 49 | 50 | ## Install 51 | 52 | Built binaries for `Linux x86_64`, `Windows x86_64`, `MacOS x86_64` and `MacOS 53 | aarch64 (M1)` are available in [GH Releases](https://github.com/kubewarden/kwctl/releases). 54 | 55 | There is also: 56 | 57 | - Community-created [Homebrew 🍺 formula for kwctl](https://formulae.brew.sh/formula/kwctl) 58 | - Community-created [AUR 🐧 package](https://aur.archlinux.org/packages/kwctl-bin) 59 | 60 | ## Usage 61 | 62 | These are the commands currently supported by kwctl. 63 | 64 | If you want a complete list of the available commands, you can read the 65 | [cli-docs.md](./cli-docs.md) file. 66 | 67 | ### List policies 68 | 69 | The list of policies downloaded on the local machine can be 70 | obtained by doing: 71 | 72 | ```console 73 | kwctl policies 74 | ``` 75 | 76 | ### Download policies 77 | 78 | Policies can be downloaded using the `pull` command. 79 | 80 | The name of the policy must be expressed as a url with one of the 81 | following protocols: 82 | 83 | - `http://`: pull from a HTTP server 84 | - `https://`: pull from a HTTPS server 85 | - `registry://`: pull from an OCI registry 86 | 87 | Pulling from a registry, by tag: 88 | 89 | ```console 90 | kwctl pull registry://ghcr.io/kubewarden/policies/psp-capabilities:latest 91 | ``` 92 | 93 | It's possible to pull from a registry using an immutable reference (in the 94 | same way as with regular container images): 95 | 96 | ```console 97 | kwctl pull registry://ghcr.io/kubewarden/policies/psp-capabilities@sha256:61ef63621fa5be8e422881d96d05edfef810992fbf9468e35d1fa5ae815bd97c 98 | ``` 99 | 100 | Note well, the shasum is the digest of the OCI artifact containing the policy. 101 | This value can be obtained using a tool like [crane](https://github.com/google/go-containerregistry/blob/main/cmd/crane/README.md): 102 | 103 | ```console 104 | crane digest ghcr.io/kubewarden/policies/psp-capabilities:v0.1.6 105 | ``` 106 | 107 | ### Run a policy locally 108 | 109 | `kwctl` can be used to run a policy locally, outside of Kubernetes. This can be used 110 | to quickly evaluate a policy and find the right settings for it. 111 | 112 | The evaluation is done against a pre-recorded [`AdmissionReview`](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#request). 113 | 114 | Running a policy locally: 115 | 116 | ```console 117 | kwctl run \ 118 | --settings-json '{"constrained_labels": {"owner": ".*"}}' \ 119 | -r test_data/ingress.json \ 120 | registry://ghcr.io/kubewarden/policies/safe-labels:v0.1.5 121 | ``` 122 | 123 | Policy configuration can be passed on the CLI via the `--settings-json` flag 124 | or can be loaded from the disk via the `--settings-path` flag. 125 | 126 | #### Scaffold AdmissionReview from a Kubernetes resource 127 | 128 | It's possible to scaffold an `AdmissionReview` object from a Kubernetes resource: 129 | 130 | ```console 131 | kwctl scaffold \ 132 | admission-request \ 133 | --operation CREATE \ 134 | --object ingress.yaml 135 | ``` 136 | 137 | The output of the above command can be used by the `run` command. 138 | 139 | ### Annotate a policy 140 | 141 | Kubewarden policies are WebAssembly module, which must contain some 142 | Kubewarden-specific metadata. 143 | 144 | The act of adding metadata to the policy is done by the policy author, right 145 | before policy distribution. 146 | 147 | The `kwctl annotate` command can be used to perform this operation. 148 | 149 | ### Inspect a policy 150 | 151 | The metadata attached to a policy, plus other details can be seen via the 152 | `kwctl inspect` command. 153 | 154 | This command works against a policy that has been previously downloaded. 155 | 156 | ### Publish a policy 157 | 158 | `kwctl` can be used to publish a local policy into an OCI registry. This is done 159 | via the `push` sub-command. 160 | 161 | The `push` sub-command can also be used to copy a policy into another registry: 162 | 163 | ```console 164 | kwctl push registry://ghcr.io/kubewarden/policies/safe-labels:v0.1.5 \ 165 | registry://registry.local.lan/kubewarden/safe-labels:v0.1.5 166 | ``` 167 | 168 | The above command copies a local policy that was downloaded from the GitHub 169 | Container Registry, into a local registry. 170 | 171 | > **Note well:** the policy must be previously downloaded locally via `kwctl pull` 172 | 173 | ### Remove a local policy 174 | 175 | Local policies can be removed via the `rm` sub-command: 176 | 177 | ```console 178 | kwctl rm 179 | ``` 180 | 181 | ### Scaffold Kubernetes Custom Resources 182 | 183 | Kubewarden policies are enforced on Kubernetes clusters by using 184 | special Custom Resources provided by our [Kubernetes integration](https://docs.kubewarden.io/quick-start.html#kubewarden-policies). 185 | 186 | The `manifest` sub-command can be used to quickly scaffold the definition of 187 | Kubewarden Custom Resources. 188 | 189 | The manifest command shares some of the arguments of the `run` command, it's 190 | typical to test a policy locally via the `kwctl run` command and then, once 191 | satisfied about the policy settings, create a deployment manifest for it via 192 | the `manifest` command. 193 | 194 | Step #1, find the right policy settings: 195 | 196 | ```console 197 | kwctl run \ 198 | --settings-json '{"constrained_labels": {"owner": ".*"}}' \ 199 | -r test_data/ingress.json \ 200 | registry://ghcr.io/kubewarden/policies/safe-labels:v0.1.5 201 | ``` 202 | 203 | Step #2, generate a manifest to enforce the policy inside of a 204 | Kubernetes cluster: 205 | 206 | ```console 207 | kwctl manifest\ 208 | --settings-json '{"constrained_labels": {"owner": ".*"}}' \ 209 | -t ClusterAdmissionPolicy \ 210 | registry://ghcr.io/kubewarden/policies/safe-labels:v0.1.5 211 | ``` 212 | 213 | This will produce the following output: 214 | 215 | ```yaml 216 | --- 217 | apiVersion: policies.kubewarden.io/v1 218 | kind: ClusterAdmissionPolicy 219 | metadata: 220 | name: generated-policy 221 | spec: 222 | module: "registry://ghcr.io/kubewarden/policies/safe-labels:v0.1.5" 223 | settings: 224 | constrained_labels: 225 | owner: ".*" 226 | rules: 227 | - apiGroups: 228 | - "*" 229 | apiVersions: 230 | - "*" 231 | resources: 232 | - "*" 233 | operations: 234 | - CREATE 235 | - UPDATE 236 | mutating: false 237 | ``` 238 | 239 | Which can then be customized by hand, and then applied into a Kubernetes cluster. 240 | 241 | ### Shell completion 242 | 243 | `kwctl` can generate autocompletion scripts for the following shells: 244 | 245 | - bash 246 | - elvish 247 | - fish 248 | - powershell 249 | - zsh 250 | 251 | The completion script can be generated with the following command: 252 | 253 | ```console 254 | $ kwctl completions -s 255 | ``` 256 | 257 | The command will print to the stdout the completion script. 258 | 259 | #### Bash 260 | 261 | To load completions in your current shell session: 262 | 263 | ```console 264 | $ source <(kwctl completions -s bash) 265 | ``` 266 | 267 | To load completions for every new session, execute once: 268 | 269 | - Linux: `$ kwctl completions -s bash > /etc/bash_completion.d/kwctl` 270 | - MacOS: `$ kwctl completions -s bash > /usr/local/etc/bash_completion.d/kwctl` 271 | 272 | You will need to start a new shell for this setup to take effect. 273 | 274 | #### Fish 275 | 276 | To load completions in your current shell session: 277 | 278 | ```console 279 | $ kwctl completions -s fish | source 280 | ``` 281 | 282 | To load completions for every new session, execute once: 283 | 284 | ```console 285 | $ kwctl completions -s fish > ~/.config/fish/completions/kwctl.fish 286 | ``` 287 | 288 | You will need to start a new shell for this setup to take effect. 289 | 290 | #### Zsh 291 | 292 | To load completions in your current shell session: 293 | 294 | ```console 295 | $ source <(kwctl completions -s zsh) 296 | ``` 297 | 298 | To load completions for every new session, execute once: 299 | 300 | ```console 301 | $ kwctl completions -s zsh > "${fpath[1]}/_kwctl" 302 | ``` 303 | 304 | ##### Oh My Zsh users 305 | 306 | These steps are required by [oh-my-zsh](https://ohmyz.sh/) users: 307 | 308 | ```console 309 | $ print -l $fpath | grep '.oh-my-zsh/completions' 310 | $ mkdir ~/.oh-my-zsh/completions 311 | $ kwctl completions -s zsh > ~/.oh-my-zsh/completions/_kwctl 312 | rm ~/.zcompdump* 313 | ``` 314 | 315 | Then start a new shell or run `source ~/.zshrc` once. 316 | 317 | ## Verify kwctl binaries 318 | 319 | kwctl binaries are signed using [Sigstore's blog signing](https://docs.sigstore.dev/signing/signing_with_blobs/). 320 | When you download a [kwctl release](https://github.com/kubewarden/kwctl/releases/) each zip file contains two 321 | files that can be used for verification: `kwctl.sig` and `kwctl.pem`. 322 | 323 | In order to verify kwctl you need cosign installed, and then execute the following command: 324 | 325 | ``` 326 | cosign verify-blob \ 327 | --signature kwctl-linux-x86_64.sig \ 328 | --cert kwctl-linux-x86_64.pem kwctl-linux-x86_64 \ 329 | --certificate-identity-regexp 'https://github.com/kubewarden/*' \ 330 | --certificate-oidc-issuer https://token.actions.githubusercontent.com 331 | ``` 332 | 333 | The output should be: 334 | 335 | ``` 336 | Verified OK 337 | ``` 338 | 339 | # Software bill of materials & provenance 340 | 341 | Kwctl has its software bill of materials (SBOM) published every release. They 342 | follow the [SPDX](https://spdx.dev/) format, you can find them together with 343 | the signature and certificate used to sign it in the [releases 344 | assets](https://github.com/kubewarden/kwctl/releases). 345 | 346 | The build [Provenance](https://slsa.dev/spec/v1.0/provenance) files are 347 | following the [SLSA](https://slsa.dev/provenance/v0.2#schema) provenance schema 348 | and are accessible at the GitHub Actions' 349 | [provenance](https://github.com/kubewarden/kwctl/attestations) tab. For 350 | information on their format and how to verify them, see the [GitHub 351 | documentation](https://docs.github.com/en/actions/security-for-github-actions/using-artifact-attestations/verifying-attestations-offline). 352 | 353 | ## Security disclosure 354 | 355 | See [SECURITY.md](https://github.com/kubewarden/community/blob/main/SECURITY.md) on the kubewarden/community repo. 356 | 357 | ## Changelog 358 | 359 | See [GitHub Releases content](https://github.com/kubewarden/kwctl/releases). 360 | -------------------------------------------------------------------------------- /SECURITY-INSIGHTS.yml: -------------------------------------------------------------------------------- 1 | header: 2 | schema-version: 1.0.0 3 | last-updated: "2024-08-12" 4 | last-reviewed: "2023-08-12" 5 | expiration-date: "2025-10-01T01:00:00.000Z" 6 | project-url: https://github.com/kubewarden/kwctl/ 7 | changelog: https://github.com/kubewarden/kwctl/releases/latest 8 | license: https://github.com/kubewarden/kwctl/blob/main/LICENSE 9 | project-lifecycle: 10 | bug-fixes-only: false 11 | core-maintainers: 12 | - https://github.com/kubewarden/community?tab=readme-ov-file#maintainers 13 | roadmap: https://github.com/kubewarden/community?tab=readme-ov-file#roadmap 14 | status: active 15 | contribution-policy: 16 | accepts-pull-requests: true 17 | accepts-automated-pull-requests: true 18 | contributing-policy: https://github.com/kubewarden/kwctl/blob/main/CONTRIBUTING.md 19 | code-of-conduct: https://github.com/kubewarden/community/blob/main/CODE_OF_CONDUCT.md 20 | documentation: 21 | - https://docs.kubewarden.io 22 | distribution-points: 23 | - https://github.com/kubewarden/kwctl/ 24 | security-artifacts: 25 | threat-model: 26 | threat-model-created: true 27 | evidence-url: 28 | - https://docs.kubewarden.io/reference/threat-model 29 | security-testing: 30 | - tool-type: sca 31 | tool-name: Dependabot 32 | tool-version: latest 33 | integration: 34 | ad-hoc: false 35 | ci: true 36 | before-release: true 37 | comment: | 38 | Dependabot is enabled for this repo. 39 | security-contacts: 40 | - type: website 41 | value: https://docs.kubewarden.io/disclosure 42 | vulnerability-reporting: 43 | accepts-vulnerability-reports: true 44 | security-policy: https://github.com/kubewarden/community/blob/main/SECURITY.md 45 | email-contact: cncf-kubewarden-maintainers@lists.cncf.io 46 | comment: | 47 | The first and best way to report a vulnerability is by using private security issues in GitHub or opening an issue on Github. We are also available on the Kubernetes Slack in the #kubewaden-dev channel. 48 | dependencies: 49 | third-party-packages: true 50 | dependencies-lists: 51 | - https://github.com/kubewarden/kwctl/blob/main/Cargo.lock 52 | sbom: 53 | - sbom-file: https://github.com/kubewarden/kwctl/releases/latest/download/kwctl-linux-x86_64-sbom.spdx 54 | sbom-format: SPDX 55 | sbom-url: https://github.com/anchore/sbom-action 56 | dependencies-lifecycle: 57 | policy-url: https://github.com/kubewarden/community/blob/main/SECURITY.md#security-patch-policy 58 | env-dependencies-policy: 59 | policy-url: https://github.com/kubewarden/community/blob/main/SECURITY.md#dependency-policy 60 | -------------------------------------------------------------------------------- /config.toml: -------------------------------------------------------------------------------- 1 | # Due to an issue with linking when cross-compiling, specify the 2 | # linker and archiver for cross-compiled targets. 3 | # 4 | # More information: https://github.com/rust-lang/cargo/issues/4133 5 | 6 | [target.x86_64-unknown-linux-musl] 7 | linker = "x86_64-linux-musl-gcc" 8 | 9 | [target.aarch64-unknown-linux-musl] 10 | linker = "aarch64-linux-musl-gcc" 11 | -------------------------------------------------------------------------------- /coverage/integration-tests/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /coverage/unit-tests/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore 5 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "github>kubewarden/github-actions//renovate-config/default" 4 | ], 5 | "packageRules": [ 6 | { 7 | "description": "Update GitHub Actions", 8 | "matchManagers": ["github-actions"], 9 | "groupName": "github-actions", 10 | "groupSlug": "github-actions" 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | 2 | [toolchain] 3 | channel = "1.87.0" 4 | components = ["clippy", "rust-analyzer", "rustfmt"] 5 | profile = "minimal" 6 | targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-musl", "x86_64-apple-darwin", "x86_64-pc-windows-msvc", "x86_64-unknown-linux-musl"] 7 | -------------------------------------------------------------------------------- /scripts/kubewarden-load-policies.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | kwctl="${KWCTL_CMD:-kwctl}" 5 | policies="kubewarden-policies.tar.gz" 6 | list="kubewarden-policies.txt" 7 | 8 | usage () { 9 | echo "USAGE: $0 [--policies kubewarden-policies.tar.gz] --registry my.registry.com:5000" 10 | echo " [-l|--policies-list path] text file with list of policies; one image per line." 11 | echo " [-p|--policies path] tar.gz generated by kwctl save." 12 | echo " [-r|--registry registry:port] target private registry:port." 13 | echo " [-s|--sources-path path] kwctl sources path." 14 | echo " [-h|--help] Usage message" 15 | } 16 | 17 | pushPolicy() { 18 | newPolicyUrl=$1 19 | if [[ -n $sourcesPath ]]; then 20 | $kwctl push "$policy" "$newPolicyUrl" --sources-path "$sourcesPath" 21 | else 22 | $kwctl push "$policy" "$newPolicyUrl" 23 | fi 24 | } 25 | 26 | while [[ $# -gt 0 ]]; do 27 | key="$1" 28 | shift 29 | case $key in 30 | -r|--registry) 31 | registry="$1" 32 | shift # past value 33 | ;; 34 | -l|--policies-list) 35 | list="$1" 36 | shift # past value 37 | ;; 38 | -p|--policies) 39 | policies="$1" 40 | shift # past value 41 | ;; 42 | -s|--sources-path) 43 | sourcesPath="$1" 44 | shift # past value 45 | ;; 46 | -h|--help) 47 | help="true" 48 | ;; 49 | *) 50 | usage 51 | exit 1 52 | ;; 53 | esac 54 | done 55 | if [[ -v help ]]; then 56 | usage 57 | exit 0 58 | fi 59 | if [[ -z ${registry:-} ]]; then 60 | usage 61 | exit 1 62 | fi 63 | 64 | $kwctl load --input "${policies}" 65 | 66 | policies=() 67 | while read -r policy; do 68 | policies+=("${policy}"); 69 | done < "${list}" 70 | 71 | for policy in "${policies[@]}"; do 72 | if [[ $policy == registry://* ]]; then 73 | # replace registry with the one provided as parameter. 74 | # e.g. registry://ghcr.io/kubewarden/policies/capabilities-psp:v0.1.9 -> registry://localhost:5000/kubewarden/policies/capabilities-psp:v0.1.9 75 | oldPolicyUrl=$(awk -Fregistry:// '{print $2}' <<< "$policy") 76 | oldRegistry=$(echo "$oldPolicyUrl" | cut -f1 -d"/") 77 | newPolicyUrl="registry://${oldPolicyUrl/$oldRegistry/$registry}" 78 | pushPolicy "$newPolicyUrl" 79 | fi 80 | if [[ $policy == https://* ]]; then 81 | # replace registry with the one provided as parameter. 82 | # e.g. https://github.com/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm -> registry://localhost:5000/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm 83 | oldPolicyUrl=$(awk -Fhttps:// '{print $2}' <<< "$policy") 84 | newPolicyUrl="registry://$registry/${oldPolicyUrl#*/}" 85 | pushPolicy "$newPolicyUrl" 86 | fi 87 | done 88 | -------------------------------------------------------------------------------- /scripts/kubewarden-save-policies.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | kwctl="${KWCTL_CMD:-kwctl}" 5 | policies="kubewarden-policies.tar.gz" 6 | list="kubewarden-policies.txt" 7 | 8 | usage () { 9 | echo "USAGE: $0 [--policies-list kubewarden-policies.txt] [--policies kubewarden-policies.tar.gz]" 10 | echo " [-l|--policies-list path] text file with list of policies; one police per line." 11 | echo " [-p|--policies path] tar.gz generated by kwctl save." 12 | echo " [-h|--help] Usage message" 13 | } 14 | 15 | while [[ $# -gt 0 ]]; do 16 | key="$1" 17 | shift 18 | case $key in 19 | -p|--policies) 20 | policies="$1" 21 | shift # past value 22 | ;; 23 | -l|--policies-list) 24 | list="$1" 25 | shift # past value 26 | ;; 27 | -h|--help) 28 | help="true" 29 | ;; 30 | *) 31 | usage 32 | exit 1 33 | ;; 34 | esac 35 | done 36 | 37 | if [[ -v help ]]; then 38 | usage 39 | exit 0 40 | fi 41 | 42 | pulled=() 43 | while IFS= read -r i; do 44 | [ -z "${i}" ] && continue 45 | if $kwctl pull "${i}" > /dev/null 2>&1; then 46 | echo "Policy pull success: ${i}" 47 | pulled+=("${i}") 48 | else 49 | echo "Policy pull failed: ${i}" 50 | fi 51 | done < "${list}" 52 | 53 | echo "Creating ${policies} with ${#pulled[@]} policies" 54 | $kwctl save "${pulled[@]}" --output "${policies}" 55 | 56 | -------------------------------------------------------------------------------- /src/annotate.rs: -------------------------------------------------------------------------------- 1 | use crate::backend::{Backend, BackendDetector}; 2 | use anyhow::{anyhow, Result}; 3 | use policy_evaluator::validator::Validate; 4 | use policy_evaluator::{constants::*, policy_metadata::Metadata, ProtocolVersion}; 5 | use std::fs::{self, File}; 6 | use std::path::PathBuf; 7 | 8 | pub(crate) fn write_annotation( 9 | wasm_path: PathBuf, 10 | metadata_path: PathBuf, 11 | destination: PathBuf, 12 | usage_path: Option, 13 | ) -> Result<()> { 14 | let usage = usage_path 15 | .map(|path| { 16 | fs::read_to_string(path).map_err(|e| anyhow!("Error reading usage file: {}", e)) 17 | }) 18 | .transpose()?; 19 | let backend_detector = BackendDetector::default(); 20 | let metadata = prepare_metadata( 21 | wasm_path.clone(), 22 | metadata_path, 23 | backend_detector, 24 | usage.as_deref(), 25 | )?; 26 | write_annotated_wasm_file(wasm_path, destination, metadata) 27 | } 28 | 29 | fn prepare_metadata( 30 | wasm_path: PathBuf, 31 | metadata_path: PathBuf, 32 | backend_detector: BackendDetector, 33 | usage: Option<&str>, 34 | ) -> Result { 35 | let metadata_file = 36 | File::open(metadata_path).map_err(|e| anyhow!("Error opening metadata file: {}", e))?; 37 | let mut metadata: Metadata = serde_yaml::from_reader(&metadata_file) 38 | .map_err(|e| anyhow!("Error unmarshalling metadata {}", e))?; 39 | 40 | let backend = backend_detector.detect(wasm_path, &metadata)?; 41 | 42 | match backend { 43 | Backend::Opa | Backend::OpaGatekeeper | Backend::Wasi => { 44 | metadata.protocol_version = Some(ProtocolVersion::Unknown) 45 | } 46 | Backend::KubewardenWapc(protocol_version) => { 47 | metadata.protocol_version = Some(protocol_version) 48 | } 49 | }; 50 | 51 | let mut annotations = metadata.annotations.unwrap_or_default(); 52 | annotations.insert( 53 | String::from(KUBEWARDEN_ANNOTATION_KWCTL_VERSION), 54 | String::from(env!("CARGO_PKG_VERSION")), 55 | ); 56 | if let Some(s) = usage { 57 | annotations.insert( 58 | String::from(KUBEWARDEN_ANNOTATION_POLICY_USAGE), 59 | String::from(s), 60 | ); 61 | } 62 | metadata.annotations = Some(annotations); 63 | 64 | metadata 65 | .validate() 66 | .map_err(|e| anyhow!("Metadata is invalid: {:?}", e)) 67 | .and(Ok(metadata)) 68 | } 69 | 70 | fn write_annotated_wasm_file( 71 | input_path: PathBuf, 72 | output_path: PathBuf, 73 | metadata: Metadata, 74 | ) -> Result<()> { 75 | let buf: Vec = std::fs::read(input_path)?; 76 | let metadata_json = serde_json::to_vec(&metadata)?; 77 | 78 | let mut module = walrus::Module::from_buffer(buf.as_slice())?; 79 | 80 | let custom_section = walrus::RawCustomSection { 81 | name: String::from(KUBEWARDEN_CUSTOM_SECTION_METADATA), 82 | data: metadata_json, 83 | }; 84 | module.customs.add(custom_section); 85 | 86 | module.emit_wasm_file(output_path)?; 87 | Ok(()) 88 | } 89 | 90 | #[cfg(test)] 91 | mod tests { 92 | use super::*; 93 | use std::io::Write; 94 | use tempfile::tempdir; 95 | 96 | fn mock_protocol_version_detector_v1(_wasm_path: PathBuf) -> Result { 97 | Ok(ProtocolVersion::V1) 98 | } 99 | 100 | fn mock_rego_policy_detector_true(_wasm_path: PathBuf) -> Result { 101 | Ok(true) 102 | } 103 | 104 | fn mock_rego_policy_detector_false(_wasm_path: PathBuf) -> Result { 105 | Ok(false) 106 | } 107 | 108 | #[test] 109 | fn test_kwctl_version_is_added_to_already_populated_annotations() -> Result<()> { 110 | let dir = tempdir()?; 111 | 112 | let file_path = dir.path().join("metadata.yml"); 113 | let mut file = File::create(file_path.clone())?; 114 | 115 | let expected_policy_title = "psp-test"; 116 | let raw_metadata = format!( 117 | r#" 118 | rules: 119 | - apiGroups: [""] 120 | apiVersions: ["v1"] 121 | resources: ["pods"] 122 | operations: ["CREATE", "UPDATE"] 123 | mutating: false 124 | backgroundAudit: true 125 | annotations: 126 | io.kubewarden.policy.title: {} 127 | "#, 128 | expected_policy_title 129 | ); 130 | 131 | write!(file, "{}", raw_metadata)?; 132 | 133 | let backend_detector = BackendDetector::new( 134 | mock_rego_policy_detector_false, 135 | mock_protocol_version_detector_v1, 136 | ); 137 | let metadata = prepare_metadata( 138 | PathBuf::from("irrelevant.wasm"), 139 | file_path, 140 | backend_detector, 141 | None, 142 | )?; 143 | let annotations = metadata.annotations.unwrap(); 144 | 145 | assert_eq!( 146 | annotations.get(KUBEWARDEN_ANNOTATION_POLICY_TITLE), 147 | Some(&String::from(expected_policy_title)) 148 | ); 149 | 150 | assert_eq!( 151 | annotations.get(KUBEWARDEN_ANNOTATION_KWCTL_VERSION), 152 | Some(&String::from(env!("CARGO_PKG_VERSION"))), 153 | ); 154 | 155 | Ok(()) 156 | } 157 | 158 | #[test] 159 | fn test_kwctl_version_is_overwrote_when_user_accidentally_provides_it() -> Result<()> { 160 | let dir = tempdir()?; 161 | 162 | let file_path = dir.path().join("metadata.yml"); 163 | let mut file = File::create(file_path.clone())?; 164 | 165 | let expected_policy_title = "psp-test"; 166 | let raw_metadata = format!( 167 | r#" 168 | rules: 169 | - apiGroups: [""] 170 | apiVersions: ["v1"] 171 | resources: ["pods"] 172 | operations: ["CREATE", "UPDATE"] 173 | mutating: false 174 | backgroundAudit: true 175 | annotations: 176 | io.kubewarden.policy.title: {} 177 | {}: NOT_VALID 178 | "#, 179 | expected_policy_title, KUBEWARDEN_ANNOTATION_KWCTL_VERSION, 180 | ); 181 | 182 | write!(file, "{}", raw_metadata)?; 183 | 184 | let backend_detector = BackendDetector::new( 185 | mock_rego_policy_detector_false, 186 | mock_protocol_version_detector_v1, 187 | ); 188 | let metadata = prepare_metadata( 189 | PathBuf::from("irrelevant.wasm"), 190 | file_path, 191 | backend_detector, 192 | None, 193 | )?; 194 | let annotations = metadata.annotations.unwrap(); 195 | 196 | assert_eq!( 197 | annotations.get(KUBEWARDEN_ANNOTATION_POLICY_TITLE), 198 | Some(&String::from(expected_policy_title)) 199 | ); 200 | 201 | assert_eq!( 202 | annotations.get(KUBEWARDEN_ANNOTATION_KWCTL_VERSION), 203 | Some(&String::from(env!("CARGO_PKG_VERSION"))), 204 | ); 205 | 206 | Ok(()) 207 | } 208 | 209 | #[test] 210 | fn test_kwctl_version_is_added_when_annotations_is_none() -> Result<()> { 211 | let dir = tempdir()?; 212 | 213 | let file_path = dir.path().join("metadata.yml"); 214 | let mut file = File::create(file_path.clone())?; 215 | 216 | let raw_metadata = r#" 217 | rules: 218 | - apiGroups: [""] 219 | apiVersions: ["v1"] 220 | resources: ["pods"] 221 | operations: ["CREATE", "UPDATE"] 222 | mutating: false 223 | backgroundAudit: true 224 | executionMode: kubewarden-wapc 225 | "#; 226 | 227 | write!(file, "{}", raw_metadata)?; 228 | 229 | let backend_detector = BackendDetector::new( 230 | mock_rego_policy_detector_false, 231 | mock_protocol_version_detector_v1, 232 | ); 233 | let metadata = prepare_metadata( 234 | PathBuf::from("irrelevant.wasm"), 235 | file_path, 236 | backend_detector, 237 | None, 238 | )?; 239 | let annotations = metadata.annotations.unwrap(); 240 | 241 | assert_eq!( 242 | annotations.get(KUBEWARDEN_ANNOTATION_KWCTL_VERSION), 243 | Some(&String::from(env!("CARGO_PKG_VERSION"))), 244 | ); 245 | 246 | Ok(()) 247 | } 248 | 249 | #[test] 250 | fn test_kwctl_usage_is_added_when_annotations_is_none() -> Result<()> { 251 | let dir = tempdir()?; 252 | 253 | let file_path = dir.path().join("metadata.yml"); 254 | let mut file = File::create(file_path.clone())?; 255 | 256 | let raw_metadata = r#" 257 | rules: 258 | - apiGroups: [""] 259 | apiVersions: ["v1"] 260 | resources: ["pods"] 261 | operations: ["CREATE", "UPDATE"] 262 | mutating: false 263 | backgroundAudit: true 264 | executionMode: kubewarden-wapc 265 | "#; 266 | 267 | write!(file, "{}", raw_metadata)?; 268 | 269 | let backend_detector = BackendDetector::new( 270 | mock_rego_policy_detector_false, 271 | mock_protocol_version_detector_v1, 272 | ); 273 | let metadata = prepare_metadata( 274 | PathBuf::from("irrelevant.wasm"), 275 | file_path, 276 | backend_detector, 277 | Some("readme contents"), 278 | )?; 279 | let annotations = metadata.annotations.unwrap(); 280 | 281 | assert_eq!( 282 | annotations.get(KUBEWARDEN_ANNOTATION_POLICY_USAGE), 283 | Some(&String::from("readme contents")), 284 | ); 285 | 286 | Ok(()) 287 | } 288 | 289 | #[test] 290 | fn test_final_metadata_for_a_rego_policy() -> Result<()> { 291 | let dir = tempdir()?; 292 | 293 | let file_path = dir.path().join("metadata.yml"); 294 | let mut file = File::create(file_path.clone())?; 295 | 296 | let raw_metadata = String::from( 297 | r#" 298 | rules: 299 | - apiGroups: [""] 300 | apiVersions: ["v1"] 301 | resources: ["pods"] 302 | operations: ["CREATE", "UPDATE"] 303 | mutating: false 304 | backgroundAudit: true 305 | executionMode: opa 306 | "#, 307 | ); 308 | 309 | write!(file, "{}", raw_metadata)?; 310 | 311 | let backend_detector = BackendDetector::new( 312 | mock_rego_policy_detector_true, 313 | mock_protocol_version_detector_v1, 314 | ); 315 | let metadata = prepare_metadata( 316 | PathBuf::from("irrelevant.wasm"), 317 | file_path, 318 | backend_detector, 319 | None, 320 | ); 321 | assert!(metadata.is_ok()); 322 | assert_eq!( 323 | metadata.unwrap().protocol_version, 324 | Some(ProtocolVersion::Unknown) 325 | ); 326 | 327 | Ok(()) 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /src/backend.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use lazy_static::lazy_static; 3 | use policy_evaluator::{ 4 | evaluation_context::EvaluationContext, policy_evaluator::PolicyExecutionMode, 5 | policy_evaluator_builder::PolicyEvaluatorBuilder, policy_metadata::Metadata, ProtocolVersion, 6 | }; 7 | use semver::{BuildMetadata, Prerelease, Version}; 8 | use std::path::{Path, PathBuf}; 9 | 10 | lazy_static! { 11 | static ref KUBEWARDEN_VERSION: Version = Version::parse(env!("CARGO_PKG_VERSION")).unwrap(); 12 | } 13 | 14 | pub(crate) enum Backend { 15 | Opa, 16 | OpaGatekeeper, 17 | Wasi, 18 | KubewardenWapc(ProtocolVersion), 19 | } 20 | 21 | type KubewardenProtocolDetectorFn = fn(PathBuf) -> Result; 22 | type RegoDetectorFn = fn(PathBuf) -> Result; 23 | 24 | // Looks at the Wasm module pointed by `wasm_path` and return whether it was generated by a Rego 25 | // policy 26 | // 27 | // The code looks at the export symbols offered by the Wasm module. 28 | // Having at least one symbol that starts with the `opa_` prefix leads 29 | // the policy to be considered a Rego-based one. 30 | fn rego_policy_detector(wasm_path: PathBuf) -> Result { 31 | let data: Vec = std::fs::read(wasm_path.clone()) 32 | .map_err(|e| anyhow!("cannot access file {:?}: {}", wasm_path, e))?; 33 | for payload in wasmparser::Parser::new(0).parse_all(&data) { 34 | if let wasmparser::Payload::ExportSection(s) = 35 | payload.map_err(|e| anyhow!("cannot parse WebAssembly file: {}", e))? 36 | { 37 | for export in s { 38 | if export 39 | .map_err(|e| anyhow!("cannot parse WebAssembly export section: {}", e))? 40 | .name 41 | .starts_with("opa_") 42 | { 43 | return Ok(true); 44 | } 45 | } 46 | } 47 | } 48 | 49 | Ok(false) 50 | } 51 | 52 | fn kubewarden_protocol_detector(wasm_path: PathBuf) -> Result { 53 | let eval_ctx = EvaluationContext::default(); 54 | PolicyEvaluatorBuilder::new() 55 | .policy_file(&wasm_path)? 56 | .execution_mode(PolicyExecutionMode::KubewardenWapc) 57 | .build_pre()? 58 | .rehydrate(&eval_ctx)? 59 | .protocol_version() 60 | .map_err(|e| anyhow!("Cannot compute ProtocolVersion used by the policy: {:?}", e)) 61 | } 62 | 63 | pub(crate) struct BackendDetector { 64 | kubewarden_protocol_detector_func: KubewardenProtocolDetectorFn, 65 | rego_detector_func: RegoDetectorFn, 66 | } 67 | 68 | impl Default for BackendDetector { 69 | fn default() -> Self { 70 | BackendDetector { 71 | kubewarden_protocol_detector_func: kubewarden_protocol_detector, 72 | rego_detector_func: rego_policy_detector, 73 | } 74 | } 75 | } 76 | 77 | impl BackendDetector { 78 | #[allow(dead_code)] 79 | /// This method is intended to be used by unit tests 80 | pub(crate) fn new( 81 | rego_detector_func: RegoDetectorFn, 82 | kubewarden_protocol_detector_func: KubewardenProtocolDetectorFn, 83 | ) -> Self { 84 | BackendDetector { 85 | kubewarden_protocol_detector_func, 86 | rego_detector_func, 87 | } 88 | } 89 | 90 | pub(crate) fn is_rego_policy(&self, wasm_path: &Path) -> Result { 91 | (self.rego_detector_func)(wasm_path.to_path_buf()) 92 | .map_err(|e| anyhow!("Rego policy type check failure: {}", e)) 93 | } 94 | 95 | pub(crate) fn detect(&self, wasm_path: PathBuf, metadata: &Metadata) -> Result { 96 | let is_rego_policy = self.is_rego_policy(&wasm_path)?; 97 | match metadata.execution_mode { 98 | PolicyExecutionMode::Wasi => Ok(Backend::Wasi), 99 | PolicyExecutionMode::Opa => { 100 | if is_rego_policy { 101 | Ok(Backend::Opa) 102 | } else { 103 | Err(anyhow!( 104 | "Wrong value inside of policy's metadata for 'executionMode'. The policy has not been created using Rego" 105 | )) 106 | } 107 | } 108 | PolicyExecutionMode::OpaGatekeeper => { 109 | if is_rego_policy { 110 | Ok(Backend::OpaGatekeeper) 111 | } else { 112 | Err(anyhow!( 113 | "Wrong value inside of policy's metadata for 'executionMode'. The policy has not been created using Rego" 114 | )) 115 | } 116 | } 117 | PolicyExecutionMode::KubewardenWapc => { 118 | if is_rego_policy { 119 | Err(anyhow!( 120 | "Wrong value inside of policy's metadata for 'executionMode'. This policy has been created using Rego" 121 | )) 122 | } else { 123 | let protocol_version = (self.kubewarden_protocol_detector_func)(wasm_path) 124 | .map_err(|e| { 125 | anyhow!("Error while detecting Kubewarden protocol version: {:?}", e) 126 | })?; 127 | Ok(Backend::KubewardenWapc(protocol_version)) 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | /// Check if policy server version is compatible with minimum kubewarden 135 | /// version required by the policy 136 | pub fn has_minimum_kubewarden_version(opt_metadata: Option<&Metadata>) -> Result<()> { 137 | if let Some(metadata) = opt_metadata { 138 | if let Some(minimum_kubewarden_version) = &metadata.minimum_kubewarden_version { 139 | let sanitized_minimum_kubewarden_version = Version { 140 | major: minimum_kubewarden_version.major, 141 | minor: minimum_kubewarden_version.minor, 142 | // Kubewarden stack version ignore patch version number 143 | patch: 0, 144 | pre: Prerelease::EMPTY, 145 | build: BuildMetadata::EMPTY, 146 | }; 147 | if *KUBEWARDEN_VERSION < sanitized_minimum_kubewarden_version { 148 | return Err(anyhow!( 149 | "Policy required Kubewarden version {} or greater. But it's running on {}", 150 | sanitized_minimum_kubewarden_version, 151 | KUBEWARDEN_VERSION.to_string(), 152 | )); 153 | } 154 | } 155 | } 156 | Ok(()) 157 | } 158 | 159 | #[cfg(test)] 160 | mod tests { 161 | use super::*; 162 | 163 | fn mock_protocol_version_detector_v1(_wasm_path: PathBuf) -> Result { 164 | Ok(ProtocolVersion::V1) 165 | } 166 | 167 | fn mock_rego_policy_detector_true(_wasm_path: PathBuf) -> Result { 168 | Ok(true) 169 | } 170 | 171 | fn mock_rego_policy_detector_false(_wasm_path: PathBuf) -> Result { 172 | Ok(false) 173 | } 174 | 175 | #[test] 176 | fn test_execution_mode_cannot_be_kubewarden_for_a_rego_policy() { 177 | let metadata = Metadata { 178 | execution_mode: PolicyExecutionMode::KubewardenWapc, 179 | ..Default::default() 180 | }; 181 | 182 | let backend_detector = BackendDetector::new( 183 | mock_rego_policy_detector_true, 184 | mock_protocol_version_detector_v1, 185 | ); 186 | let backend = backend_detector.detect(PathBuf::from("irrelevant.wasm"), &metadata); 187 | assert!(backend.is_err()); 188 | } 189 | 190 | #[test] 191 | fn test_execution_mode_cannot_be_opa_or_gatekeeper_for_a_kubewarden_policy() { 192 | for execution_mode in [PolicyExecutionMode::Opa, PolicyExecutionMode::OpaGatekeeper] { 193 | let metadata = Metadata { 194 | execution_mode, 195 | ..Default::default() 196 | }; 197 | 198 | let backend_detector = BackendDetector::new( 199 | mock_rego_policy_detector_false, 200 | mock_protocol_version_detector_v1, 201 | ); 202 | let backend = backend_detector.detect(PathBuf::from("irrelevant.wasm"), &metadata); 203 | assert!(backend.is_err()); 204 | } 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /src/bench.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use tiny_bench::{bench_with_configuration_labeled, BenchmarkConfig}; 3 | use tracing::error; 4 | 5 | use crate::run; 6 | 7 | pub(crate) struct PullAndBenchSettings { 8 | pub pull_and_run_settings: run::PullAndRunSettings, 9 | pub benchmark_cfg: BenchmarkConfig, 10 | } 11 | 12 | pub(crate) async fn pull_and_bench(cfg: &PullAndBenchSettings) -> Result<()> { 13 | let run_env = run::prepare_run_env(&cfg.pull_and_run_settings).await?; 14 | let mut policy_evaluator = run_env.policy_evaluator; 15 | let mut callback_handler = run_env.callback_handler; 16 | let callback_handler_shutdown_channel_tx = run_env.callback_handler_shutdown_channel_tx; 17 | let request = run_env.request; 18 | 19 | // validate the settings given by the user 20 | let settings_validation_response = policy_evaluator.validate_settings(&run_env.policy_settings); 21 | if !settings_validation_response.valid { 22 | println!("{}", serde_json::to_string(&settings_validation_response)?); 23 | return Err(anyhow!( 24 | "Provided settings are not valid: {:?}", 25 | settings_validation_response.message 26 | )); 27 | } 28 | 29 | // Spawn the tokio task used by the CallbackHandler 30 | let callback_handle = tokio::spawn(async move { 31 | callback_handler.loop_eval().await; 32 | }); 33 | 34 | // validate the settings given by the user 35 | let settings_validation_response = policy_evaluator.validate_settings(&run_env.policy_settings); 36 | if !settings_validation_response.valid { 37 | println!("{}", serde_json::to_string(&settings_validation_response)?); 38 | return Err(anyhow!( 39 | "Provided settings are not valid: {:?}", 40 | settings_validation_response.message 41 | )); 42 | } 43 | 44 | bench_with_configuration_labeled("validate_settings", &cfg.benchmark_cfg, || { 45 | let _settings_validation_response = 46 | policy_evaluator.validate_settings(&run_env.policy_settings); 47 | }); 48 | 49 | tokio::task::block_in_place(|| { 50 | bench_with_configuration_labeled("validate", &cfg.benchmark_cfg, || { 51 | let _response = policy_evaluator.validate(request.clone(), &run_env.policy_settings); 52 | }); 53 | }); 54 | 55 | // The evaluation is done, we can shutdown the tokio task that is running 56 | // the CallbackHandler 57 | if callback_handler_shutdown_channel_tx.send(()).is_err() { 58 | error!("Cannot shut down the CallbackHandler task"); 59 | } else if let Err(e) = callback_handle.await { 60 | error!( 61 | error = e.to_string().as_str(), 62 | "Error waiting for the CallbackHandler task" 63 | ); 64 | } 65 | 66 | Ok(()) 67 | } 68 | -------------------------------------------------------------------------------- /src/callback_handler/mod.rs: -------------------------------------------------------------------------------- 1 | use crate::run::{HostCapabilitiesMode, PullAndRunSettings}; 2 | use anyhow::Result; 3 | use policy_evaluator::{callback_requests::CallbackRequest, kube}; 4 | use std::path::PathBuf; 5 | use tokio::sync::{mpsc, oneshot}; 6 | 7 | use self::proxy::CallbackHandlerProxy; 8 | 9 | mod proxy; 10 | 11 | #[derive(Clone)] 12 | pub(crate) enum ProxyMode { 13 | Record { destination: PathBuf }, 14 | Replay { source: PathBuf }, 15 | } 16 | 17 | /// This is an abstraction over the callback_handler provided by the 18 | /// policy_evaluator crate. 19 | /// The goal is to allow kwctl to have a proxy handler, that can 20 | /// record and reply any kind of policy <-> host capability exchange 21 | pub(crate) enum CallbackHandler { 22 | Direct(policy_evaluator::callback_handler::CallbackHandler), 23 | Proxy(proxy::CallbackHandlerProxy), 24 | } 25 | 26 | impl CallbackHandler { 27 | pub async fn new( 28 | cfg: &PullAndRunSettings, 29 | kube_client: Option, 30 | shutdown_channel: oneshot::Receiver<()>, 31 | ) -> Result { 32 | match &cfg.host_capabilities_mode { 33 | HostCapabilitiesMode::Proxy(proxy_mode) => { 34 | new_proxy(proxy_mode, cfg, kube_client, shutdown_channel).await 35 | } 36 | HostCapabilitiesMode::Direct => { 37 | new_transparent(cfg, kube_client, shutdown_channel).await 38 | } 39 | } 40 | } 41 | 42 | pub async fn loop_eval(&mut self) { 43 | match self { 44 | CallbackHandler::Direct(direct) => direct.loop_eval().await, 45 | CallbackHandler::Proxy(proxy) => proxy.loop_eval().await, 46 | } 47 | } 48 | 49 | pub fn sender_channel(&self) -> mpsc::Sender { 50 | match self { 51 | CallbackHandler::Direct(direct) => direct.sender_channel(), 52 | CallbackHandler::Proxy(proxy) => proxy.sender_channel(), 53 | } 54 | } 55 | } 56 | 57 | async fn new_proxy( 58 | mode: &ProxyMode, 59 | cfg: &PullAndRunSettings, 60 | kube_client: Option, 61 | shutdown_channel: oneshot::Receiver<()>, 62 | ) -> Result { 63 | let proxy = CallbackHandlerProxy::new( 64 | mode, 65 | shutdown_channel, 66 | cfg.sources.clone(), 67 | cfg.sigstore_trust_root.clone(), 68 | kube_client, 69 | ) 70 | .await?; 71 | 72 | Ok(CallbackHandler::Proxy(proxy)) 73 | } 74 | 75 | async fn new_transparent( 76 | cfg: &PullAndRunSettings, 77 | kube_client: Option, 78 | shutdown_channel: oneshot::Receiver<()>, 79 | ) -> Result { 80 | let mut callback_handler_builder = 81 | policy_evaluator::callback_handler::CallbackHandlerBuilder::new(shutdown_channel) 82 | .registry_config(cfg.sources.clone()) 83 | .trust_root(cfg.sigstore_trust_root.clone()); 84 | if let Some(kc) = kube_client { 85 | callback_handler_builder = callback_handler_builder.kube_client(kc); 86 | } 87 | 88 | let real_callback_handler = callback_handler_builder.build().await?; 89 | 90 | Ok(CallbackHandler::Direct(real_callback_handler)) 91 | } 92 | -------------------------------------------------------------------------------- /src/completions.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use clap_complete::{ 3 | generate, 4 | shells::{Bash, Elvish, Fish, PowerShell, Zsh}, 5 | }; 6 | use std::io; 7 | 8 | pub(crate) fn completions(shell: &str) -> Result<()> { 9 | let mut app = crate::cli::build_cli(); 10 | 11 | match shell { 12 | "bash" => { 13 | generate(Bash, &mut app, "kwctl", &mut io::stdout()); 14 | Ok(()) 15 | } 16 | "fish" => { 17 | generate(Fish, &mut app, "kwctl", &mut io::stdout()); 18 | Ok(()) 19 | } 20 | "zsh" => { 21 | generate(Zsh, &mut app, "kwctl", &mut io::stdout()); 22 | Ok(()) 23 | } 24 | "elvish" => { 25 | generate(Elvish, &mut app, "kwctl", &mut io::stdout()); 26 | Ok(()) 27 | } 28 | "powershell" => { 29 | generate(PowerShell, &mut app, "kwctl", &mut io::stdout()); 30 | Ok(()) 31 | } 32 | unknown => Err(anyhow!("Unknown shell '{}'", unknown)), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/info.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use clap::crate_version; 3 | use itertools::Itertools; 4 | use policy_evaluator::{ 5 | burrego, 6 | policy_fetcher::store::{Store, DEFAULT_ROOT}, 7 | }; 8 | 9 | pub(crate) fn info() -> Result<()> { 10 | let builtins: String = burrego::get_builtins() 11 | .keys() 12 | .sorted() 13 | .map(|builtin| format!(" - {builtin}")) 14 | .join("\n"); 15 | 16 | let store = Store::default(); 17 | 18 | println!( 19 | r#"kwctl version: {} 20 | 21 | Open Policy Agent/Gatekeeper implemented builtins: 22 | {} 23 | 24 | Policy store: {} 25 | Config directory: {} 26 | kwctl cache directory: {} 27 | "#, 28 | crate_version!(), 29 | builtins, 30 | store.root.to_string_lossy(), 31 | DEFAULT_ROOT.config_dir().to_string_lossy(), 32 | crate::scaffold::DEFAULT_KWCTL_CACHE.to_string_lossy(), 33 | ); 34 | 35 | Ok(()) 36 | } 37 | -------------------------------------------------------------------------------- /src/inspect.rs: -------------------------------------------------------------------------------- 1 | use crate::{Registry, Sources}; 2 | use anyhow::{anyhow, Result}; 3 | use is_terminal::IsTerminal; 4 | use policy_evaluator::{ 5 | constants::*, 6 | policy_evaluator::PolicyExecutionMode, 7 | policy_fetcher::{ 8 | oci_client::{ 9 | manifest::{OciImageManifest, OciManifest}, 10 | secrets::RegistryAuth, 11 | }, 12 | sigstore::{ 13 | cosign::{ClientBuilder, CosignCapabilities}, 14 | registry::{oci_reference::OciReference, Auth, ClientConfig}, 15 | }, 16 | }, 17 | policy_metadata::Metadata, 18 | }; 19 | use prettytable::{format::FormatBuilder, Table}; 20 | use std::io::{self}; 21 | use std::{collections::HashMap, convert::TryFrom, str::FromStr}; 22 | use termimad::{terminal_size, FmtText, MadSkin}; 23 | 24 | pub(crate) async fn inspect( 25 | uri_or_sha_prefix: &str, 26 | output: OutputType, 27 | sources: Option, 28 | no_color: bool, 29 | no_signatures: bool, 30 | ) -> Result<()> { 31 | let uri = crate::utils::map_path_to_uri(uri_or_sha_prefix)?; 32 | let wasm_path = crate::utils::wasm_path(&uri)?; 33 | let metadata_printer = MetadataPrinter::from(&output); 34 | 35 | let metadata = Metadata::from_path(&wasm_path) 36 | .map_err(|e| anyhow!("Error parsing policy metadata: {}", e))?; 37 | 38 | match metadata { 39 | Some(metadata) => metadata_printer.print(&metadata, no_color)?, 40 | None => return Err(anyhow!( 41 | "No Kubewarden metadata found inside of '{}'.\nPolicies can be annotated with the `kwctl annotate` command.", 42 | uri 43 | )), 44 | }; 45 | 46 | if no_signatures { 47 | return Ok(()); 48 | } 49 | 50 | let signatures = fetch_signatures_manifest(&uri, sources).await; 51 | match signatures { 52 | Ok(signatures) => { 53 | if let Some(signatures) = signatures { 54 | let sigstore_printer = SignaturesPrinter::from(&output); 55 | sigstore_printer.print(&signatures); 56 | } 57 | } 58 | Err(error) => { 59 | println!(); 60 | if error 61 | .to_string() 62 | .as_str() 63 | .starts_with("OCI API error: manifest unknown on") 64 | { 65 | println!("No sigstore signatures found"); 66 | } else { 67 | println!("Cannot determine if the policy has been signed. There was an error while attempting to fetch its signatures from the remote registry: {error} ") 68 | } 69 | } 70 | } 71 | 72 | Ok(()) 73 | } 74 | 75 | pub(crate) enum OutputType { 76 | Yaml, 77 | Pretty, 78 | } 79 | 80 | impl TryFrom> for OutputType { 81 | type Error = anyhow::Error; 82 | 83 | fn try_from(value: Option<&str>) -> Result { 84 | match value { 85 | Some("yaml") => Ok(Self::Yaml), 86 | None => Ok(Self::Pretty), 87 | Some(unknown) => Err(anyhow!("Invalid output format '{}'", unknown)), 88 | } 89 | } 90 | } 91 | 92 | enum MetadataPrinter { 93 | Yaml, 94 | Pretty, 95 | } 96 | 97 | impl From<&OutputType> for MetadataPrinter { 98 | fn from(output_type: &OutputType) -> Self { 99 | match output_type { 100 | OutputType::Yaml => Self::Yaml, 101 | OutputType::Pretty => Self::Pretty, 102 | } 103 | } 104 | } 105 | 106 | impl MetadataPrinter { 107 | fn print(&self, metadata: &Metadata, no_color: bool) -> Result<()> { 108 | match self { 109 | MetadataPrinter::Yaml => { 110 | let metadata_yaml = serde_yaml::to_string(metadata)?; 111 | print!("{metadata_yaml}"); 112 | Ok(()) 113 | } 114 | MetadataPrinter::Pretty => { 115 | self.print_metadata_generic_info(metadata)?; 116 | println!(); 117 | self.print_metadata_rules(metadata, no_color)?; 118 | println!(); 119 | if !metadata.context_aware_resources.is_empty() { 120 | self.print_metadata_context_aware_resources(metadata, no_color)?; 121 | println!(); 122 | } 123 | self.print_metadata_usage(metadata, no_color); 124 | Ok(()) 125 | } 126 | } 127 | } 128 | 129 | fn annotation_to_row_key(&self, text: &str) -> String { 130 | let mut out = String::from(text); 131 | out.push(':'); 132 | String::from(out.trim_start_matches("io.kubewarden.policy.")) 133 | } 134 | 135 | fn print_metadata_generic_info(&self, metadata: &Metadata) -> Result<()> { 136 | let protocol_version = metadata 137 | .protocol_version 138 | .clone() 139 | .ok_or_else(|| anyhow!("Invalid policy: protocol_version not defined"))?; 140 | 141 | let pretty_annotations = [ 142 | KUBEWARDEN_ANNOTATION_POLICY_TITLE, 143 | KUBEWARDEN_ANNOTATION_POLICY_DESCRIPTION, 144 | KUBEWARDEN_ANNOTATION_POLICY_AUTHOR, 145 | KUBEWARDEN_ANNOTATION_POLICY_URL, 146 | KUBEWARDEN_ANNOTATION_POLICY_SOURCE, 147 | KUBEWARDEN_ANNOTATION_POLICY_LICENSE, 148 | ]; 149 | let mut annotations = metadata.annotations.clone().unwrap_or_default(); 150 | 151 | let mut table = Table::new(); 152 | table.set_format(FormatBuilder::new().padding(0, 1).build()); 153 | 154 | table.add_row(row![Fmbl -> "Details"]); 155 | for annotation in pretty_annotations.iter() { 156 | if let Some(value) = annotations.get(&String::from(*annotation)) { 157 | table.add_row(row![Fgbl -> self.annotation_to_row_key(annotation), d -> value]); 158 | annotations.remove(&String::from(*annotation)); 159 | } 160 | } 161 | table.add_row(row![Fgbl -> "mutating:", metadata.mutating]); 162 | table.add_row(row![Fgbl -> "background audit support:", metadata.background_audit]); 163 | table.add_row(row![Fgbl -> "context aware:", !metadata.context_aware_resources.is_empty()]); 164 | table.add_row(row![Fgbl -> "policy type:", metadata.policy_type]); 165 | table.add_row(row![Fgbl -> "execution mode:", metadata.execution_mode]); 166 | if metadata.execution_mode == PolicyExecutionMode::KubewardenWapc { 167 | table.add_row(row![Fgbl -> "protocol version:", protocol_version]); 168 | } 169 | if let Some(minimum_kubewarden_version) = &metadata.minimum_kubewarden_version { 170 | table.add_row(row![Fgbl -> "minimum kubewarden version:", minimum_kubewarden_version]); 171 | } 172 | 173 | let _usage = annotations.remove(KUBEWARDEN_ANNOTATION_POLICY_USAGE); 174 | if !annotations.is_empty() { 175 | table.add_row(row![]); 176 | table.add_row(row![Fmbl -> "Annotations"]); 177 | for (annotation, value) in annotations.iter() { 178 | table.add_row(row![Fgbl -> annotation, d -> value]); 179 | } 180 | } 181 | table.printstd(); 182 | Ok(()) 183 | } 184 | 185 | fn print_metadata_rules(&self, metadata: &Metadata, no_color: bool) -> Result<()> { 186 | let rules_yaml = serde_yaml::to_string(&metadata.rules)?; 187 | 188 | // Quick hack to print a colorized "Rules" section, with the same 189 | // style as the other sections we print 190 | let mut table = Table::new(); 191 | table.set_format(FormatBuilder::new().padding(0, 1).build()); 192 | table.add_row(row![Fmbl -> "Rules"]); 193 | table.printstd(); 194 | 195 | let text = format!("```yaml\n{rules_yaml}```"); 196 | self.render_markdown(&text, no_color); 197 | Ok(()) 198 | } 199 | 200 | fn print_metadata_context_aware_resources( 201 | &self, 202 | metadata: &Metadata, 203 | no_color: bool, 204 | ) -> Result<()> { 205 | let resources_yaml = serde_yaml::to_string(&metadata.context_aware_resources)?; 206 | 207 | // Quick hack to print a colorized "Context Aware" section, with the same 208 | // style as the other sections we print 209 | let mut table = Table::new(); 210 | table.set_format(FormatBuilder::new().padding(0, 1).build()); 211 | table.add_row(row![Fmbl -> "Context Aware"]); 212 | table.printstd(); 213 | 214 | println!( 215 | "The policy requires access to the following Kubernetes resources at evaluation time:" 216 | ); 217 | 218 | let text = format!("```yaml\n{resources_yaml}```"); 219 | self.render_markdown(&text, no_color); 220 | println!("To avoid abuses, review carefully what the policy requires access to."); 221 | 222 | Ok(()) 223 | } 224 | 225 | fn print_metadata_usage(&self, metadata: &Metadata, no_color: bool) { 226 | let usage = match metadata.annotations.clone() { 227 | None => None, 228 | Some(annotations) => annotations 229 | .get(KUBEWARDEN_ANNOTATION_POLICY_USAGE) 230 | .map(String::from), 231 | }; 232 | 233 | if usage.is_none() { 234 | return; 235 | } 236 | 237 | // Quick hack to print a colorized "Rules" section, with the same 238 | // style as the other sections we print 239 | let mut table = Table::new(); 240 | table.set_format(FormatBuilder::new().padding(0, 1).build()); 241 | table.add_row(row![Fmbl -> "Usage"]); 242 | table.printstd(); 243 | 244 | let fenced_usage = format!("---\n{}\n---", usage.unwrap()); 245 | self.render_markdown(&fenced_usage, no_color); 246 | } 247 | 248 | fn render_markdown(&self, text: &str, no_color: bool) { 249 | let mut skin: MadSkin = if no_color || !io::stdout().is_terminal() { 250 | MadSkin::no_style() 251 | } else { 252 | MadSkin::default() 253 | }; 254 | skin.headers[0].align = termimad::Alignment::Left; 255 | 256 | let (mut width, _) = terminal_size(); 257 | if width > 120 { 258 | // limit width to print nicer rulers 259 | width = 120; 260 | } 261 | let fmt_text = FmtText::from_text(&skin, text.into(), Some(width as usize)); 262 | print!("{}", fmt_text); 263 | } 264 | } 265 | 266 | enum SignaturesPrinter { 267 | Yaml, 268 | Pretty, 269 | } 270 | 271 | impl From<&OutputType> for SignaturesPrinter { 272 | fn from(output_type: &OutputType) -> Self { 273 | match output_type { 274 | OutputType::Yaml => Self::Yaml, 275 | OutputType::Pretty => Self::Pretty, 276 | } 277 | } 278 | } 279 | 280 | impl SignaturesPrinter { 281 | fn print(&self, signatures: &OciImageManifest) { 282 | match self { 283 | SignaturesPrinter::Yaml => { 284 | let mut doc_entry: HashMap = HashMap::new(); 285 | doc_entry.insert("signatures".to_string(), signatures); 286 | 287 | let signatures_yaml = serde_yaml::to_string(&doc_entry); 288 | if let Ok(signatures_yaml) = signatures_yaml { 289 | print!("{signatures_yaml}") 290 | } 291 | } 292 | SignaturesPrinter::Pretty => { 293 | println!(); 294 | println!("Sigstore signatures"); 295 | println!(); 296 | 297 | for layer in &signatures.layers { 298 | let mut table = Table::new(); 299 | table.set_format(FormatBuilder::new().padding(0, 1).build()); 300 | table.add_row(row![Fmbl -> "Digest: ", layer.digest]); 301 | table.add_row(row![Fmbl -> "Media type: ", layer.media_type]); 302 | table.add_row(row![Fmbl -> "Size: ", layer.size]); 303 | if let Some(annotations) = &layer.annotations { 304 | table.add_row(row![Fmbl -> "Annotations"]); 305 | for annotation in annotations.iter() { 306 | table.add_row(row![Fgbl -> annotation.0, annotation.1]); 307 | } 308 | } 309 | table.printstd(); 310 | println!(); 311 | } 312 | } 313 | } 314 | } 315 | } 316 | 317 | async fn fetch_signatures_manifest( 318 | uri: &str, 319 | sources: Option, 320 | ) -> Result> { 321 | let registry = Registry::new(); 322 | let client_config: ClientConfig = sources.clone().unwrap_or_default().into(); 323 | let mut client = ClientBuilder::default() 324 | .with_oci_client_config(client_config) 325 | .build()?; 326 | let image_name = uri 327 | .strip_prefix("registry://") 328 | .ok_or_else(|| anyhow!("invalid uri"))?; 329 | let image_ref = OciReference::from_str(image_name)?; 330 | let auth = match Registry::auth(image_name) { 331 | RegistryAuth::Anonymous => Auth::Anonymous, 332 | RegistryAuth::Basic(username, password) => Auth::Basic(username, password), 333 | }; 334 | 335 | let (cosign_signature_image, _source_image_digest) = 336 | client.triangulate(&image_ref, &auth).await?; 337 | 338 | let manifest = registry 339 | .manifest(&cosign_signature_image.whole(), sources.as_ref()) 340 | .await?; 341 | 342 | match manifest { 343 | OciManifest::Image(img) => Ok(Some(img)), 344 | _ => Ok(None), 345 | } 346 | } 347 | -------------------------------------------------------------------------------- /src/load.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use flate2::read::GzDecoder; 3 | use policy_evaluator::policy_fetcher::store::Store; 4 | use std::fs::File; 5 | use tar::Archive; 6 | 7 | // load policies inside the tarball provided by source_path into the default store 8 | pub(crate) fn load(source_path: &str) -> Result<()> { 9 | let default_store = Store::default(); 10 | let destination_path = default_store.root; 11 | let tar_gz = 12 | File::open(source_path).map_err(|e| anyhow!("cannot open file {}: {}", source_path, e))?; 13 | let tar = GzDecoder::new(tar_gz); 14 | let mut archive = Archive::new(tar); 15 | archive 16 | .unpack(destination_path) 17 | .map_err(|e| anyhow!("cannot unpack file {}: {}", source_path, e))?; 18 | 19 | Ok(()) 20 | } 21 | -------------------------------------------------------------------------------- /src/policies.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use policy_evaluator::{ 3 | policy_fetcher::{policy::Policy, store::Store}, 4 | policy_metadata::Metadata as PolicyMetadata, 5 | }; 6 | use prettytable::{format, Table}; 7 | 8 | pub(crate) fn list() -> Result<()> { 9 | if policy_list()?.is_empty() { 10 | return Ok(()); 11 | } 12 | let mut table = Table::new(); 13 | table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE); 14 | table.set_titles(row![ 15 | "Policy", 16 | "Mutating", 17 | "Context aware", 18 | "SHA-256", 19 | "Size" 20 | ]); 21 | for policy in policy_list()? { 22 | let (mutating, context_aware) = if let Some(policy_metadata) = 23 | PolicyMetadata::from_path(&policy.local_path) 24 | .map_err(|e| anyhow!("error processing metadata of policy {}: {:?}", policy, e))? 25 | { 26 | let mutating = if policy_metadata.mutating { 27 | "yes" 28 | } else { 29 | "no" 30 | }; 31 | 32 | let context_aware = if policy_metadata.context_aware_resources.is_empty() { 33 | "no" 34 | } else { 35 | "yes" 36 | }; 37 | 38 | (mutating, context_aware) 39 | } else { 40 | ("unknown", "no") 41 | }; 42 | 43 | let mut sha256sum = policy.digest()?; 44 | sha256sum.truncate(12); 45 | 46 | let policy_filesystem_metadata = std::fs::metadata(&policy.local_path)?; 47 | 48 | table.add_row(row![ 49 | format!("{policy}"), 50 | mutating, 51 | context_aware, 52 | sha256sum, 53 | humansize::format_size(policy_filesystem_metadata.len(), humansize::DECIMAL), 54 | ]); 55 | } 56 | table.printstd(); 57 | Ok(()) 58 | } 59 | 60 | fn policy_list() -> Result> { 61 | Store::default().list().map_err(anyhow::Error::new) 62 | } 63 | -------------------------------------------------------------------------------- /src/pull.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use anyhow::Result; 4 | use indicatif::{ProgressBar, ProgressStyle}; 5 | use policy_evaluator::policy_fetcher::{ 6 | fetch_policy, policy::Policy, sources::Sources, PullDestination, 7 | }; 8 | 9 | pub(crate) async fn pull( 10 | uri: &str, 11 | sources: Option<&Sources>, 12 | destination: PullDestination, 13 | ) -> Result { 14 | let pb = ProgressBar::new_spinner(); 15 | pb.set_style( 16 | ProgressStyle::default_spinner() 17 | .template("{spinner:.green} {msg}") 18 | .expect("cannot set spinner template"), 19 | ); 20 | pb.set_message(format!("Pulling policy from {}", uri)); 21 | pb.enable_steady_tick(Duration::from_millis(100)); 22 | 23 | let result = fetch_policy(uri, destination, sources) 24 | .await 25 | .map_err(anyhow::Error::new); 26 | 27 | match &result { 28 | Ok(_) => pb.finish_with_message(format!("Successfully pulled policy from {}", uri)), 29 | Err(e) => pb.finish_with_message(format!("Failed to pull policy: {}", e)), 30 | } 31 | 32 | result 33 | } 34 | -------------------------------------------------------------------------------- /src/push.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::BTreeMap, fs, path::PathBuf}; 2 | 3 | use anyhow::{anyhow, Result}; 4 | use policy_evaluator::{ 5 | constants::KUBEWARDEN_ANNOTATION_POLICY_SOURCE, 6 | policy_fetcher::{ 7 | oci_client::annotations::ORG_OPENCONTAINERS_IMAGE_SOURCE, registry::Registry, 8 | sources::Sources, 9 | }, 10 | policy_metadata::Metadata, 11 | }; 12 | use tracing::{debug, warn}; 13 | 14 | use crate::backend::BackendDetector; 15 | 16 | pub(crate) async fn push( 17 | wasm_path: PathBuf, 18 | uri: &str, 19 | sources: Option<&Sources>, 20 | force: bool, 21 | ) -> Result { 22 | let metadata = Metadata::from_path(&wasm_path)?; 23 | 24 | if metadata.is_none() { 25 | if force { 26 | let backend_detector = BackendDetector::default(); 27 | if can_be_force_pushed_without_metadata(backend_detector, wasm_path.clone())? { 28 | eprintln!("Warning: pushing a non-annotated policy!"); 29 | } else { 30 | return Err(anyhow!("Rego policies cannot be pushed without metadata")); 31 | } 32 | } else { 33 | return Err(anyhow!("Cannot push a policy that is not annotated. Use `annotate` command or `push --force`")); 34 | } 35 | } 36 | 37 | let annotations = metadata.and_then(|meta| meta.annotations.map(build_oci_annotations)); 38 | 39 | let policy = fs::read(&wasm_path).map_err(|e| anyhow!("Cannot open policy file: {:?}", e))?; 40 | Registry::new() 41 | .push(&policy, uri, sources, annotations) 42 | .await 43 | .map_err(anyhow::Error::new) 44 | } 45 | 46 | fn can_be_force_pushed_without_metadata( 47 | backend_detector: BackendDetector, 48 | wasm_path: PathBuf, 49 | ) -> Result { 50 | let is_rego = backend_detector 51 | .is_rego_policy(&wasm_path) 52 | .map_err(|e| anyhow!("Cannot understand if the policy is based on Rego: {:?}", e))?; 53 | 54 | Ok(!is_rego) 55 | } 56 | 57 | /// Augment the annotations with the `org.opencontainers.image.source` 58 | /// annotation, if the `io.kubewarden.policy.source` annotation is present. 59 | fn build_oci_annotations(annotations: BTreeMap) -> BTreeMap { 60 | // filter all the multi-line annotations, they are not supported by the OCI spec 61 | let mut annotations: BTreeMap = annotations 62 | .iter() 63 | .filter(|(k, v)| { 64 | let keep = v.lines().count() <= 1; 65 | if !keep { 66 | warn!( 67 | annotation = k, 68 | "annotation is a multi-line string, it will be removed from the OCI manifest", 69 | ); 70 | } 71 | keep 72 | }) 73 | .map(|(k, v)| (k.to_owned(), v.trim().to_owned())) 74 | .collect(); 75 | 76 | if let Some(source) = annotations.get(KUBEWARDEN_ANNOTATION_POLICY_SOURCE) { 77 | if !annotations.contains_key(ORG_OPENCONTAINERS_IMAGE_SOURCE) { 78 | annotations.insert( 79 | ORG_OPENCONTAINERS_IMAGE_SOURCE.to_string(), 80 | source.to_owned(), 81 | ); 82 | } 83 | } 84 | 85 | debug!("OCI annotations: {:?}", annotations); 86 | 87 | annotations 88 | } 89 | 90 | #[cfg(test)] 91 | mod tests { 92 | use super::*; 93 | use policy_evaluator::constants::{ 94 | KUBEWARDEN_ANNOTATION_POLICY_DESCRIPTION, KUBEWARDEN_ANNOTATION_POLICY_URL, 95 | KUBEWARDEN_ANNOTATION_POLICY_USAGE, 96 | }; 97 | 98 | #[test] 99 | fn test_build_oci_annotations_propagate_policy_source() { 100 | let policy_source = "example.com"; 101 | let policy_url = "http://example.com"; 102 | 103 | let mut annotations = BTreeMap::new(); 104 | annotations.insert( 105 | KUBEWARDEN_ANNOTATION_POLICY_SOURCE.to_string(), 106 | policy_source.to_string(), 107 | ); 108 | annotations.insert( 109 | KUBEWARDEN_ANNOTATION_POLICY_URL.to_string(), 110 | policy_url.to_string(), 111 | ); 112 | annotations.insert( 113 | KUBEWARDEN_ANNOTATION_POLICY_USAGE.to_string(), 114 | "this is a multi-line\nstring".to_string(), 115 | ); 116 | annotations.insert( 117 | KUBEWARDEN_ANNOTATION_POLICY_DESCRIPTION.to_string(), 118 | "this is a line that ends with a line terminator\n".to_string(), 119 | ); 120 | 121 | let actual = build_oci_annotations(annotations); 122 | 123 | assert!(!actual.contains_key(KUBEWARDEN_ANNOTATION_POLICY_USAGE)); 124 | assert_eq!( 125 | actual.get(ORG_OPENCONTAINERS_IMAGE_SOURCE).unwrap(), 126 | policy_source 127 | ); 128 | assert_eq!( 129 | actual.get(KUBEWARDEN_ANNOTATION_POLICY_URL).unwrap(), 130 | policy_url, 131 | ); 132 | assert_eq!( 133 | actual.get(KUBEWARDEN_ANNOTATION_POLICY_SOURCE).unwrap(), 134 | policy_source 135 | ); 136 | assert_eq!( 137 | actual 138 | .get(KUBEWARDEN_ANNOTATION_POLICY_DESCRIPTION) 139 | .unwrap(), 140 | "this is a line that ends with a line terminator", 141 | ); 142 | } 143 | 144 | #[test] 145 | fn test_build_oci_annotations_do_not_overwrite_oci_source_if_already_set() { 146 | let policy_source = "example.com"; 147 | let oci_source = "oci.org"; 148 | 149 | let mut annotations = BTreeMap::new(); 150 | annotations.insert( 151 | KUBEWARDEN_ANNOTATION_POLICY_SOURCE.to_string(), 152 | policy_source.to_string(), 153 | ); 154 | annotations.insert( 155 | KUBEWARDEN_ANNOTATION_POLICY_USAGE.to_string(), 156 | "this is a multi-line\nstring".to_string(), 157 | ); 158 | annotations.insert( 159 | ORG_OPENCONTAINERS_IMAGE_SOURCE.to_string(), 160 | oci_source.to_string(), 161 | ); 162 | 163 | let actual = build_oci_annotations(annotations); 164 | assert!(!actual.contains_key(KUBEWARDEN_ANNOTATION_POLICY_USAGE)); 165 | assert_eq!( 166 | actual.get(ORG_OPENCONTAINERS_IMAGE_SOURCE).unwrap(), 167 | oci_source 168 | ); 169 | assert_eq!( 170 | actual.get(KUBEWARDEN_ANNOTATION_POLICY_SOURCE).unwrap(), 171 | policy_source 172 | ); 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /src/rm.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use policy_evaluator::policy_fetcher::store::{PolicyPath, Store}; 3 | use std::path::PathBuf; 4 | 5 | use crate::utils::LookupError; 6 | 7 | pub(crate) fn rm(uri_or_sha_prefix: &str) -> Result<()> { 8 | let uri = crate::utils::get_uri(&uri_or_sha_prefix.to_string())?; 9 | 10 | let store = Store::default(); 11 | 12 | if store.get_policy_by_uri(&uri)?.is_none() { 13 | return Err(anyhow!(LookupError::PolicyMissing(uri))); 14 | } 15 | 16 | let policy_path = store.policy_full_path(&uri, PolicyPath::PrefixAndFilename)?; 17 | std::fs::remove_file(&policy_path) 18 | .map_err(|err| anyhow!("could not delete policy {}: {}", uri, err))?; 19 | 20 | // Given a policy in the store, try to cleanup all intermediate 21 | // directories up to the store root, from the innermost to the 22 | // outermost. We don't care about errors: we just try to `rmdir` 23 | // every directory up to the store root in reverse order to clean 24 | // up as much as possible -- if possible. 25 | { 26 | let mut prefix = store.root.clone(); 27 | let policy_leading_store_components = policy_path 28 | .iter() 29 | .map(|component| { 30 | prefix = prefix.join(component); 31 | prefix.clone() 32 | }) 33 | .collect::>(); 34 | 35 | policy_leading_store_components 36 | .iter() 37 | .rev() 38 | .skip(1) // policy name 39 | .take(policy_leading_store_components.len() - store.root.components().count()) 40 | .for_each(|store_component| { 41 | #[allow(unused_must_use)] 42 | { 43 | // try to clean up empty dirs. Ignore errors. 44 | std::fs::remove_dir(store.root.join(store_component)); 45 | } 46 | }); 47 | } 48 | 49 | Ok(()) 50 | } 51 | -------------------------------------------------------------------------------- /src/save.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use flate2::write::GzEncoder; 3 | use flate2::Compression; 4 | use policy_evaluator::policy_fetcher::store::{PolicyPath, Store}; 5 | use std::fs::File; 6 | 7 | // saves all policies in a tarball with the name provided as output. 8 | // policies must be inside the default store. 9 | pub(crate) fn save(policies: Vec<&String>, output: &str) -> Result<()> { 10 | let tar_gz = 11 | File::create(output).map_err(|e| anyhow!("cannot create file {}: {}", output, e))?; 12 | let enc = GzEncoder::new(tar_gz, Compression::default()); 13 | let mut tar = tar::Builder::new(enc); 14 | 15 | for policy in policies { 16 | let store = Store::default(); 17 | let uri = crate::utils::map_path_to_uri(policy.as_str())?; 18 | let wasm_path = crate::utils::wasm_path(&uri) 19 | .map_err(|e| anyhow!("cannot find policy {}: {}", policy, e))?; 20 | let mut file = File::open(wasm_path) 21 | .map_err(|e| anyhow!("cannot open policy file {}: {}", policy, e))?; 22 | let policy_path = store 23 | .policy_path(&uri, PolicyPath::PrefixAndFilename) 24 | .map_err(|e| anyhow!("cannot find path for policy {}: {}", policy, e))?; 25 | tar.append_file(policy_path, &mut file) 26 | .map_err(|e| anyhow!("cannot append policy {} to tar file: {}", policy, e))?; 27 | } 28 | 29 | Ok(()) 30 | } 31 | -------------------------------------------------------------------------------- /src/scaffold.rs: -------------------------------------------------------------------------------- 1 | mod kubewarden_crds; 2 | 3 | mod manifest; 4 | pub(crate) use manifest::manifest; 5 | 6 | mod vap; 7 | pub(crate) use vap::vap; 8 | 9 | mod verification_config; 10 | pub(crate) use verification_config::verification_config; 11 | 12 | mod artifacthub; 13 | pub(crate) use artifacthub::artifacthub; 14 | 15 | mod admission_request; 16 | pub(crate) use admission_request::Operation as AdmissionRequestOperation; 17 | pub(crate) use admission_request::{admission_request, DEFAULT_KWCTL_CACHE}; 18 | -------------------------------------------------------------------------------- /src/scaffold/artifacthub.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use policy_evaluator::{policy_artifacthub::ArtifactHubPkg, policy_metadata::Metadata}; 3 | use std::{ 4 | fs::{self, File}, 5 | path::PathBuf, 6 | }; 7 | use time::OffsetDateTime; 8 | 9 | pub(crate) fn artifacthub( 10 | metadata_path: PathBuf, 11 | questions_path: Option, 12 | ) -> Result { 13 | let comment_header = r#"# Kubewarden Artifacthub Package config 14 | # 15 | # Use this config to submit the policy to https://artifacthub.io. 16 | # 17 | # This config can be saved to its default location with: 18 | # kwctl scaffold artifacthub > artifacthub-pkg.yml "#; 19 | 20 | let metadata_file = 21 | File::open(metadata_path).map_err(|e| anyhow!("Error opening metadata file: {}", e))?; 22 | let metadata: Metadata = serde_yaml::from_reader(&metadata_file) 23 | .map_err(|e| anyhow!("Error unmarshalling metadata {}", e))?; 24 | let questions = questions_path 25 | .map(|path| { 26 | fs::read_to_string(path).map_err(|e| anyhow!("Error reading questions file: {}", e)) 27 | }) 28 | .transpose()?; 29 | 30 | let kubewarden_artifacthub_pkg = 31 | ArtifactHubPkg::from_metadata(&metadata, OffsetDateTime::now_utc(), questions.as_deref())?; 32 | 33 | Ok(format!( 34 | "{}\n{}", 35 | comment_header, 36 | serde_yaml::to_string(&kubewarden_artifacthub_pkg)? 37 | )) 38 | } 39 | -------------------------------------------------------------------------------- /src/scaffold/kubewarden_crds.rs: -------------------------------------------------------------------------------- 1 | use k8s_openapi::apimachinery::pkg::apis::meta::v1::{LabelSelector, ObjectMeta}; 2 | use policy_evaluator::policy_metadata::{ContextAwareResource, Rule}; 3 | use serde::{Deserialize, Serialize}; 4 | use std::collections::BTreeSet; 5 | 6 | #[derive(Serialize, Deserialize)] 7 | #[serde(rename_all = "camelCase")] 8 | pub(crate) struct ClusterAdmissionPolicy { 9 | pub api_version: String, 10 | pub kind: String, 11 | pub metadata: ObjectMeta, 12 | pub spec: ClusterAdmissionPolicySpec, 13 | } 14 | 15 | #[derive(Serialize, Deserialize, Default)] 16 | #[serde(rename_all = "camelCase")] 17 | pub(crate) struct ClusterAdmissionPolicySpec { 18 | pub module: String, 19 | pub settings: serde_yaml::Mapping, 20 | pub rules: Vec, 21 | pub mutating: bool, 22 | // Skip serialization when this is true, which is the default case. 23 | // This is needed as a temporary fix for https://github.com/kubewarden/kubewarden-controller/issues/395 24 | #[serde(skip_serializing_if = "is_true")] 25 | pub background_audit: bool, 26 | #[serde(skip_serializing_if = "BTreeSet::is_empty")] 27 | pub context_aware_resources: BTreeSet, 28 | #[serde(skip_serializing_if = "Option::is_none")] 29 | pub failure_policy: Option, 30 | #[serde(skip_serializing_if = "Option::is_none")] 31 | pub mode: Option, 32 | #[serde(skip_serializing_if = "Option::is_none")] 33 | pub match_policy: Option, 34 | #[serde(skip_serializing_if = "Option::is_none")] 35 | pub namespace_selector: Option, 36 | #[serde(skip_serializing_if = "Option::is_none")] 37 | pub object_selector: Option, 38 | } 39 | 40 | fn is_true(b: &bool) -> bool { 41 | *b 42 | } 43 | 44 | #[derive(Serialize, Deserialize)] 45 | #[serde(rename_all = "camelCase")] 46 | pub(crate) struct AdmissionPolicy { 47 | pub api_version: String, 48 | pub kind: String, 49 | pub metadata: ObjectMeta, 50 | pub spec: AdmissionPolicySpec, 51 | } 52 | 53 | #[derive(Serialize, Deserialize)] 54 | #[serde(rename_all = "camelCase")] 55 | pub(crate) struct AdmissionPolicySpec { 56 | pub module: String, 57 | pub settings: serde_yaml::Mapping, 58 | pub rules: Vec, 59 | pub mutating: bool, 60 | // Skip serialization when this is true, which is the default case. 61 | // This is needed as a temporary fix for https://github.com/kubewarden/kubewarden-controller/issues/395 62 | #[serde(skip_serializing_if = "is_true")] 63 | pub background_audit: bool, 64 | } 65 | -------------------------------------------------------------------------------- /src/scaffold/vap.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use k8s_openapi::api::admissionregistration::v1::{ 3 | ValidatingAdmissionPolicy, ValidatingAdmissionPolicyBinding, 4 | }; 5 | use policy_evaluator::{policy_fetcher::oci_client::Reference, policy_metadata::Rule}; 6 | use std::{collections::BTreeSet, convert::TryFrom, fs::File, path::Path}; 7 | use tracing::warn; 8 | 9 | use crate::scaffold::kubewarden_crds::{ClusterAdmissionPolicy, ClusterAdmissionPolicySpec}; 10 | 11 | pub(crate) fn vap(cel_policy_module: &str, vap_path: &Path, binding_path: &Path) -> Result<()> { 12 | let vap_file = File::open(vap_path) 13 | .map_err(|e| anyhow!("cannot open {}: #{e}", vap_path.to_str().unwrap()))?; 14 | let binding_file = File::open(binding_path) 15 | .map_err(|e| anyhow!("cannot open {}: #{e}", binding_path.to_str().unwrap()))?; 16 | 17 | let vap: ValidatingAdmissionPolicy = serde_yaml::from_reader(vap_file) 18 | .map_err(|e| anyhow!("cannot convert given data into a ValidatingAdmissionPolicy: #{e}"))?; 19 | let vap_binding: ValidatingAdmissionPolicyBinding = serde_yaml::from_reader(binding_file) 20 | .map_err(|e| { 21 | anyhow!("cannot convert given data into a ValidatingAdmissionPolicyBinding: #{e}") 22 | })?; 23 | 24 | match cel_policy_module.parse::() { 25 | Ok(cel_policy_ref) => match cel_policy_ref.tag() { 26 | None | Some("latest") => { 27 | warn!( 28 | "Using the 'latest' version of the CEL policy could lead to unexpected behavior. It is recommended to use a specific version to avoid breaking changes." 29 | ); 30 | } 31 | _ => {} 32 | }, 33 | Err(_) => { 34 | warn!("The CEL policy module specified is not a valid OCI reference"); 35 | } 36 | } 37 | 38 | let cluster_admission_policy = 39 | convert_vap_to_cluster_admission_policy(cel_policy_module, vap, vap_binding)?; 40 | 41 | serde_yaml::to_writer(std::io::stdout(), &cluster_admission_policy)?; 42 | 43 | Ok(()) 44 | } 45 | 46 | fn convert_vap_to_cluster_admission_policy( 47 | cel_policy_module: &str, 48 | vap: ValidatingAdmissionPolicy, 49 | vap_binding: ValidatingAdmissionPolicyBinding, 50 | ) -> anyhow::Result { 51 | let vap_spec = vap.spec.unwrap_or_default(); 52 | if vap_spec.audit_annotations.is_some() { 53 | warn!("auditAnnotations are not supported by Kubewarden's CEL policy yet. They will be ignored."); 54 | } 55 | if vap_spec.match_conditions.is_some() { 56 | warn!("matchConditions are not supported by Kubewarden's CEL policy yet. They will be ignored."); 57 | } 58 | if vap_spec.param_kind.is_some() { 59 | // It's not safe to skip this, the policy will definitely not work. 60 | return Err(anyhow!( 61 | "paramKind is not supported by Kubewarden's CEL policy yet" 62 | )); 63 | } 64 | 65 | let mut settings = serde_yaml::Mapping::new(); 66 | 67 | // migrate CEL variables 68 | if let Some(vap_variables) = vap_spec.variables { 69 | let vap_variables: Vec = vap_variables 70 | .iter() 71 | .map(|v| serde_yaml::to_value(v).expect("cannot convert VAP variable to YAML")) 72 | .collect(); 73 | settings.insert("variables".into(), vap_variables.into()); 74 | } 75 | 76 | // migrate CEL validations 77 | if let Some(vap_validations) = vap_spec.validations { 78 | let kw_cel_validations: Vec = vap_validations 79 | .iter() 80 | .map(|v| serde_yaml::to_value(v).expect("cannot convert VAP validation to YAML")) 81 | .collect(); 82 | settings.insert("validations".into(), kw_cel_validations.into()); 83 | } 84 | 85 | // VAP specifies the namespace selector inside of the binding 86 | let namespace_selector = vap_binding 87 | .spec 88 | .unwrap_or_default() 89 | .match_resources 90 | .unwrap_or_default() 91 | .namespace_selector; 92 | 93 | // VAP rules are specified inside of the VAP object 94 | let vap_match_constraints = vap_spec.match_constraints.unwrap_or_default(); 95 | let match_policy = vap_match_constraints.match_policy; 96 | let rules = vap_match_constraints 97 | .resource_rules 98 | .unwrap_or_default() 99 | .iter() 100 | .map(Rule::try_from) 101 | .collect::, &'static str>>() 102 | .map_err(|e| anyhow!("error converting VAP matchConstraints into rules: {e}"))?; 103 | 104 | // migrate VAP 105 | let cluster_admission_policy = ClusterAdmissionPolicy { 106 | api_version: "policies.kubewarden.io/v1".to_string(), 107 | kind: "ClusterAdmissionPolicy".to_string(), 108 | metadata: vap_binding.metadata, 109 | spec: ClusterAdmissionPolicySpec { 110 | module: cel_policy_module.to_string(), 111 | namespace_selector, 112 | match_policy, 113 | rules, 114 | object_selector: vap_match_constraints.object_selector, 115 | mutating: false, 116 | background_audit: true, 117 | context_aware_resources: BTreeSet::new(), 118 | failure_policy: vap_spec.failure_policy, 119 | mode: None, // VAP policies are always in protect mode, which is the default for KW 120 | settings, 121 | }, 122 | }; 123 | 124 | Ok(cluster_admission_policy) 125 | } 126 | 127 | #[cfg(test)] 128 | mod tests { 129 | use super::*; 130 | use rstest::*; 131 | 132 | const CEL_POLICY_MODULE: &str = "ghcr.io/kubewarden/policies/cel-policy:latest"; 133 | 134 | fn test_data(path: &str) -> String { 135 | Path::new(env!("CARGO_MANIFEST_DIR")) 136 | .join("tests") 137 | .join("data") 138 | .join(path) 139 | .to_string_lossy() 140 | .to_string() 141 | } 142 | 143 | #[rstest] 144 | #[case::vap_without_variables("vap/vap-without-variables.yml", "vap/vap-binding.yml", false)] 145 | #[case::vap_with_variables("vap/vap-with-variables.yml", "vap/vap-binding.yml", true)] 146 | fn from_vap_to_cluster_admission_policy( 147 | #[case] vap_yaml_path: &str, 148 | #[case] vap_binding_yaml_path: &str, 149 | #[case] has_variables: bool, 150 | ) { 151 | let yaml_file = File::open(test_data(vap_yaml_path)).unwrap(); 152 | let vap: ValidatingAdmissionPolicy = serde_yaml::from_reader(yaml_file).unwrap(); 153 | 154 | let expected_validations = 155 | serde_yaml::to_value(vap.clone().spec.unwrap().validations.unwrap()).unwrap(); 156 | let expected_rules = vap 157 | .clone() 158 | .spec 159 | .unwrap() 160 | .match_constraints 161 | .unwrap() 162 | .resource_rules 163 | .unwrap() 164 | .iter() 165 | .map(Rule::try_from) 166 | .collect::, &str>>() 167 | .unwrap(); 168 | 169 | let yaml_file = File::open(test_data(vap_binding_yaml_path)).unwrap(); 170 | let vap_binding: ValidatingAdmissionPolicyBinding = 171 | serde_yaml::from_reader(yaml_file).unwrap(); 172 | 173 | let cluster_admission_policy = convert_vap_to_cluster_admission_policy( 174 | CEL_POLICY_MODULE, 175 | vap.clone(), 176 | vap_binding.clone(), 177 | ) 178 | .unwrap(); 179 | 180 | assert_eq!(CEL_POLICY_MODULE, cluster_admission_policy.spec.module); 181 | assert!(!cluster_admission_policy.spec.mutating); 182 | assert_eq!(cluster_admission_policy.spec.rules, expected_rules); 183 | assert!(cluster_admission_policy.spec.background_audit); 184 | assert!(cluster_admission_policy 185 | .spec 186 | .context_aware_resources 187 | .is_empty()); 188 | assert_eq!( 189 | vap.clone().spec.unwrap().failure_policy, 190 | cluster_admission_policy.spec.failure_policy 191 | ); 192 | assert!(cluster_admission_policy.spec.mode.is_none()); 193 | assert_eq!( 194 | vap.clone() 195 | .spec 196 | .unwrap() 197 | .match_constraints 198 | .unwrap() 199 | .match_policy, 200 | cluster_admission_policy.spec.match_policy 201 | ); 202 | assert_eq!( 203 | vap_binding 204 | .clone() 205 | .spec 206 | .unwrap() 207 | .match_resources 208 | .unwrap() 209 | .namespace_selector, 210 | cluster_admission_policy.spec.namespace_selector 211 | ); 212 | assert!(cluster_admission_policy.spec.object_selector.is_none()); 213 | assert_eq!( 214 | expected_validations, 215 | cluster_admission_policy.spec.settings["validations"] 216 | ); 217 | 218 | if has_variables { 219 | let expected_variables = 220 | serde_yaml::to_value(vap.clone().spec.unwrap().variables.unwrap()).unwrap(); 221 | assert_eq!( 222 | expected_variables, 223 | cluster_admission_policy.spec.settings["variables"] 224 | ); 225 | } else { 226 | assert!(!cluster_admission_policy 227 | .spec 228 | .settings 229 | .contains_key("variables")); 230 | } 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /src/scaffold/verification_config.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use policy_evaluator::policy_fetcher::verify::config::{ 3 | LatestVerificationConfig, Signature, VersionedVerificationConfig, 4 | }; 5 | 6 | pub(crate) fn verification_config() -> Result { 7 | let mut comment_header = r#"# Default Kubewarden verification config 8 | # 9 | # With this config, the only valid policies are those signed by Kubewarden 10 | # infrastructure. 11 | # 12 | # This config can be saved to its default location (for this OS) with: 13 | # kwctl scaffold verification-config > "# 14 | .to_string(); 15 | 16 | comment_header.push_str( 17 | crate::KWCTL_DEFAULT_VERIFICATION_CONFIG_PATH 18 | .to_owned() 19 | .as_str(), 20 | ); 21 | comment_header.push_str( 22 | r#" 23 | # 24 | # Providing a config in the default location enables Sigstore verification. 25 | # See https://docs.kubewarden.io/next/howtos/security-hardening/secure-supply-chain 26 | # for more Sigstore verification options."#, 27 | ); 28 | 29 | let kubewarden_verification_config = 30 | VersionedVerificationConfig::V1(LatestVerificationConfig { 31 | all_of: Some(vec![Signature::GithubAction { 32 | owner: "kubewarden".to_string(), 33 | repo: None, 34 | annotations: None, 35 | }]), 36 | any_of: None, 37 | }); 38 | 39 | Ok(format!( 40 | "{}\n{}", 41 | comment_header, 42 | serde_yaml::to_string(&kubewarden_verification_config)? 43 | )) 44 | } 45 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use policy_evaluator::policy_evaluator::PolicyExecutionMode; 3 | use policy_evaluator::policy_fetcher::oci_client::Reference; 4 | use policy_evaluator::policy_fetcher::store::{errors::StoreError, Store}; 5 | use regex::Regex; 6 | use serde_json::json; 7 | use std::path::PathBuf; 8 | use std::str::FromStr; 9 | use url::Url; 10 | 11 | #[derive(Debug, thiserror::Error)] 12 | pub(crate) enum LookupError { 13 | #[error("Cannot find policy with uri: {0}")] 14 | PolicyMissing(String), 15 | #[error("{0}")] 16 | StoreError(#[from] StoreError), 17 | #[error("Unknown scheme: {0}")] 18 | UnknownScheme(String), 19 | #[error("{0}")] 20 | UrlParserError(#[from] url::ParseError), 21 | #[error("Error while converting URL to string")] 22 | UrlToStringConversionError(), 23 | #[error("{0}")] 24 | IoError(#[from] std::io::Error), 25 | } 26 | 27 | pub(crate) fn map_path_to_uri(uri_or_sha_prefix: &str) -> std::result::Result { 28 | let uri_has_schema = Regex::new(r"^\w+://").unwrap(); 29 | if uri_has_schema.is_match(uri_or_sha_prefix) { 30 | return Ok(String::from(uri_or_sha_prefix)); 31 | } 32 | 33 | let path = PathBuf::from(uri_or_sha_prefix); 34 | if path.exists() { 35 | let path = path.canonicalize()?; 36 | 37 | Ok(Url::from_file_path(path).unwrap().to_string()) 38 | } else { 39 | let store = Store::default(); 40 | if let Some(policy) = store.get_policy_by_sha_prefix(uri_or_sha_prefix)? { 41 | Ok(policy.uri.clone()) 42 | } else { 43 | Err(LookupError::PolicyMissing(uri_or_sha_prefix.to_string())) 44 | } 45 | } 46 | } 47 | 48 | pub(crate) fn get_uri(uri_or_sha_prefix: &String) -> std::result::Result { 49 | map_path_to_uri(uri_or_sha_prefix).or_else(|_| { 50 | Reference::from_str(uri_or_sha_prefix) 51 | .map(|oci_reference| format!("registry://{}", oci_reference.whole())) 52 | .map_err(|_| LookupError::PolicyMissing(uri_or_sha_prefix.to_string())) 53 | }) 54 | } 55 | 56 | pub(crate) fn get_wasm_path(uri_or_sha_prefix: &str) -> std::result::Result { 57 | let uri = get_uri(&uri_or_sha_prefix.to_owned())?; 58 | wasm_path(&uri) 59 | } 60 | 61 | pub(crate) fn wasm_path(uri: &str) -> std::result::Result { 62 | let url = Url::parse(uri)?; 63 | match url.scheme() { 64 | "file" => url 65 | .to_file_path() 66 | .map_err(|_| LookupError::UrlToStringConversionError()), 67 | "http" | "https" | "registry" => { 68 | let store = Store::default(); 69 | let policy = store.get_policy_by_uri(uri)?; 70 | 71 | if let Some(policy) = policy { 72 | Ok(policy.local_path) 73 | } else { 74 | Err(LookupError::PolicyMissing(uri.to_string())) 75 | } 76 | } 77 | _ => Err(LookupError::UnknownScheme(url.scheme().to_string())), 78 | } 79 | } 80 | 81 | pub(crate) fn new_policy_execution_mode_from_str(name: &str) -> Result { 82 | let execution_mode: PolicyExecutionMode = 83 | serde_json::from_value(json!(name)).map_err(|_| { 84 | anyhow!( 85 | "Unknown policy execution mode \"{}\". Valid values are {}, {}, {}", 86 | name, 87 | serde_json::to_string(&PolicyExecutionMode::KubewardenWapc).unwrap(), 88 | serde_json::to_string(&PolicyExecutionMode::Opa).unwrap(), 89 | serde_json::to_string(&PolicyExecutionMode::OpaGatekeeper).unwrap(), 90 | ) 91 | })?; 92 | Ok(execution_mode) 93 | } 94 | 95 | pub(crate) fn find_file_matching_file(possible_names: &[&str]) -> Option { 96 | possible_names 97 | .iter() 98 | .map(PathBuf::from) 99 | .find(|path| path.exists()) 100 | } 101 | 102 | #[cfg(test)] 103 | mod tests { 104 | use std::collections::HashMap; 105 | 106 | use super::*; 107 | 108 | #[test] 109 | fn test_map_path_to_uri_remote_scheme() -> Result<()> { 110 | assert_eq!( 111 | map_path_to_uri("registry://some-registry.com/some-path/some-policy:0.0.1")?, 112 | String::from("registry://some-registry.com/some-path/some-policy:0.0.1"), 113 | ); 114 | 115 | Ok(()) 116 | } 117 | 118 | #[test] 119 | fn test_map_path_to_uri_local_scheme() -> Result<()> { 120 | assert_eq!( 121 | map_path_to_uri("file:///absolute/directory/some-policy-0.0.1.wasm")?, 122 | "file:///absolute/directory/some-policy-0.0.1.wasm", 123 | ); 124 | 125 | Ok(()) 126 | } 127 | 128 | #[test] 129 | fn test_build_policy_execution_mode_from_valid_input() { 130 | let mut data: HashMap = HashMap::new(); 131 | data.insert(String::from("opa"), PolicyExecutionMode::Opa); 132 | data.insert( 133 | String::from("gatekeeper"), 134 | PolicyExecutionMode::OpaGatekeeper, 135 | ); 136 | data.insert( 137 | String::from("kubewarden-wapc"), 138 | PolicyExecutionMode::KubewardenWapc, 139 | ); 140 | 141 | for (name, mode) in data { 142 | let actual = new_policy_execution_mode_from_str(name.as_str()); 143 | assert!( 144 | actual.is_ok(), 145 | "Error while converting {}: {:?}", 146 | name, 147 | actual 148 | ); 149 | 150 | let actual = actual.unwrap(); 151 | assert_eq!(actual, mode, "Expected {}, got {}", mode, actual); 152 | } 153 | } 154 | 155 | #[test] 156 | fn test_build_policy_execution_mode_from_invalid_input() { 157 | let actual = new_policy_execution_mode_from_str("test"); 158 | assert!(actual.is_err(),); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/verify.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | use policy_evaluator::policy_fetcher::{ 3 | policy::Policy, 4 | sigstore::trust::ManualTrustRoot, 5 | sources::Sources, 6 | verify::{config::LatestVerificationConfig, Verifier}, 7 | }; 8 | use std::collections::BTreeMap; 9 | use std::sync::Arc; 10 | use tracing::{debug, info}; 11 | 12 | pub(crate) type VerificationAnnotations = BTreeMap; 13 | 14 | pub(crate) async fn verify( 15 | url: &str, 16 | sources: Option<&Sources>, 17 | verification_config: &LatestVerificationConfig, 18 | sigstore_trust_root: Option>>, 19 | ) -> Result { 20 | debug!( 21 | policy = url, 22 | ?sources, 23 | ?verification_config, 24 | "Verifying policy" 25 | ); 26 | let mut verifier = Verifier::new(sources.cloned(), sigstore_trust_root).await?; 27 | let verified_manifest_digest = verifier.verify(url, verification_config).await?; 28 | 29 | info!("Policy successfully verified"); 30 | Ok(verified_manifest_digest) 31 | } 32 | 33 | pub(crate) async fn verify_local_checksum( 34 | policy: &Policy, 35 | sources: Option<&Sources>, 36 | verified_manifest_digest: &str, 37 | sigstore_trust_root: Option>>, 38 | ) -> Result<()> { 39 | let mut verifier = Verifier::new(sources.cloned(), sigstore_trust_root).await?; 40 | verifier 41 | .verify_local_file_checksum(policy, verified_manifest_digest) 42 | .await?; 43 | 44 | info!("Local checksum successfully verified"); 45 | Ok(()) 46 | } 47 | -------------------------------------------------------------------------------- /tests/airgap.rs: -------------------------------------------------------------------------------- 1 | use assert_cmd::Command; 2 | use std::path::{Path, PathBuf}; 3 | use tempfile::tempdir; 4 | use testcontainers::{core::WaitFor, runners::SyncRunner}; 5 | 6 | mod common; 7 | 8 | #[test] 9 | fn test_airgap() { 10 | let tempdir = tempdir().unwrap(); 11 | let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); 12 | 13 | // Run registry 14 | let registry_image = testcontainers::GenericImage::new("docker.io/library/registry", "2") 15 | .with_wait_for(WaitFor::message_on_stderr("listening on ")); 16 | let testcontainer = registry_image 17 | .start() 18 | .expect("Failed to start registry container"); 19 | let port = testcontainer 20 | .get_host_port_ipv4(5000) 21 | .expect("Failed to get host port"); 22 | 23 | // Save policies 24 | let mut save_policies_script = setup_airgap_script_command( 25 | &project_root.join("scripts/kubewarden-save-policies.sh"), 26 | tempdir.path(), 27 | ); 28 | save_policies_script 29 | .arg("--policies-list") 30 | .arg(project_root.join("tests/data/airgap/policies.txt")) 31 | .arg("--policies") 32 | .arg(tempdir.path().join("policies.tar.gz")) 33 | .assert() 34 | .success(); 35 | 36 | // Remove policies from store 37 | let mut kwctl = common::setup_command(tempdir.path()); 38 | kwctl 39 | .arg("rm") 40 | .arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9") 41 | .assert() 42 | .success(); 43 | 44 | let mut kwctl = common::setup_command(tempdir.path()); 45 | kwctl 46 | .arg("rm") 47 | .arg("https://github.com/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm") 48 | .assert() 49 | .success(); 50 | 51 | // Create sources.yml 52 | let sources_yaml = format!( 53 | r#" 54 | insecure_sources: 55 | - "localhost:{}" 56 | "#, 57 | port 58 | ); 59 | std::fs::write(tempdir.path().join("sources.yml"), sources_yaml).unwrap(); 60 | 61 | // Load policies 62 | let mut load_policies_script = setup_airgap_script_command( 63 | &project_root.join("scripts/kubewarden-load-policies.sh"), 64 | tempdir.path(), 65 | ); 66 | load_policies_script 67 | .arg("--policies") 68 | .arg(tempdir.path().join("policies.tar.gz")) 69 | .arg("--policies-list") 70 | .arg(project_root.join("tests/data/airgap/policies.txt")) 71 | .arg("--registry") 72 | .arg(format!("localhost:{}", port)) 73 | .arg("--sources-path") 74 | .arg(tempdir.path().join("sources.yml")) 75 | .assert() 76 | .success(); 77 | 78 | // Verify policies in local registry 79 | let mut kwctl = common::setup_command(tempdir.path()); 80 | kwctl 81 | .arg("pull") 82 | .arg(format!( 83 | "registry://localhost:{}/kubewarden/tests/pod-privileged:v0.1.9", 84 | port 85 | )) 86 | .arg("--sources-path") 87 | .arg(tempdir.path().join("sources.yml")) 88 | .assert() 89 | .success(); 90 | 91 | let mut kwctl = common::setup_command(tempdir.path()); 92 | kwctl 93 | .arg("pull") 94 | .arg(format!( 95 | "registry://localhost:{}/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm ", 96 | port 97 | )) 98 | .arg("--sources-path") 99 | .arg(tempdir.path().join("sources.yml")) 100 | .assert() 101 | .success(); 102 | } 103 | 104 | fn setup_airgap_script_command(script: &Path, tempdir: &Path) -> Command { 105 | let mut cmd = Command::new(script); 106 | 107 | cmd.current_dir(tempdir) 108 | .env("XDG_CONFIG_HOME", tempdir.join(".config")) 109 | .env("XDG_CACHE_HOME", tempdir.join(".cache")) 110 | .env("XDG_DATA_HOME", tempdir.join(".local/share")) 111 | .env("KWCTL_CMD", env!("CARGO_BIN_EXE_kwctl")); 112 | 113 | cmd 114 | } 115 | -------------------------------------------------------------------------------- /tests/common/mod.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | use assert_cmd::Command; 4 | 5 | #[allow(dead_code)] 6 | pub fn setup_command(path: &Path) -> Command { 7 | let mut cmd = Command::cargo_bin("kwctl").unwrap(); 8 | 9 | cmd.current_dir(path) 10 | .env("XDG_CONFIG_HOME", path.join(".config")) 11 | .env("XDG_CACHE_HOME", path.join(".cache")) 12 | .env("XDG_DATA_HOME", path.join(".local/share")); 13 | 14 | cmd 15 | } 16 | 17 | #[allow(dead_code)] 18 | pub fn test_data(path: &str) -> String { 19 | Path::new(env!("CARGO_MANIFEST_DIR")) 20 | .join("tests") 21 | .join("data") 22 | .join(path) 23 | .to_string_lossy() 24 | .to_string() 25 | } 26 | -------------------------------------------------------------------------------- /tests/data/airgap/policies.txt: -------------------------------------------------------------------------------- 1 | registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9 2 | https://github.com/kubewarden/pod-privileged-policy/releases/download/v0.1.6/policy.wasm 3 | -------------------------------------------------------------------------------- /tests/data/artifacthub/metadata.yml: -------------------------------------------------------------------------------- 1 | rules: 2 | - apiGroups: 3 | - admissionregistration.k8s.io 4 | apiVersions: 5 | - v1beta1 6 | resources: 7 | - "*" 8 | operations: 9 | - CREATE 10 | - apiGroups: 11 | - apiextensions.k8s.io 12 | apiVersions: 13 | - v1beta1 14 | resources: 15 | - "*" 16 | operations: 17 | - CREATE 18 | - apiGroups: 19 | - apiregistration.k8s.io 20 | apiVersions: 21 | - v1beta1 22 | resources: 23 | - "*" 24 | operations: 25 | - CREATE 26 | - apiGroups: 27 | - apps 28 | apiVersions: 29 | - v1beta1 30 | - v1beta2 31 | resources: 32 | - "*" 33 | operations: 34 | - CREATE 35 | - apiGroups: 36 | - audit.k8s.io 37 | apiVersions: 38 | - v1alpha1 39 | - v1beta1 40 | resources: 41 | - "*" 42 | operations: 43 | - CREATE 44 | - apiGroups: 45 | - authentication.k8s.io 46 | apiVersions: 47 | - v1beta1 48 | resources: 49 | - "*" 50 | operations: 51 | - CREATE 52 | - apiGroups: 53 | - autoscaling 54 | apiVersions: 55 | - v2beta1 56 | - v2beta2 57 | resources: 58 | - "*" 59 | operations: 60 | - CREATE 61 | - apiGroups: 62 | - batch 63 | apiVersions: 64 | - v1beta1 65 | resources: 66 | - "*" 67 | operations: 68 | - CREATE 69 | - apiGroups: 70 | - certificates.k8s.io 71 | apiVersions: 72 | - v1beta1 73 | resources: 74 | - "*" 75 | operations: 76 | - CREATE 77 | - apiGroups: 78 | - coordination.k8s.io 79 | apiVersions: 80 | - v1beta1 81 | resources: 82 | - "*" 83 | operations: 84 | - CREATE 85 | - apiGroups: 86 | - discovery.k8s.io 87 | apiVersions: 88 | - v1beta1 89 | resources: 90 | - "*" 91 | operations: 92 | - CREATE 93 | - apiGroups: 94 | - events.k8s.io 95 | apiVersions: 96 | - v1beta1 97 | resources: 98 | - "*" 99 | operations: 100 | - CREATE 101 | - apiGroups: 102 | - extensions 103 | apiVersions: 104 | - v1beta1 105 | resources: 106 | - "*" 107 | operations: 108 | - CREATE 109 | - apiGroups: 110 | - flowcontrol.apiserver.k8s.io 111 | apiVersions: 112 | - v1beta1 113 | - v1beta2 114 | - v1beta3 115 | resources: 116 | - "*" 117 | operations: 118 | - CREATE 119 | - apiGroups: 120 | - networking.k8s.io 121 | apiVersions: 122 | - v1beta1 123 | resources: 124 | - "*" 125 | operations: 126 | - CREATE 127 | - apiGroups: 128 | - node.k8s.io 129 | apiVersions: 130 | - v1beta1 131 | resources: 132 | - "*" 133 | operations: 134 | - CREATE 135 | - apiGroups: 136 | - policy 137 | apiVersions: 138 | - v1beta1 139 | resources: 140 | - "*" 141 | operations: 142 | - CREATE 143 | - apiGroups: 144 | - rbac.authorization.k8s.io 145 | apiVersions: 146 | - v1alpha1 147 | - v1beta1 148 | resources: 149 | - "*" 150 | operations: 151 | - CREATE 152 | - apiGroups: 153 | - scheduling.k8s.io 154 | apiVersions: 155 | - v1alpha1 156 | - v1beta1 157 | resources: 158 | - "*" 159 | operations: 160 | - CREATE 161 | - apiGroups: 162 | - storage.k8s.io 163 | apiVersions: 164 | - v1beta1 165 | resources: 166 | - "*" 167 | operations: 168 | - CREATE 169 | mutating: false 170 | contextAware: false 171 | executionMode: kubewarden-wapc 172 | backgroundAudit: false 173 | annotations: 174 | # artifacthub specific 175 | io.artifacthub.displayName: Deprecated API Versions 176 | io.artifacthub.resources: "*" 177 | io.artifacthub.keywords: compliance, deprecated API 178 | io.kubewarden.policy.ociUrl: ghcr.io/kubewarden/policies/deprecated-api-versions 179 | # kubewarden specific 180 | io.kubewarden.policy.title: deprecated-api-versions 181 | io.kubewarden.policy.description: Find deprecated and removed Kubernetes resources 182 | io.kubewarden.policy.version: 0.2.0 183 | io.kubewarden.policy.author: Kubewarden developers 184 | io.kubewarden.policy.url: https://github.com/kubewarden/deprecated-api-versions-policy 185 | io.kubewarden.policy.source: https://github.com/kubewarden/deprecated-api-versions-policy 186 | io.kubewarden.policy.license: Apache-2.0 187 | io.kubewarden.policy.category: Kubernetes API Versions 188 | io.kubewarden.policy.severity: low 189 | -------------------------------------------------------------------------------- /tests/data/context-aware-policy-request-pod-creation-all-labels.json: -------------------------------------------------------------------------------- 1 | { 2 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 3 | "kind": { 4 | "group": "", 5 | "kind": "Pod", 6 | "version": "v1" 7 | }, 8 | "resource": { 9 | "group": "", 10 | "version": "v1", 11 | "resource": "pods" 12 | }, 13 | "namespace": "test-policy", 14 | "object": { 15 | "metadata": { 16 | "name": "nginx", 17 | "labels": { 18 | "hello": "world" 19 | } 20 | }, 21 | "spec": { 22 | "containers": [ 23 | { 24 | "image": "nginx", 25 | "name": "nginx" 26 | } 27 | ] 28 | } 29 | }, 30 | "operation": "CREATE", 31 | "requestKind": { 32 | "group": "", 33 | "version": "v1", 34 | "kind": "Pod" 35 | }, 36 | "userInfo": { 37 | "username": "alice", 38 | "uid": "alice-uid", 39 | "groups": ["system:authenticated"] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/data/host-capabilities-sessions/context-aware-demo-namespace-found.yml: -------------------------------------------------------------------------------- 1 | - type: Exchange 2 | request: | 3 | !KubernetesGetResource 4 | api_version: v1 5 | kind: Namespace 6 | name: test-policy 7 | namespace: null 8 | disable_cache: false 9 | response: 10 | type: Success 11 | payload: '{"apiVersion":"v1","kind":"Namespace","metadata":{"annotations":{"cattle.io/status":"{\"Conditions\":[{\"Type\":\"ResourceQuotaInit\",\"Status\":\"True\",\"Message\":\"\",\"LastUpdateTime\":\"2023-03-17T10:23:56Z\"},{\"Type\":\"InitialRolesPopulated\",\"Status\":\"True\",\"Message\":\"\",\"LastUpdateTime\":\"2023-03-17T10:23:56Z\"}]}","lifecycle.cattle.io/create.namespace-auth":"true","propagate.hello":"world"},"creationTimestamp":"2023-03-09T13:46:10Z","finalizers":["controller.cattle.io/namespace-auth"],"labels":{"kubernetes.io/metadata.name":"test-policy"},"managedFields":[{"apiVersion":"v1","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{},"f:labels":{".":{},"f:kubernetes.io/metadata.name":{}}}},"manager":"kubectl-client-side-apply","operation":"Update","time":"2023-03-09T13:56:14Z"},{"apiVersion":"v1","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{"f:propagate.hello":{}}}},"manager":"kubectl-edit","operation":"Update","time":"2023-03-17T10:23:55Z"},{"apiVersion":"v1","fieldsType":"FieldsV1","fieldsV1":{"f:metadata":{"f:annotations":{"f:cattle.io/status":{},"f:lifecycle.cattle.io/create.namespace-auth":{}},"f:finalizers":{".":{},"v:\"controller.cattle.io/namespace-auth\"":{}}}},"manager":"rancher","operation":"Update","time":"2023-03-17T10:23:55Z"}],"name":"test-policy","resourceVersion":"963079","uid":"877b355c-2722-4f73-8131-72ec63256668"},"spec":{"finalizers":["kubernetes"]},"status":{"phase":"Active"}}' 12 | -------------------------------------------------------------------------------- /tests/data/host-capabilities-sessions/context-aware-demo-namespace-not-found.yml: -------------------------------------------------------------------------------- 1 | - type: Exchange 2 | request: | 3 | !KubernetesGetResource 4 | api_version: v1 5 | kind: Namespace 6 | name: test-policy 7 | namespace: null 8 | disable_cache: false 9 | response: 10 | type: Error 11 | message: Cannot find v1/Namespace named 'test-policy' inside of namespace 'None' 12 | -------------------------------------------------------------------------------- /tests/data/host-capabilities-sessions/context-aware-unique-ingress-duplicate.yml: -------------------------------------------------------------------------------- 1 | - type: Exchange 2 | request: | 3 | !KubernetesListResourceAll 4 | api_version: networking.k8s.io/v1 5 | kind: Ingress 6 | label_selector: null 7 | field_selector: null 8 | response: 9 | type: Success 10 | payload: | 11 | { 12 | "apiVersion": "v1", 13 | "kind": "List", 14 | "metadata": {"resourceVersion":"450657254"}, 15 | "items":[ 16 | { 17 | "metadata": { 18 | "creationTimestamp": "2021-07-23T21:16:28Z", 19 | "generation": 2, 20 | "name": "test", 21 | "namespace": "default", 22 | "resourceVersion": "126783215", 23 | "uid": "25e07786-fe09-49ba-a0f4-3008f3517120" 24 | }, 25 | "spec": { 26 | "rules": [ 27 | { 28 | "host": "foo.bar.com", 29 | "http": { 30 | "paths": [ 31 | { 32 | "path": "/", 33 | "pathType": "Prefix", 34 | "backend": { 35 | "service": { 36 | "name": "demo", 37 | "port": { 38 | "number": 80 39 | } 40 | } 41 | } 42 | } 43 | ] 44 | } 45 | } 46 | ] 47 | } 48 | } 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /tests/data/host-capabilities-sessions/context-aware-unique-ingress-no-duplicate.yml: -------------------------------------------------------------------------------- 1 | - type: Exchange 2 | request: | 3 | !KubernetesListResourceAll 4 | api_version: networking.k8s.io/v1 5 | kind: Ingress 6 | label_selector: null 7 | field_selector: null 8 | response: 9 | type: Success 10 | payload: | 11 | { 12 | "apiVersion": "v1", 13 | "kind": "List", 14 | "metadata": {"resourceVersion":"450657254"}, 15 | "items":[ 16 | { 17 | "metadata": { 18 | "creationTimestamp": "2021-07-23T21:16:28Z", 19 | "generation": 2, 20 | "name": "test", 21 | "namespace": "default", 22 | "resourceVersion": "126783215", 23 | "uid": "25e07786-fe09-49ba-a0f4-3008f3517120" 24 | }, 25 | "spec": { 26 | "rules": [ 27 | { 28 | "host": "test.example.com", 29 | "http": { 30 | "paths": [ 31 | { 32 | "path": "/", 33 | "pathType": "Prefix", 34 | "backend": { 35 | "service": { 36 | "name": "demo", 37 | "port": { 38 | "number": 80 39 | } 40 | } 41 | } 42 | } 43 | ] 44 | } 45 | } 46 | ] 47 | } 48 | } 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /tests/data/ingress.json: -------------------------------------------------------------------------------- 1 | { 2 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 3 | "kind": { 4 | "group": "networking.k8s.io", 5 | "kind": "Ingress", 6 | "version": "v1" 7 | }, 8 | "resource": { 9 | "group": "networking.k8s.io", 10 | "version": "v1", 11 | "resource": "ingresses" 12 | }, 13 | "name": "foobar", 14 | "operation": "CREATE", 15 | "userInfo": { 16 | "username": "kubernetes-admin", 17 | "groups": [ 18 | "system:masters", 19 | "system:authenticated" 20 | ] 21 | }, 22 | "object": { 23 | "apiVersion": "networking.k8s.io/v1", 24 | "kind": "Ingress", 25 | "metadata": { 26 | "name": "foobar" 27 | }, 28 | "spec": { 29 | "rules": [ 30 | { 31 | "host": "foo.bar.com", 32 | "http": { 33 | "paths": [ 34 | { 35 | "pathType": "Prefix", 36 | "path": "/bar", 37 | "backend": { 38 | "service": { 39 | "name": "service1", 40 | "port": { 41 | "number": 3000 42 | } 43 | } 44 | } 45 | } 46 | ] 47 | } 48 | } 49 | ] 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/data/privileged-pod-admission-review.json: -------------------------------------------------------------------------------- 1 | { 2 | "apiVersion": "admission.k8s.io/v1", 3 | "kind": "AdmissionReview", 4 | "request": { 5 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 6 | "kind": { 7 | "group": "", 8 | "version": "v1", 9 | "kind": "Pod" 10 | }, 11 | "resource": { 12 | "group": "", 13 | "version": "v1", 14 | "resource": "pods" 15 | }, 16 | "requestKind": { 17 | "group": "", 18 | "version": "v1", 19 | "kind": "Pod" 20 | }, 21 | "requestResource": { 22 | "group": "", 23 | "version": "v1", 24 | "resource": "pods" 25 | }, 26 | "name": "nginx", 27 | "namespace": "default", 28 | "operation": "CREATE", 29 | "userInfo": { 30 | "username": "kubernetes-admin", 31 | "groups": [ 32 | "system:masters", 33 | "system:authenticated" 34 | ] 35 | }, 36 | "object": { 37 | "kind": "Pod", 38 | "apiVersion": "v1", 39 | "metadata": { 40 | "name": "nginx", 41 | "namespace": "default", 42 | "uid": "04dc7a5e-e1f1-4e34-8d65-2c9337a43e64", 43 | "creationTimestamp": "2020-11-12T15:18:36Z", 44 | "labels": { 45 | "env": "test" 46 | }, 47 | "annotations": { 48 | "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"env\":\"test\"},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"imagePullPolicy\":\"IfNotPresent\",\"name\":\"nginx\"}],\"tolerations\":[{\"effect\":\"NoSchedule\",\"key\":\"example-key\",\"operator\":\"Exists\"}]}}\n" 49 | }, 50 | "managedFields": [ 51 | { 52 | "manager": "kubectl", 53 | "operation": "Update", 54 | "apiVersion": "v1", 55 | "time": "2020-11-12T15:18:36Z", 56 | "fieldsType": "FieldsV1", 57 | "fieldsV1": { 58 | "f:metadata": { 59 | "f:annotations": { 60 | ".": {}, 61 | "f:kubectl.kubernetes.io/last-applied-configuration": {} 62 | }, 63 | "f:labels": { 64 | ".": {}, 65 | "f:env": {} 66 | } 67 | }, 68 | "f:spec": { 69 | "f:containers": { 70 | "k:{\"name\":\"nginx\"}": { 71 | ".": {}, 72 | "f:image": {}, 73 | "f:imagePullPolicy": {}, 74 | "f:name": {}, 75 | "f:resources": {}, 76 | "f:terminationMessagePath": {}, 77 | "f:terminationMessagePolicy": {} 78 | } 79 | }, 80 | "f:dnsPolicy": {}, 81 | "f:enableServiceLinks": {}, 82 | "f:restartPolicy": {}, 83 | "f:schedulerName": {}, 84 | "f:securityContext": {}, 85 | "f:terminationGracePeriodSeconds": {}, 86 | "f:tolerations": {} 87 | } 88 | } 89 | } 90 | ] 91 | }, 92 | "spec": { 93 | "volumes": [ 94 | { 95 | "name": "default-token-pvpz7", 96 | "secret": { 97 | "secretName": "default-token-pvpz7" 98 | } 99 | } 100 | ], 101 | "containers": [ 102 | { 103 | "name": "sleeping-sidecar", 104 | "image": "alpine", 105 | "command": ["sleep", "1h"], 106 | "resources": {}, 107 | "volumeMounts": [ 108 | { 109 | "name": "default-token-pvpz7", 110 | "readOnly": true, 111 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 112 | } 113 | ], 114 | "terminationMessagePath": "/dev/termination-log", 115 | "terminationMessagePolicy": "File", 116 | "imagePullPolicy": "IfNotPresent" 117 | }, 118 | { 119 | "name": "nginx", 120 | "image": "nginx", 121 | "resources": {}, 122 | "volumeMounts": [ 123 | { 124 | "name": "default-token-pvpz7", 125 | "readOnly": true, 126 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 127 | } 128 | ], 129 | "securityContext": { 130 | "privileged": true 131 | }, 132 | "terminationMessagePath": "/dev/termination-log", 133 | "terminationMessagePolicy": "File", 134 | "imagePullPolicy": "IfNotPresent" 135 | } 136 | ], 137 | "restartPolicy": "Always", 138 | "terminationGracePeriodSeconds": 30, 139 | "dnsPolicy": "ClusterFirst", 140 | "serviceAccountName": "default", 141 | "serviceAccount": "default", 142 | "securityContext": {}, 143 | "schedulerName": "default-scheduler", 144 | "tolerations": [ 145 | { 146 | "key": "node.kubernetes.io/not-ready", 147 | "operator": "Exists", 148 | "effect": "NoExecute", 149 | "tolerationSeconds": 300 150 | }, 151 | { 152 | "key": "node.kubernetes.io/unreachable", 153 | "operator": "Exists", 154 | "effect": "NoExecute", 155 | "tolerationSeconds": 300 156 | }, 157 | { 158 | "key": "dedicated", 159 | "operator": "Equal", 160 | "value": "tenantA", 161 | "effect": "NoSchedule" 162 | } 163 | ], 164 | "priority": 0, 165 | "enableServiceLinks": true, 166 | "preemptionPolicy": "PreemptLowerPriority" 167 | }, 168 | "status": { 169 | "phase": "Pending", 170 | "qosClass": "BestEffort" 171 | } 172 | }, 173 | "oldObject": null, 174 | "dryRun": false, 175 | "options": { 176 | "kind": "CreateOptions", 177 | "apiVersion": "meta.k8s.io/v1" 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /tests/data/privileged-pod.json: -------------------------------------------------------------------------------- 1 | { 2 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 3 | "kind": { 4 | "group": "", 5 | "version": "v1", 6 | "kind": "Pod" 7 | }, 8 | "resource": { 9 | "group": "", 10 | "version": "v1", 11 | "resource": "pods" 12 | }, 13 | "requestKind": { 14 | "group": "", 15 | "version": "v1", 16 | "kind": "Pod" 17 | }, 18 | "requestResource": { 19 | "group": "", 20 | "version": "v1", 21 | "resource": "pods" 22 | }, 23 | "name": "nginx", 24 | "namespace": "default", 25 | "operation": "CREATE", 26 | "userInfo": { 27 | "username": "kubernetes-admin", 28 | "groups": [ 29 | "system:masters", 30 | "system:authenticated" 31 | ] 32 | }, 33 | "object": { 34 | "kind": "Pod", 35 | "apiVersion": "v1", 36 | "metadata": { 37 | "name": "nginx", 38 | "namespace": "default", 39 | "uid": "04dc7a5e-e1f1-4e34-8d65-2c9337a43e64", 40 | "creationTimestamp": "2020-11-12T15:18:36Z", 41 | "labels": { 42 | "env": "test" 43 | }, 44 | "annotations": { 45 | "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"env\":\"test\"},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"imagePullPolicy\":\"IfNotPresent\",\"name\":\"nginx\"}],\"tolerations\":[{\"effect\":\"NoSchedule\",\"key\":\"example-key\",\"operator\":\"Exists\"}]}}\n" 46 | }, 47 | "managedFields": [ 48 | { 49 | "manager": "kubectl", 50 | "operation": "Update", 51 | "apiVersion": "v1", 52 | "time": "2020-11-12T15:18:36Z", 53 | "fieldsType": "FieldsV1", 54 | "fieldsV1": { 55 | "f:metadata": { 56 | "f:annotations": { 57 | ".": {}, 58 | "f:kubectl.kubernetes.io/last-applied-configuration": {} 59 | }, 60 | "f:labels": { 61 | ".": {}, 62 | "f:env": {} 63 | } 64 | }, 65 | "f:spec": { 66 | "f:containers": { 67 | "k:{\"name\":\"nginx\"}": { 68 | ".": {}, 69 | "f:image": {}, 70 | "f:imagePullPolicy": {}, 71 | "f:name": {}, 72 | "f:resources": {}, 73 | "f:terminationMessagePath": {}, 74 | "f:terminationMessagePolicy": {} 75 | } 76 | }, 77 | "f:dnsPolicy": {}, 78 | "f:enableServiceLinks": {}, 79 | "f:restartPolicy": {}, 80 | "f:schedulerName": {}, 81 | "f:securityContext": {}, 82 | "f:terminationGracePeriodSeconds": {}, 83 | "f:tolerations": {} 84 | } 85 | } 86 | } 87 | ] 88 | }, 89 | "spec": { 90 | "volumes": [ 91 | { 92 | "name": "default-token-pvpz7", 93 | "secret": { 94 | "secretName": "default-token-pvpz7" 95 | } 96 | } 97 | ], 98 | "containers": [ 99 | { 100 | "name": "sleeping-sidecar", 101 | "image": "alpine", 102 | "command": ["sleep", "1h"], 103 | "resources": {}, 104 | "volumeMounts": [ 105 | { 106 | "name": "default-token-pvpz7", 107 | "readOnly": true, 108 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 109 | } 110 | ], 111 | "terminationMessagePath": "/dev/termination-log", 112 | "terminationMessagePolicy": "File", 113 | "imagePullPolicy": "IfNotPresent" 114 | }, 115 | { 116 | "name": "nginx", 117 | "image": "nginx", 118 | "resources": {}, 119 | "volumeMounts": [ 120 | { 121 | "name": "default-token-pvpz7", 122 | "readOnly": true, 123 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 124 | } 125 | ], 126 | "securityContext": { 127 | "privileged": true 128 | }, 129 | "terminationMessagePath": "/dev/termination-log", 130 | "terminationMessagePolicy": "File", 131 | "imagePullPolicy": "IfNotPresent" 132 | } 133 | ], 134 | "restartPolicy": "Always", 135 | "terminationGracePeriodSeconds": 30, 136 | "dnsPolicy": "ClusterFirst", 137 | "serviceAccountName": "default", 138 | "serviceAccount": "default", 139 | "securityContext": {}, 140 | "schedulerName": "default-scheduler", 141 | "tolerations": [ 142 | { 143 | "key": "node.kubernetes.io/not-ready", 144 | "operator": "Exists", 145 | "effect": "NoExecute", 146 | "tolerationSeconds": 300 147 | }, 148 | { 149 | "key": "node.kubernetes.io/unreachable", 150 | "operator": "Exists", 151 | "effect": "NoExecute", 152 | "tolerationSeconds": 300 153 | }, 154 | { 155 | "key": "dedicated", 156 | "operator": "Equal", 157 | "value": "tenantA", 158 | "effect": "NoSchedule" 159 | } 160 | ], 161 | "priority": 0, 162 | "enableServiceLinks": true, 163 | "preemptionPolicy": "PreemptLowerPriority" 164 | }, 165 | "status": { 166 | "phase": "Pending", 167 | "qosClass": "BestEffort" 168 | } 169 | }, 170 | "oldObject": null, 171 | "dryRun": false, 172 | "options": { 173 | "kind": "CreateOptions", 174 | "apiVersion": "meta.k8s.io/v1" 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /tests/data/raw.json: -------------------------------------------------------------------------------- 1 | { 2 | "user": "tonio", 3 | "action": "eats", 4 | "resource": "banana" 5 | } 6 | -------------------------------------------------------------------------------- /tests/data/rego-annotate/metadata-correct.yml: -------------------------------------------------------------------------------- 1 | rules: 2 | - apiGroups: [""] 3 | apiVersions: ["v1"] 4 | resources: ["services"] 5 | operations: ["CREATE", "UPDATE"] 6 | mutating: false 7 | contextAware: false 8 | executionMode: gatekeeper 9 | annotations: 10 | io.kubewarden.policy.title: disallow-service-loadbalancer 11 | io.kubewarden.policy.description: Prevent the creation of Service resources of type `LoadBalancer` 12 | io.kubewarden.policy.author: Flavio Castelli 13 | io.kubewarden.policy.url: https://github.com/kubewarden/disallow-service-loadbalancer-policy 14 | io.kubewarden.policy.source: https://github.com/kubewarden/disallow-service-loadbalancer-policy 15 | io.kubewarden.policy.license: Apache-2.0 16 | io.kubewarden.policy.usage: | 17 | This policy works by inspecting `type` of `Service` resources and prevents the 18 | creation of Services with type `LoadBalancer`. 19 | 20 | Kubernetes network policies have no control over what is being exposed 21 | via these type of Services. Moreover, on public clouds, the creation of 22 | `LoadBalancer` Services leads to additional charges. 23 | 24 | Because of that, it's usually a safer choice to have 25 | tighter control over the creation of these type of Services. 26 | 27 | # Configuration 28 | 29 | This policy doesn't take any configuration value. 30 | -------------------------------------------------------------------------------- /tests/data/rego-annotate/metadata-wrong.yml: -------------------------------------------------------------------------------- 1 | rules: 2 | - apiGroups: [""] 3 | apiVersions: ["v1"] 4 | resources: ["services"] 5 | operations: ["CREATE", "UPDATE"] 6 | mutating: false 7 | contextAware: false 8 | annotations: 9 | io.kubewarden.policy.title: disallow-service-loadbalancer 10 | io.kubewarden.policy.description: Prevent the creation of Service resources of type `LoadBalancer` 11 | io.kubewarden.policy.author: Flavio Castelli 12 | io.kubewarden.policy.url: https://github.com/kubewarden/disallow-service-loadbalancer-policy 13 | io.kubewarden.policy.source: https://github.com/kubewarden/disallow-service-loadbalancer-policy 14 | io.kubewarden.policy.license: Apache-2.0 15 | io.kubewarden.policy.usage: | 16 | This policy works by inspecting `type` of `Service` resources and prevents the 17 | creation of Services with type `LoadBalancer`. 18 | 19 | Kubernetes network policies have no control over what is being exposed 20 | via these type of Services. Moreover, on public clouds, the creation of 21 | `LoadBalancer` Services leads to additional charges. 22 | 23 | Because of that, it's usually a safer choice to have 24 | tighter control over the creation of these type of Services. 25 | 26 | # Configuration 27 | 28 | This policy doesn't take any configuration value. 29 | -------------------------------------------------------------------------------- /tests/data/rego-annotate/no-default-namespace-rego.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kubewarden/kwctl/9ce7f59fdad72176a4a65f386a3e1e13496f2904/tests/data/rego-annotate/no-default-namespace-rego.wasm -------------------------------------------------------------------------------- /tests/data/sigstore/README.md: -------------------------------------------------------------------------------- 1 | # Sigstore artifacts 2 | 3 | This folder contains artifacts such as signing keys, used for testing 4 | [Sigstore](www.sigstore.dev) functionality. 5 | 6 | ## Verifying 7 | 8 | Verification tests are performed by signing with 9 | [cosign](https://github.com/sigstore/cosign), and verifying with `kwctl`. 10 | 11 | ### Recreating the image under test 12 | 13 | Obtain the same image under test, under our control: 14 | ```console 15 | $ kwctl pull registry://ghcr.io/kubewarden/policies/pod-privileged:v0.1.9 16 | $ kwctl push \ 17 | ~/.cache/kubewarden/store/registry/ghcr.io/kubewarden/policies/pod-privileged:v0.1.9 \ 18 | ghcr.io/kubewarden/tests/pod-privileged:v0.1.9 19 | ``` 20 | 21 | Sign it with 2 keys, key1 with 2 annotations, key2 with 1 annotation. Key3 is 22 | not used to sign this image (signing it pushes new images with the metadata, 23 | which will be triangulated back to our image): 24 | 25 | ```console 26 | $ COSIGN_PASSWORD=kubewarden cosign generate-key-pair 27 | $ mv cosign.key cosign1.key; mv cosign.pub cosign1.pub 28 | $ COSIGN_PASSWORD=kubewarden cosign sign \ 29 | --key cosign1.key -a env=prod -a stable=true \ 30 | ghcr.io/kubewarden/tests/pod-privileged:v0.1.9 31 | $ COSIGN_PASSWORD=kubewarden cosign generate-key-pair 32 | $ mv cosign.key cosign2.key; mv cosign.pub cosign2.pub 33 | $ COSIGN_PASSWORD=kubewarden cosign sign \ 34 | --key cosign2.key -a env=prod \ 35 | ghcr.io/kubewarden/tests/pod-privileged:v0.1.9 36 | ``` 37 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign1.key: -------------------------------------------------------------------------------- 1 | -----BEGIN ENCRYPTED COSIGN PRIVATE KEY----- 2 | eyJrZGYiOnsibmFtZSI6InNjcnlwdCIsInBhcmFtcyI6eyJOIjozMjc2OCwiciI6 3 | OCwicCI6MX0sInNhbHQiOiJtaTFBTXBXOXVZQ0ZROWF1TmdXcWNUb3o3Tzd6UlI2 4 | UXBJdEhDbEpISjh3PSJ9LCJjaXBoZXIiOnsibmFtZSI6Im5hY2wvc2VjcmV0Ym94 5 | Iiwibm9uY2UiOiJXRFQ0Y1A3MDNDdnJnVlFJNWpHZlNVNktDaEpONXZLOCJ9LCJj 6 | aXBoZXJ0ZXh0IjoiSFFTTzg3MUhCc1VBVTlNVi96Tmc2Q1phOWY3UWpBWjVIdTZI 7 | eWMvUzdROVIwNlQxWk1IM1dOc2FjcXI0UFV5SVd4QlBuWTZCcGx4cnd4b29vOFFC 8 | NERIUm8vRnFiRlg2a3NJak41WC9seW44dWd4SlRXdG9Lb0pYQU5sR0R0MzhoSjFw 9 | RGkyeGVNVWUxSVR3Y3MzOFdEK2l6cTgvQnJ6NjI5OUtiNjRWUU41UW0zR2psTW13 10 | V0lvZnFHclF4QUROVG1FRWc4R3NrRkJmTHc9PSJ9 11 | -----END ENCRYPTED COSIGN PRIVATE KEY----- 12 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign1.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQiTy5S+2JFvVlhUwWPLziM7iTM2j 3 | byLgh2IjpNQN0Uio/9pZOTP/CsJmXoUNshfpTUHd3OxgHgz/6adtf2nBwQ== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign2.key: -------------------------------------------------------------------------------- 1 | -----BEGIN ENCRYPTED COSIGN PRIVATE KEY----- 2 | eyJrZGYiOnsibmFtZSI6InNjcnlwdCIsInBhcmFtcyI6eyJOIjozMjc2OCwiciI6 3 | OCwicCI6MX0sInNhbHQiOiJmNkJ5Wnl1Mit2VHBwRTVpNUQ2YlovTWpoakVHWm5p 4 | RmNIcDVTN1RXZytNPSJ9LCJjaXBoZXIiOnsibmFtZSI6Im5hY2wvc2VjcmV0Ym94 5 | Iiwibm9uY2UiOiJZNWg3SVh0VHd4RGp1M1VlR0orYmh4aVBvMzZOeUszKyJ9LCJj 6 | aXBoZXJ0ZXh0IjoiMW1HUGhhbC9NaE94dnlwYVVHb3Jnb2lXU1R3ODdJbUJPZ1lx 7 | UHh1WDdNNmFwc3drVHZYYk9PKzNhYlZjaWpBNGdHRmJ5K0V0S1FYOHJiR1dNally 8 | NWt5NTFJZmRYaDRGZnlnUUxVQnRqdERRbmRlV2RDU2pEam9sM1JXRDNYK3VyU1BR 9 | eVQ3OFF0NHpEem0zUGkvRU9QeEFWSkVkMlMxSGRxSmdOdVBtaXpjTG05RXVTb2w4 10 | Y3hjZTRBUEVLZ0RwTzVVYXN2MldBeFJRd1E9PSJ9 11 | -----END ENCRYPTED COSIGN PRIVATE KEY----- 12 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign2.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx0HuqSss8DUIIUg3I006b1EQjj3Q 3 | igsTrvZ/Q3+h+81DkNJg4LzID1rz0UJFUcdzI5NqlFLSTDIQw0gVKOiK7g== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign3.key: -------------------------------------------------------------------------------- 1 | -----BEGIN ENCRYPTED COSIGN PRIVATE KEY----- 2 | eyJrZGYiOnsibmFtZSI6InNjcnlwdCIsInBhcmFtcyI6eyJOIjozMjc2OCwiciI6 3 | OCwicCI6MX0sInNhbHQiOiI4cjBQY1BwcGJTOENDbEJDaXVYM0dGMUxXVjBTVUxZ 4 | enZNQXB0VFIyMERJPSJ9LCJjaXBoZXIiOnsibmFtZSI6Im5hY2wvc2VjcmV0Ym94 5 | Iiwibm9uY2UiOiJIeklWYmJ3VVNPNzNPejVCVmJVV3NkTndYVFg5K2RxSCJ9LCJj 6 | aXBoZXJ0ZXh0IjoiVE9xK3NCSkxIYk5vN2dnVC92MkV0RklLby9UcjA4dk8zZzlQ 7 | bjZCNTNRclU4OTM5M09ZdytwQkJLZ2EzRmJxb04zcEdnalN5dWxrZTVvdFJoZVFH 8 | NmROYVVFT29kMTVYcjNjNzhXTzhhd291VkdGMEVnTFVZOHU1Sy9PcmcxS2tYZEl3 9 | eGxiOWNTU3d2Q1huNzdCR0tJSDB4bkIvaXZPZDdxSG94bTlQdzhUV1kzdVBpcXRn 10 | RWROQ04ycTJqVzEwNUNrRlR1N0dEcmVwQ2c9PSJ9 11 | -----END ENCRYPTED COSIGN PRIVATE KEY----- 12 | -------------------------------------------------------------------------------- /tests/data/sigstore/cosign3.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZHEdfvdm7kBmlBRLIN/2MixoSMZV 3 | 3flBBjmbjmlyEGEkm5/NfNqX+vvJFXz6DLwg0fh1RnJw9V/EAQyyx7e3qA== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /tests/data/sigstore/verification-config-keyless.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | 4 | allOf: 5 | - kind: genericIssuer 6 | issuer: https://token.actions.githubusercontent.com 7 | subject: 8 | urlPrefix: https://github.com/kubewarden 9 | -------------------------------------------------------------------------------- /tests/data/sigstore/verification-config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | 4 | allOf: 5 | - kind: pubKey 6 | owner: pubkey1.pub 7 | key: | 8 | -----BEGIN PUBLIC KEY----- 9 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQiTy5S+2JFvVlhUwWPLziM7iTM2j 10 | byLgh2IjpNQN0Uio/9pZOTP/CsJmXoUNshfpTUHd3OxgHgz/6adtf2nBwQ== 11 | -----END PUBLIC KEY----- 12 | annotations: 13 | env: prod 14 | stable: "true" 15 | - kind: pubKey 16 | owner: pubkey2.pub 17 | key: | 18 | -----BEGIN PUBLIC KEY----- 19 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEx0HuqSss8DUIIUg3I006b1EQjj3Q 20 | igsTrvZ/Q3+h+81DkNJg4LzID1rz0UJFUcdzI5NqlFLSTDIQw0gVKOiK7g== 21 | -----END PUBLIC KEY----- 22 | annotations: 23 | env: prod 24 | -------------------------------------------------------------------------------- /tests/data/unprivileged-pod-admission-review.json: -------------------------------------------------------------------------------- 1 | { 2 | "apiVersion": "admission.k8s.io/v1", 3 | "kind": "AdmissionReview", 4 | "request": { 5 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 6 | "kind": { 7 | "group": "", 8 | "version": "v1", 9 | "kind": "Pod" 10 | }, 11 | "resource": { 12 | "group": "", 13 | "version": "v1", 14 | "resource": "pods" 15 | }, 16 | "requestKind": { 17 | "group": "", 18 | "version": "v1", 19 | "kind": "Pod" 20 | }, 21 | "requestResource": { 22 | "group": "", 23 | "version": "v1", 24 | "resource": "pods" 25 | }, 26 | "name": "nginx", 27 | "namespace": "default", 28 | "operation": "CREATE", 29 | "userInfo": { 30 | "username": "kubernetes-admin", 31 | "groups": [ 32 | "system:masters", 33 | "system:authenticated" 34 | ] 35 | }, 36 | "object": { 37 | "kind": "Pod", 38 | "apiVersion": "v1", 39 | "metadata": { 40 | "name": "nginx", 41 | "namespace": "default", 42 | "uid": "04dc7a5e-e1f1-4e34-8d65-2c9337a43e64", 43 | "creationTimestamp": "2020-11-12T15:18:36Z", 44 | "labels": { 45 | "env": "test" 46 | }, 47 | "annotations": { 48 | "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"env\":\"test\"},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"imagePullPolicy\":\"IfNotPresent\",\"name\":\"nginx\"}],\"tolerations\":[{\"effect\":\"NoSchedule\",\"key\":\"example-key\",\"operator\":\"Exists\"}]}}\n" 49 | }, 50 | "managedFields": [ 51 | { 52 | "manager": "kubectl", 53 | "operation": "Update", 54 | "apiVersion": "v1", 55 | "time": "2020-11-12T15:18:36Z", 56 | "fieldsType": "FieldsV1", 57 | "fieldsV1": { 58 | "f:metadata": { 59 | "f:annotations": { 60 | ".": {}, 61 | "f:kubectl.kubernetes.io/last-applied-configuration": {} 62 | }, 63 | "f:labels": { 64 | ".": {}, 65 | "f:env": {} 66 | } 67 | }, 68 | "f:spec": { 69 | "f:containers": { 70 | "k:{\"name\":\"nginx\"}": { 71 | ".": {}, 72 | "f:image": {}, 73 | "f:imagePullPolicy": {}, 74 | "f:name": {}, 75 | "f:resources": {}, 76 | "f:terminationMessagePath": {}, 77 | "f:terminationMessagePolicy": {} 78 | } 79 | }, 80 | "f:dnsPolicy": {}, 81 | "f:enableServiceLinks": {}, 82 | "f:restartPolicy": {}, 83 | "f:schedulerName": {}, 84 | "f:securityContext": {}, 85 | "f:terminationGracePeriodSeconds": {}, 86 | "f:tolerations": {} 87 | } 88 | } 89 | } 90 | ] 91 | }, 92 | "spec": { 93 | "volumes": [ 94 | { 95 | "name": "default-token-pvpz7", 96 | "secret": { 97 | "secretName": "default-token-pvpz7" 98 | } 99 | } 100 | ], 101 | "containers": [ 102 | { 103 | "name": "sleeping-sidecar", 104 | "image": "alpine", 105 | "command": ["sleep", "1h"], 106 | "resources": {}, 107 | "volumeMounts": [ 108 | { 109 | "name": "default-token-pvpz7", 110 | "readOnly": true, 111 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 112 | } 113 | ], 114 | "terminationMessagePath": "/dev/termination-log", 115 | "terminationMessagePolicy": "File", 116 | "imagePullPolicy": "IfNotPresent" 117 | }, 118 | { 119 | "name": "nginx", 120 | "image": "nginx", 121 | "resources": {}, 122 | "volumeMounts": [ 123 | { 124 | "name": "default-token-pvpz7", 125 | "readOnly": true, 126 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 127 | } 128 | ], 129 | "securityContext": { 130 | "allowPrivilegeEscalation": false 131 | }, 132 | "terminationMessagePath": "/dev/termination-log", 133 | "terminationMessagePolicy": "File", 134 | "imagePullPolicy": "IfNotPresent" 135 | } 136 | ], 137 | "restartPolicy": "Always", 138 | "terminationGracePeriodSeconds": 30, 139 | "dnsPolicy": "ClusterFirst", 140 | "serviceAccountName": "default", 141 | "serviceAccount": "default", 142 | "securityContext": {}, 143 | "schedulerName": "default-scheduler", 144 | "tolerations": [ 145 | { 146 | "key": "node.kubernetes.io/not-ready", 147 | "operator": "Exists", 148 | "effect": "NoExecute", 149 | "tolerationSeconds": 300 150 | }, 151 | { 152 | "key": "node.kubernetes.io/unreachable", 153 | "operator": "Exists", 154 | "effect": "NoExecute", 155 | "tolerationSeconds": 300 156 | }, 157 | { 158 | "key": "dedicated", 159 | "operator": "Equal", 160 | "value": "tenantA", 161 | "effect": "NoSchedule" 162 | } 163 | ], 164 | "priority": 0, 165 | "enableServiceLinks": true, 166 | "preemptionPolicy": "PreemptLowerPriority" 167 | }, 168 | "status": { 169 | "phase": "Pending", 170 | "qosClass": "BestEffort" 171 | } 172 | }, 173 | "oldObject": null, 174 | "dryRun": false, 175 | "options": { 176 | "kind": "CreateOptions", 177 | "apiVersion": "meta.k8s.io/v1" 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /tests/data/unprivileged-pod.json: -------------------------------------------------------------------------------- 1 | { 2 | "uid": "1299d386-525b-4032-98ae-1949f69f9cfc", 3 | "kind": { 4 | "group": "", 5 | "version": "v1", 6 | "kind": "Pod" 7 | }, 8 | "resource": { 9 | "group": "", 10 | "version": "v1", 11 | "resource": "pods" 12 | }, 13 | "requestKind": { 14 | "group": "", 15 | "version": "v1", 16 | "kind": "Pod" 17 | }, 18 | "requestResource": { 19 | "group": "", 20 | "version": "v1", 21 | "resource": "pods" 22 | }, 23 | "name": "nginx", 24 | "namespace": "default", 25 | "operation": "CREATE", 26 | "userInfo": { 27 | "username": "kubernetes-admin", 28 | "groups": [ 29 | "system:masters", 30 | "system:authenticated" 31 | ] 32 | }, 33 | "object": { 34 | "kind": "Pod", 35 | "apiVersion": "v1", 36 | "metadata": { 37 | "name": "nginx", 38 | "namespace": "default", 39 | "uid": "04dc7a5e-e1f1-4e34-8d65-2c9337a43e64", 40 | "creationTimestamp": "2020-11-12T15:18:36Z", 41 | "labels": { 42 | "env": "test" 43 | }, 44 | "annotations": { 45 | "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"labels\":{\"env\":\"test\"},\"name\":\"nginx\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"image\":\"nginx\",\"imagePullPolicy\":\"IfNotPresent\",\"name\":\"nginx\"}],\"tolerations\":[{\"effect\":\"NoSchedule\",\"key\":\"example-key\",\"operator\":\"Exists\"}]}}\n" 46 | }, 47 | "managedFields": [ 48 | { 49 | "manager": "kubectl", 50 | "operation": "Update", 51 | "apiVersion": "v1", 52 | "time": "2020-11-12T15:18:36Z", 53 | "fieldsType": "FieldsV1", 54 | "fieldsV1": { 55 | "f:metadata": { 56 | "f:annotations": { 57 | ".": {}, 58 | "f:kubectl.kubernetes.io/last-applied-configuration": {} 59 | }, 60 | "f:labels": { 61 | ".": {}, 62 | "f:env": {} 63 | } 64 | }, 65 | "f:spec": { 66 | "f:containers": { 67 | "k:{\"name\":\"nginx\"}": { 68 | ".": {}, 69 | "f:image": {}, 70 | "f:imagePullPolicy": {}, 71 | "f:name": {}, 72 | "f:resources": {}, 73 | "f:terminationMessagePath": {}, 74 | "f:terminationMessagePolicy": {} 75 | } 76 | }, 77 | "f:dnsPolicy": {}, 78 | "f:enableServiceLinks": {}, 79 | "f:restartPolicy": {}, 80 | "f:schedulerName": {}, 81 | "f:securityContext": {}, 82 | "f:terminationGracePeriodSeconds": {}, 83 | "f:tolerations": {} 84 | } 85 | } 86 | } 87 | ] 88 | }, 89 | "spec": { 90 | "volumes": [ 91 | { 92 | "name": "default-token-pvpz7", 93 | "secret": { 94 | "secretName": "default-token-pvpz7" 95 | } 96 | } 97 | ], 98 | "containers": [ 99 | { 100 | "name": "sleeping-sidecar", 101 | "image": "alpine", 102 | "command": ["sleep", "1h"], 103 | "resources": {}, 104 | "volumeMounts": [ 105 | { 106 | "name": "default-token-pvpz7", 107 | "readOnly": true, 108 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 109 | } 110 | ], 111 | "terminationMessagePath": "/dev/termination-log", 112 | "terminationMessagePolicy": "File", 113 | "imagePullPolicy": "IfNotPresent" 114 | }, 115 | { 116 | "name": "nginx", 117 | "image": "nginx", 118 | "resources": {}, 119 | "volumeMounts": [ 120 | { 121 | "name": "default-token-pvpz7", 122 | "readOnly": true, 123 | "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount" 124 | } 125 | ], 126 | "securityContext": { 127 | "allowPrivilegeEscalation": false 128 | }, 129 | "terminationMessagePath": "/dev/termination-log", 130 | "terminationMessagePolicy": "File", 131 | "imagePullPolicy": "IfNotPresent" 132 | } 133 | ], 134 | "restartPolicy": "Always", 135 | "terminationGracePeriodSeconds": 30, 136 | "dnsPolicy": "ClusterFirst", 137 | "serviceAccountName": "default", 138 | "serviceAccount": "default", 139 | "securityContext": {}, 140 | "schedulerName": "default-scheduler", 141 | "tolerations": [ 142 | { 143 | "key": "node.kubernetes.io/not-ready", 144 | "operator": "Exists", 145 | "effect": "NoExecute", 146 | "tolerationSeconds": 300 147 | }, 148 | { 149 | "key": "node.kubernetes.io/unreachable", 150 | "operator": "Exists", 151 | "effect": "NoExecute", 152 | "tolerationSeconds": 300 153 | }, 154 | { 155 | "key": "dedicated", 156 | "operator": "Equal", 157 | "value": "tenantA", 158 | "effect": "NoSchedule" 159 | } 160 | ], 161 | "priority": 0, 162 | "enableServiceLinks": true, 163 | "preemptionPolicy": "PreemptLowerPriority" 164 | }, 165 | "status": { 166 | "phase": "Pending", 167 | "qosClass": "BestEffort" 168 | } 169 | }, 170 | "oldObject": null, 171 | "dryRun": false, 172 | "options": { 173 | "kind": "CreateOptions", 174 | "apiVersion": "meta.k8s.io/v1" 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /tests/data/vap/vap-binding.yml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1 2 | kind: ValidatingAdmissionPolicyBinding 3 | metadata: 4 | name: "kw-scaffold-demo" 5 | spec: 6 | policyName: "vap-test" 7 | validationActions: [Deny] 8 | matchResources: 9 | namespaceSelector: 10 | matchLabels: 11 | kubernetes.io/metadata.name: default 12 | -------------------------------------------------------------------------------- /tests/data/vap/vap-with-variables.yml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1 2 | kind: ValidatingAdmissionPolicy 3 | metadata: 4 | name: "force-liveness-probe" 5 | spec: 6 | failurePolicy: Fail 7 | variables: 8 | - name: containers_without_liveness_probe 9 | expression: "object.spec.template.spec.containers.filter(c, !has(c.livenessProbe)).map(c, c.name)" 10 | matchConstraints: 11 | resourceRules: 12 | - apiGroups: ["apps"] 13 | apiVersions: ["v1"] 14 | operations: ["CREATE", "UPDATE"] 15 | resources: ["deployments"] 16 | validations: 17 | - expression: "size(variables.containers_without_liveness_probe) == 0" 18 | messageExpression: "'These containers are missing a liveness probe: ' + variables.containers_without_liveness_probe.join(' ')" 19 | reason: Invalid 20 | -------------------------------------------------------------------------------- /tests/data/vap/vap-without-variables.yml: -------------------------------------------------------------------------------- 1 | apiVersion: admissionregistration.k8s.io/v1 2 | kind: ValidatingAdmissionPolicy 3 | metadata: 4 | name: "vap-test" 5 | spec: 6 | failurePolicy: Fail 7 | matchConstraints: 8 | resourceRules: 9 | - apiGroups: ["apps"] 10 | apiVersions: ["v1"] 11 | operations: ["CREATE", "UPDATE"] 12 | resources: ["deployments", "deployments/scale"] 13 | validations: 14 | - expression: "object.spec.replicas > 2" 15 | message: "should have at least 2 replicas" 16 | - expression: "object.spec.replicas <= 10" 17 | message: "should have at most 5 replicas" 18 | - expression: "object.spec.replicas % 2 != 0" 19 | message: "should have an odd number of replicas" 20 | -------------------------------------------------------------------------------- /tests/secure_supply_chain_e2e.rs: -------------------------------------------------------------------------------- 1 | use assert_cmd::Command; 2 | use common::{setup_command, test_data}; 3 | use predicates::{prelude::*, str::contains}; 4 | use rstest::rstest; 5 | use std::{fs, path::Path}; 6 | use tempfile::tempdir; 7 | 8 | mod common; 9 | 10 | fn cosign_initialize(path: &Path) { 11 | let mut cmd = Command::new("cosign"); 12 | cmd.env("HOME", path).arg("initialize"); 13 | cmd.assert().success(); 14 | } 15 | 16 | #[test] 17 | fn test_verify_tuf_integration() { 18 | let tempdir = tempdir().unwrap(); 19 | let mut cmd = setup_command(tempdir.path()); 20 | 21 | cmd.arg("verify") 22 | .arg("--verification-config-path") 23 | .arg(test_data("sigstore/verification-config-keyless.yml")) 24 | .arg("registry://ghcr.io/kubewarden/tests/capabilities-psp:v0.1.9"); 25 | 26 | cmd.assert().success(); 27 | 28 | // TODO: uncomment once https://github.com/sigstore/sigstore-rs/issues/345 is fixed 29 | // 30 | // let fulcio_and_rekor_data_path = Path::new(tempdir.path()) 31 | // .join(".config") 32 | // .join("kubewarden") 33 | // .join("fulcio_and_rekor_data"); 34 | // 35 | // assert!(std::fs::metadata(fulcio_and_rekor_data_path.join("fulcio.crt.pem")).is_ok()); 36 | // assert!(std::fs::metadata(fulcio_and_rekor_data_path.join("fulcio_v1.crt.pem")).is_ok()); 37 | // assert!(std::fs::metadata(fulcio_and_rekor_data_path.join("rekor.pub")).is_ok()); 38 | } 39 | 40 | #[test] 41 | fn test_verify_fulcio_cert_path() { 42 | let tempdir = tempdir().unwrap(); 43 | cosign_initialize(tempdir.path()); 44 | 45 | let mut cmd = setup_command(tempdir.path()); 46 | cmd.arg("verify") 47 | .arg("--fulcio-cert-path") 48 | .arg(".sigstore/root/targets/fulcio.crt.pem") 49 | .arg("--fulcio-cert-path") 50 | .arg(".sigstore/root/targets/fulcio_v1.crt.pem") 51 | .arg("--rekor-public-key-path") 52 | .arg(".sigstore/root/targets/rekor.pub") 53 | .arg("--verification-config-path") 54 | .arg(test_data("sigstore/verification-config.yml")) 55 | .arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.2.5"); 56 | 57 | cmd.assert().success(); 58 | } 59 | 60 | #[test] 61 | fn test_verify_fulcio_cert_path_no_rekor_public_key() { 62 | let tempdir = tempdir().unwrap(); 63 | cosign_initialize(tempdir.path()); 64 | 65 | let mut cmd = setup_command(tempdir.path()); 66 | cmd.arg("verify") 67 | .arg("--fulcio-cert-path") 68 | .arg(".sigstore/root/targets/fulcio.crt.pem") 69 | .arg("--verification-config-path") 70 | .arg(test_data("sigstore/verification-config.yml")) 71 | .arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.2.5"); 72 | 73 | cmd.assert().failure(); 74 | cmd.assert().stderr(contains( 75 | "both a fulcio certificate and a rekor public key are required", 76 | )); 77 | } 78 | 79 | #[test] 80 | fn test_verify_rekor_public_key_no_certs() { 81 | let tempdir = tempdir().unwrap(); 82 | cosign_initialize(tempdir.path()); 83 | 84 | let mut cmd = setup_command(tempdir.path()); 85 | cmd.arg("verify") 86 | .arg("--rekor-public-key-path") 87 | .arg(".sigstore/root/targets/rekor.pub") 88 | .arg("--verification-config-path") 89 | .arg(test_data("sigstore/verification-config.yml")) 90 | .arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.2.5"); 91 | 92 | cmd.assert().failure(); 93 | cmd.assert().stderr(contains( 94 | "both a fulcio certificate and a rekor public key are required", 95 | )); 96 | } 97 | 98 | #[test] 99 | fn test_verify_missing_signatures() { 100 | let tempdir = tempdir().unwrap(); 101 | cosign_initialize(tempdir.path()); 102 | 103 | let mut cmd = setup_command(tempdir.path()); 104 | cmd.arg("verify") 105 | .arg("--fulcio-cert-path") 106 | .arg(".sigstore/root/targets/fulcio.crt.pem") 107 | .arg("--fulcio-cert-path") 108 | .arg(".sigstore/root/targets/fulcio_v1.crt.pem") 109 | .arg("--rekor-public-key-path") 110 | .arg(".sigstore/root/targets/rekor.pub") 111 | .arg("--verification-config-path") 112 | .arg(test_data("sigstore/verification-config.yml")) 113 | .arg("registry://ghcr.io/kubewarden/tests/capabilities-psp:v0.1.9"); 114 | 115 | cmd.assert().failure(); 116 | cmd.assert() 117 | .stderr(contains("Image verification failed: missing signatures")); 118 | } 119 | 120 | #[test] 121 | fn test_verify_keyless() { 122 | let tempdir = tempdir().unwrap(); 123 | cosign_initialize(tempdir.path()); 124 | 125 | let mut cmd = setup_command(tempdir.path()); 126 | cmd.arg("verify") 127 | .arg("--fulcio-cert-path") 128 | .arg(".sigstore/root/targets/fulcio.crt.pem") 129 | .arg("--fulcio-cert-path") 130 | .arg(".sigstore/root/targets/fulcio_v1.crt.pem") 131 | .arg("--rekor-public-key-path") 132 | .arg(".sigstore/root/targets/rekor.pub") 133 | .arg("--verification-config-path") 134 | .arg(test_data("sigstore/verification-config.yml")) 135 | .arg("registry://ghcr.io/kubewarden/tests/capabilities-psp:v0.1.9"); 136 | 137 | cmd.assert().failure(); 138 | cmd.assert() 139 | .stderr(contains("Image verification failed: missing signatures")); 140 | } 141 | 142 | #[test] 143 | fn test_verify_scaffolded_verification_config() { 144 | let tempdir = tempdir().unwrap(); 145 | cosign_initialize(tempdir.path()); 146 | 147 | let mut cmd = setup_command(tempdir.path()); 148 | cmd.arg("scaffold").arg("verification-config"); 149 | cmd.assert().success(); 150 | 151 | let kubwarden_config_path = Path::new(tempdir.path()).join(".config").join("kubewarden"); 152 | fs::create_dir_all(&kubwarden_config_path).unwrap(); 153 | 154 | let verification_config = cmd.output().unwrap().stdout; 155 | let verification_config_path = Path::new(tempdir.path()) 156 | .join(&kubwarden_config_path) 157 | .join("verification-config.yml"); 158 | fs::write(&verification_config_path, verification_config).unwrap(); 159 | 160 | let mut cmd = setup_command(tempdir.path()); 161 | cmd.arg("verify") 162 | .arg("--fulcio-cert-path") 163 | .arg(".sigstore/root/targets/fulcio.crt.pem") 164 | .arg("--fulcio-cert-path") 165 | .arg(".sigstore/root/targets/fulcio_v1.crt.pem") 166 | .arg("--rekor-public-key-path") 167 | .arg(".sigstore/root/targets/rekor.pub") 168 | .arg("--verification-config-path") 169 | .arg(&verification_config_path) 170 | .arg("registry://ghcr.io/kubewarden/tests/capabilities-psp:v0.1.9"); 171 | 172 | cmd.assert().success(); 173 | } 174 | 175 | #[rstest] 176 | #[case( 177 | &["sigstore/cosign1.pub"], 178 | &["env=prod", "stable=true"], 179 | true, 180 | contains("Policy successfully verified") 181 | )] 182 | #[case( 183 | &["sigstore/cosign1.pub", "sigstore/cosign2.pub"], 184 | &["env=prod"], 185 | true, 186 | contains("Policy successfully verified") 187 | )] 188 | #[case::no_keys( 189 | &[], 190 | &["env=prod"], 191 | false, 192 | contains("Intending to verify annotations, but no verification keys, OIDC issuer or GitHub owner were passed") 193 | )] 194 | #[case::non_existing_key( 195 | &["non_existing_key.pub"], 196 | &["env=prod", "stable=true"], 197 | false, 198 | contains("No such file or directory") 199 | )] 200 | #[case::missing_signatures( 201 | &["sigstore/cosign2.pub"], 202 | &["env=prod", "stable=true"], 203 | false, 204 | contains("Image verification failed: missing signatures") 205 | )] 206 | fn test_verify_oci_registry( 207 | #[case] keys: &[&str], 208 | #[case] annotations: &[&str], 209 | #[case] success: bool, 210 | #[case] predicate: impl PredicateStrExt, 211 | ) { 212 | let tempdir = tempdir().unwrap(); 213 | let mut cmd = setup_command(tempdir.path()); 214 | 215 | cmd.arg("verify"); 216 | for annotation in annotations { 217 | cmd.arg("-a").arg(annotation); 218 | } 219 | for key in keys { 220 | cmd.arg("-k").arg(test_data(key)); 221 | } 222 | cmd.arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9"); 223 | 224 | if success { 225 | cmd.assert().success(); 226 | } else { 227 | cmd.assert().failure(); 228 | } 229 | 230 | cmd.assert().stderr(predicate); 231 | } 232 | 233 | #[rstest] 234 | #[case( 235 | &["sigstore/cosign1.pub"], 236 | true, 237 | contains("Policy successfully verified") 238 | )] 239 | #[case::no_keys( 240 | &[], 241 | false, 242 | contains("Intending to verify annotations, but no verification keys, OIDC issuer or GitHub owner were passed") 243 | )] 244 | #[case::missing_signatures( 245 | &["sigstore/cosign2.pub"], 246 | false,contains("Image verification failed: missing signatures") 247 | )] 248 | fn test_pull_signed_policy( 249 | #[case] keys: &[&str], 250 | #[case] success: bool, 251 | #[case] predicate: impl PredicateStrExt, 252 | ) { 253 | let tempdir = tempdir().unwrap(); 254 | let mut cmd = setup_command(tempdir.path()); 255 | 256 | cmd.arg("pull") 257 | .arg("-a") 258 | .arg("env=prod") 259 | .arg("-a") 260 | .arg("stable=true"); 261 | for key in keys { 262 | cmd.arg("-k").arg(test_data(key)); 263 | } 264 | cmd.arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9"); 265 | 266 | if success { 267 | cmd.assert().success(); 268 | } else { 269 | cmd.assert().failure(); 270 | } 271 | 272 | cmd.assert().stderr(predicate); 273 | } 274 | 275 | #[rstest] 276 | #[case::good_keys( 277 | &["sigstore/cosign1.pub", "sigstore/cosign2.pub"], 278 | true, 279 | contains("Policy successfully verified") 280 | )] 281 | #[case::wrong_key( 282 | &["sigstore/cosign1.pub", "sigstore/cosign3.pub"], 283 | false, 284 | contains("Image verification failed: missing signatures")) 285 | ] 286 | fn test_run_signed_policy( 287 | #[case] keys: &[&str], 288 | #[case] success: bool, 289 | #[case] predicate: impl PredicateStrExt, 290 | ) { 291 | let tempdir = tempdir().unwrap(); 292 | let mut cmd = setup_command(tempdir.path()); 293 | 294 | cmd.arg("run") 295 | .arg("-a") 296 | .arg("env=prod") 297 | .arg("--request-path") 298 | .arg(test_data("privileged-pod.json")); 299 | for key in keys { 300 | cmd.arg("-k").arg(test_data(key)); 301 | } 302 | cmd.arg("registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9"); 303 | 304 | if success { 305 | cmd.assert().success(); 306 | } else { 307 | cmd.assert().failure(); 308 | } 309 | 310 | cmd.assert().stderr(predicate); 311 | } 312 | 313 | #[rstest] 314 | #[case::success( 315 | "registry://ghcr.io/kubewarden/tests/pod-privileged:v0.1.9", 316 | true, 317 | contains("Policy successfully verified") 318 | )] 319 | #[case::missing_signatures( 320 | "registry://ghcr.io/kubewarden/tests/capabilities-psp:v0.1.9", 321 | false, 322 | contains("Image verification failed: missing signatures") 323 | )] 324 | fn test_run_signed_policy_verification_config( 325 | #[case] uri: &str, 326 | #[case] success: bool, 327 | #[case] predicate: impl PredicateStrExt, 328 | ) { 329 | let tempdir = tempdir().unwrap(); 330 | cosign_initialize(tempdir.path()); 331 | 332 | let mut cmd = setup_command(tempdir.path()); 333 | cmd.arg("run") 334 | .arg("--fulcio-cert-path") 335 | .arg(".sigstore/root/targets/fulcio.crt.pem") 336 | .arg("--fulcio-cert-path") 337 | .arg(".sigstore/root/targets/fulcio_v1.crt.pem") 338 | .arg("--rekor-public-key-path") 339 | .arg(".sigstore/root/targets/rekor.pub") 340 | .arg("--verification-config-path") 341 | .arg(test_data("sigstore/verification-config.yml")) 342 | .arg("--request-path") 343 | .arg(test_data("privileged-pod.json")) 344 | .arg(uri); 345 | 346 | if success { 347 | cmd.assert().success(); 348 | } else { 349 | cmd.assert().failure(); 350 | } 351 | 352 | cmd.assert().stderr(predicate); 353 | } 354 | -------------------------------------------------------------------------------- /updatecli/DEVELOP.md: -------------------------------------------------------------------------------- 1 | To test the updatecli manifests locally: 2 | 3 | ```console 4 | export UPDATECLI_GITHUB_TOKEN= 5 | UPDATECLI_GITHUB_OWNER= updatecli diff --config updatecli/updatecli.d/update-rust-toolchain.yaml --values updatecli/values.yaml 6 | ``` 7 | -------------------------------------------------------------------------------- /updatecli/updatecli.d/update-rust-toolchain.yaml: -------------------------------------------------------------------------------- 1 | name: Update Rust version inside of rust-toolchain file 2 | 3 | scms: 4 | github: 5 | kind: github 6 | spec: 7 | user: "{{ .github.author }}" 8 | email: "{{ .github.email }}" 9 | owner: "{{ requiredEnv .github.owner }}" 10 | repository: "kwctl" 11 | token: "{{ requiredEnv .github.token }}" 12 | username: "{{ requiredEnv .github.user }}" 13 | branch: "{{ .github.branch }}" 14 | commitusingapi: true # enable cryptographically signed commits 15 | commitmessage: 16 | hidecredit: true 17 | 18 | sources: 19 | rust-lang: 20 | name: Get the latest release of Rust from rust-lang 21 | kind: githubrelease 22 | spec: 23 | owner: rust-lang 24 | repository: rust 25 | token: "{{ requiredEnv .github.token }}" 26 | versionfilter: 27 | kind: semver 28 | pattern: "*" 29 | 30 | targets: 31 | dataFile: 32 | name: 'deps(rust): update Rust version to {{ source "rust-lang" }}' 33 | kind: toml 34 | scmid: github 35 | spec: 36 | file: "rust-toolchain.toml" 37 | key: toolchain.channel 38 | 39 | actions: 40 | default: 41 | kind: github/pullrequest 42 | scmid: github 43 | spec: 44 | labels: 45 | - kind/chore 46 | -------------------------------------------------------------------------------- /updatecli/values.yaml: -------------------------------------------------------------------------------- 1 | github: 2 | owner: "UPDATECLI_GITHUB_OWNER" 3 | token: "UPDATECLI_GITHUB_TOKEN" 4 | branch: "main" 5 | author: "Kubewarden bot" 6 | email: "cncf-kubewarden-maintainers@lists.cncf.io" 7 | user: "UPDATECLI_GITHUB_OWNER" 8 | --------------------------------------------------------------------------------