mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-09 01:16:55 +00:00
* types added Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added secret fetching and client creation Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * codegen Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fixed tests Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * validate target resource scope & namespace settings (#7098) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: mutation code (#7095) * fix: mutation code Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * kuttl tests Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * lazy loading of context vars (#7071) * lazy loading of context vars Signed-off-by: Jim Bugwadia <jim@nirmata.com> * gofumpt Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add kuttl tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> --------- Signed-off-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * moved to policy context Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * removed errors Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * RegistryClientLoader Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * [Feature] Add kuttl tests with policy exceptions disabled (#7117) * added tests Signed-off-by: Ved Ratan <vedratan8@gmail.com> * removed redundant code Signed-off-by: Ved Ratan <vedratan8@gmail.com> * fix Signed-off-by: Ved Ratan <vedratan8@gmail.com> * fix Signed-off-by: Ved Ratan <vedratan8@gmail.com> * typo fix and README changes Signed-off-by: Ved Ratan <vedratan8@gmail.com> * fix Signed-off-by: Ved Ratan <vedratan8@gmail.com> --------- Signed-off-by: Ved Ratan <vedratan8@gmail.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Conditions message (#7113) * add message to conditions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * extend tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> --------- Signed-off-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump zgosalvez/github-actions-ensure-sha-pinned-actions (#7123) Bumps [zgosalvez/github-actions-ensure-sha-pinned-actions](https://github.com/zgosalvez/github-actions-ensure-sha-pinned-actions) from 2.1.2 to 2.1.3. - [Release notes](https://github.com/zgosalvez/github-actions-ensure-sha-pinned-actions/releases) - [Commits](21991cec25...555a30da26
) --- updated-dependencies: - dependency-name: zgosalvez/github-actions-ensure-sha-pinned-actions dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigs.k8s.io/kustomize/kyaml from 0.14.1 to 0.14.2 (#7121) Bumps [sigs.k8s.io/kustomize/kyaml](https://github.com/kubernetes-sigs/kustomize) from 0.14.1 to 0.14.2. - [Release notes](https://github.com/kubernetes-sigs/kustomize/releases) - [Commits](https://github.com/kubernetes-sigs/kustomize/compare/kyaml/v0.14.1...kyaml/v0.14.2) --- updated-dependencies: - dependency-name: sigs.k8s.io/kustomize/kyaml dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump oras.land/oras-go/v2 from 2.0.2 to 2.1.0 (#7102) Bumps [oras.land/oras-go/v2](https://github.com/oras-project/oras-go) from 2.0.2 to 2.1.0. - [Release notes](https://github.com/oras-project/oras-go/releases) - [Commits](https://github.com/oras-project/oras-go/compare/v2.0.2...v2.1.0) --- updated-dependencies: - dependency-name: oras.land/oras-go/v2 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * add condition msg to v2beta1 (#7126) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * feat: print container flags and their values (#7127) * add condition msg to v2beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * print flags settings Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * remove the container flag genWorker from the admission controller (#7132) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump google.golang.org/grpc from 1.54.0 to 1.55.0 (#7103) Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.54.0 to 1.55.0. - [Release notes](https://github.com/grpc/grpc-go/releases) - [Commits](https://github.com/grpc/grpc-go/compare/v1.54.0...v1.55.0) --- updated-dependencies: - dependency-name: google.golang.org/grpc dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * remove the duplicate entry (#7125) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigs.k8s.io/kustomize/api from 0.13.2 to 0.13.3 (#7120) Bumps [sigs.k8s.io/kustomize/api](https://github.com/kubernetes-sigs/kustomize) from 0.13.2 to 0.13.3. - [Release notes](https://github.com/kubernetes-sigs/kustomize/releases) - [Commits](https://github.com/kubernetes-sigs/kustomize/compare/api/v0.13.2...api/v0.13.3) --- updated-dependencies: - dependency-name: sigs.k8s.io/kustomize/api dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * update background scan logging messages (#7142) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Update chart with v2 to v3 migration guidance. (#7144) * add Saxo Bank and Velux as adopters Signed-off-by: Chip Zoller <chipzoller@gmail.com> * update chart README and validations Signed-off-by: Chip Zoller <chipzoller@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Chip Zoller <chipzoller@gmail.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * add Controller Internals info (#7147) Signed-off-by: Chip Zoller <chipzoller@gmail.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Supporting ValidatingAdmissionPolicy in kyverno cli (apply and test command) (#6656) * feat: add policy reporter to the dev lab Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * refactor: remove obsolete structs from CLI Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * Supporting ValidatingAdmissionPolicy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.26.3 to v0.27.0-rc.0 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno apply Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Support validating admission policy in kyverno test Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * refactoring Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding kyverno apply tests for validating admission policy Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * running codegen-all Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Adding IsVap field in TestResults Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * chore: bump k8s from v0.27.0-rc.0 to v0.27.1 Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * fix Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * Fix vap in engine response Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigs.k8s.io/kustomize/api from 0.13.3 to 0.13.4 (#7150) Bumps [sigs.k8s.io/kustomize/api](https://github.com/kubernetes-sigs/kustomize) from 0.13.3 to 0.13.4. - [Release notes](https://github.com/kubernetes-sigs/kustomize/releases) - [Commits](https://github.com/kubernetes-sigs/kustomize/compare/api/v0.13.3...api/v0.13.4) --- updated-dependencies: - dependency-name: sigs.k8s.io/kustomize/api dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump golang.org/x/crypto from 0.8.0 to 0.9.0 (#7149) Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.8.0 to 0.9.0. - [Commits](https://github.com/golang/crypto/compare/v0.8.0...v0.9.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Added `omit-events` flag to allow disabling of event emission (#7010) * added comma seperated flag Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * reason added in logs Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added requested changes Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * kuttl test init Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * updated kuttl tests Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * updated behavior Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fixed flawed behavior Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * updated test location and added readme Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * tests Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * updated step Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * omit events Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> --------- Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: let reports controller quit when loosing the lead (#7153) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump slsa-framework/slsa-github-generator (#7160) Bumps [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator) from 1.5.0 to 1.6.0. - [Release notes](https://github.com/slsa-framework/slsa-github-generator/releases) - [Changelog](https://github.com/slsa-framework/slsa-github-generator/blob/main/CHANGELOG.md) - [Commits](https://github.com/slsa-framework/slsa-github-generator/compare/v1.5.0...v1.6.0) --- updated-dependencies: - dependency-name: slsa-framework/slsa-github-generator dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore: bump otel deps (#7152) * chore: bump otel deps Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/cloudflare/circl from 1.3.2 to 1.3.3 (#7172) Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/docker/distribution (#7171) Bumps [github.com/docker/distribution](https://github.com/docker/distribution) from 2.8.1+incompatible to 2.8.2+incompatible. - [Release notes](https://github.com/docker/distribution/releases) - [Commits](https://github.com/docker/distribution/compare/v2.8.1...v2.8.2) --- updated-dependencies: - dependency-name: github.com/docker/distribution dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/go-logr/zapr from 1.2.3 to 1.2.4 (#7177) Bumps [github.com/go-logr/zapr](https://github.com/go-logr/zapr) from 1.2.3 to 1.2.4. - [Release notes](https://github.com/go-logr/zapr/releases) - [Commits](https://github.com/go-logr/zapr/compare/v1.2.3...v1.2.4) --- updated-dependencies: - dependency-name: github.com/go-logr/zapr dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Add refactor note (#7169) Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fixed typo in the v2 to v3 helm migration guide (#7163) * fixed typo in the v2 to v3 helm migration guide Signed-off-by: Richard Parke <richardparke15@gmail.com> * codegen Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Richard Parke <richardparke15@gmail.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/distribution/distribution (#7178) Bumps [github.com/distribution/distribution](https://github.com/distribution/distribution) from 2.8.1+incompatible to 2.8.2+incompatible. - [Release notes](https://github.com/distribution/distribution/releases) - [Commits](https://github.com/distribution/distribution/compare/v2.8.1...v2.8.2) --- updated-dependencies: - dependency-name: github.com/distribution/distribution dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * tweaks (#7166) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * feat: add logging feature to helm chart (#7181) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * refactor: hide json context from caller (#7139) * refactor: hide json context from caller Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * unit tests Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * feat: add omit-events feature in helm chart (#7185) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: preconditions in mutate existing rules (#7183) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: use structured jsonpatch instead of byte arrays (#7186) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added secret lister Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * changes from review Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added rclientloader to policy context Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * refactor changes Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * NIT Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added RegistryClientLoaderNewOrDie to policy context Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * CI fixes Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: panic for policy variable validation (#7079) * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * check errors Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: remove policy-reporter from dev lab (#7196) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: cleanup controller metrics name (#7198) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: http request metrics (#7197) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * remove unused code (#7203) Signed-off-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * handle Deny rules where conditions eval to true (#7204) Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * [Bug] Enforce message wrong (#7208) * fix Signed-off-by: Ved Ratan <vedratan8@gmail.com> * fixed tests Signed-off-by: Ved Ratan <vedratan8@gmail.com> --------- Signed-off-by: Ved Ratan <vedratan8@gmail.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump codecov/codecov-action from 3.1.3 to 3.1.4 (#7207) Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 3.1.3 to 3.1.4. - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](894ff025c7...eaaf4bedf3
) --- updated-dependencies: - dependency-name: codecov/codecov-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigstore/cosign-installer from 3.0.3 to 3.0.4 (#7215) Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 3.0.3 to 3.0.4. - [Release notes](https://github.com/sigstore/cosign-installer/releases) - [Commits](204a51a57a...03d0fecf17
) --- updated-dependencies: - dependency-name: sigstore/cosign-installer dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: panic in reports controller (#7220) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: mutate existing auth check (#7219) * fix auth check when using variables in ns Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl tests Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: do not exclude kube-system service accounts by default (#7225) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * docs: add reports system design doc (#6949) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump k8s.io/apimachinery from 0.27.1 to 0.27.2 (#7227) Bumps [k8s.io/apimachinery](https://github.com/kubernetes/apimachinery) from 0.27.1 to 0.27.2. - [Commits](https://github.com/kubernetes/apimachinery/compare/v0.27.1...v0.27.2) --- updated-dependencies: - dependency-name: k8s.io/apimachinery dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: shuting <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump k8s.io/cli-runtime from 0.27.1 to 0.27.2 (#7228) Bumps [k8s.io/cli-runtime](https://github.com/kubernetes/cli-runtime) from 0.27.1 to 0.27.2. - [Commits](https://github.com/kubernetes/cli-runtime/compare/v0.27.1...v0.27.2) --- updated-dependencies: - dependency-name: k8s.io/cli-runtime dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigstore/cosign-installer from 3.0.4 to 3.0.5 (#7229) Bumps [sigstore/cosign-installer](https://github.com/sigstore/cosign-installer) from 3.0.4 to 3.0.5. - [Release notes](https://github.com/sigstore/cosign-installer/releases) - [Commits](03d0fecf17...dd6b2e2b61
) --- updated-dependencies: - dependency-name: sigstore/cosign-installer dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump k8s.io/pod-security-admission from 0.27.1 to 0.27.2 (#7232) Bumps [k8s.io/pod-security-admission](https://github.com/kubernetes/pod-security-admission) from 0.27.1 to 0.27.2. - [Commits](https://github.com/kubernetes/pod-security-admission/compare/v0.27.1...v0.27.2) --- updated-dependencies: - dependency-name: k8s.io/pod-security-admission dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: match logic misbehave (#7218) * add rule name in ur for mutate existing Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix match logic Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fixes Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix the match logic to only apply to the new object, unless it's a delete request Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/stretchr/testify from 1.8.2 to 1.8.3 (#7240) Bumps [github.com/stretchr/testify](https://github.com/stretchr/testify) from 1.8.2 to 1.8.3. - [Release notes](https://github.com/stretchr/testify/releases) - [Commits](https://github.com/stretchr/testify/compare/v1.8.2...v1.8.3) --- updated-dependencies: - dependency-name: github.com/stretchr/testify dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/onsi/gomega from 1.27.6 to 1.27.7 (#7239) Bumps [github.com/onsi/gomega](https://github.com/onsi/gomega) from 1.27.6 to 1.27.7. - [Release notes](https://github.com/onsi/gomega/releases) - [Changelog](https://github.com/onsi/gomega/blob/master/CHANGELOG.md) - [Commits](https://github.com/onsi/gomega/compare/v1.27.6...v1.27.7) --- updated-dependencies: - dependency-name: github.com/onsi/gomega dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump k8s.io/kube-aggregator from 0.27.1 to 0.27.2 (#7241) Bumps [k8s.io/kube-aggregator](https://github.com/kubernetes/kube-aggregator) from 0.27.1 to 0.27.2. - [Commits](https://github.com/kubernetes/kube-aggregator/compare/v0.27.1...v0.27.2) --- updated-dependencies: - dependency-name: k8s.io/kube-aggregator dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump k8s.io/apiextensions-apiserver from 0.27.1 to 0.27.2 (#7242) Bumps [k8s.io/apiextensions-apiserver](https://github.com/kubernetes/apiextensions-apiserver) from 0.27.1 to 0.27.2. - [Release notes](https://github.com/kubernetes/apiextensions-apiserver/releases) - [Commits](https://github.com/kubernetes/apiextensions-apiserver/compare/v0.27.1...v0.27.2) --- updated-dependencies: - dependency-name: k8s.io/apiextensions-apiserver dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * passing rclientloader directly Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * lazy evaluate vars in conditions (#7238) * lazy evaluate vars in conditions Signed-off-by: Jim Bugwadia <jim@nirmata.com> * remove unnecessary conversion Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix test Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Update test/conformance/kuttl/validate/clusterpolicy/standard/variables/lazyload/conditions/03-manifests.yaml Signed-off-by: shuting <shutting06@gmail.com> * Update test/conformance/kuttl/validate/clusterpolicy/standard/variables/lazyload/README.md Signed-off-by: shuting <shutting06@gmail.com> * added error check in test Signed-off-by: Jim Bugwadia <jim@nirmata.com> --------- Signed-off-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: shuting <shutting06@gmail.com> Co-authored-by: shuting <shutting06@gmail.com> Co-authored-by: kyverno-bot <104836976+kyverno-bot@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * quote image in error (#7259) Signed-off-by: bakito <github@bakito.ch> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix: auto update webhooks not configuring fail endpoint (#7261) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * fix latest version check (#7263) Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump svenstaro/upload-release-action from 2.5.0 to 2.6.0 (#7270) Bumps [svenstaro/upload-release-action](https://github.com/svenstaro/upload-release-action) from 2.5.0 to 2.6.0. - [Release notes](https://github.com/svenstaro/upload-release-action/releases) - [Changelog](https://github.com/svenstaro/upload-release-action/blob/master/CHANGELOG.md) - [Commits](7319e4733e...58d5258088
) --- updated-dependencies: - dependency-name: svenstaro/upload-release-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump sigs.k8s.io/controller-runtime from 0.14.6 to 0.15.0 (#7272) Bumps [sigs.k8s.io/controller-runtime](https://github.com/kubernetes-sigs/controller-runtime) from 0.14.6 to 0.15.0. - [Release notes](https://github.com/kubernetes-sigs/controller-runtime/releases) - [Changelog](https://github.com/kubernetes-sigs/controller-runtime/blob/main/RELEASE.md) - [Commits](https://github.com/kubernetes-sigs/controller-runtime/compare/v0.14.6...v0.15.0) --- updated-dependencies: - dependency-name: sigs.k8s.io/controller-runtime dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat: add yaml util to check empty document (#7276) Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * chore(deps): bump github.com/go-git/go-git/v5 from 5.6.1 to 5.7.0 (#7274) Bumps [github.com/go-git/go-git/v5](https://github.com/go-git/go-git) from 5.6.1 to 5.7.0. - [Release notes](https://github.com/go-git/go-git/releases) - [Commits](https://github.com/go-git/go-git/compare/v5.6.1...v5.7.0) --- updated-dependencies: - dependency-name: github.com/go-git/go-git/v5 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * NIT Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * Azure to ACR Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * go mod fix Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * codegen Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * NIT Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * adding kuttl test Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * use pointer Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * cleanup Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * global client Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * cleanup Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * added kubeclient Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * added nil kubeclient check Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> * context Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * factory Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more fixes Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * secrets lister Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * flags Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * tests Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix cli Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix kuttl test Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix kuttl test Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix kuttl test Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * kuttl test Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * factories Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Vishal Choudhary <sendtovishalchoudhary@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Signed-off-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: Ved Ratan <vedratan8@gmail.com> Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: Chip Zoller <chipzoller@gmail.com> Signed-off-by: Mariam Fahmy <mariamfahmy66@gmail.com> Signed-off-by: Richard Parke <richardparke15@gmail.com> Signed-off-by: shuting <shutting06@gmail.com> Signed-off-by: bakito <github@bakito.ch> Co-authored-by: shuting <shuting@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Ved Ratan <82467006+VedRatan@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chip Zoller <chipzoller@gmail.com> Co-authored-by: Mariam Fahmy <55502281+MariamFahmy98@users.noreply.github.com> Co-authored-by: rparke <50015370+rparke@users.noreply.github.com> Co-authored-by: shuting <shutting06@gmail.com> Co-authored-by: kyverno-bot <104836976+kyverno-bot@users.noreply.github.com> Co-authored-by: Marc Brugger <github@bakito.ch>
998 lines
32 KiB
Go
998 lines
32 KiB
Go
package common
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/go-git/go-billy/v5"
|
|
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
|
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
|
sanitizederror "github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/sanitizedError"
|
|
"github.com/kyverno/kyverno/cmd/cli/kubectl-kyverno/utils/store"
|
|
"github.com/kyverno/kyverno/pkg/autogen"
|
|
"github.com/kyverno/kyverno/pkg/background/generate"
|
|
"github.com/kyverno/kyverno/pkg/clients/dclient"
|
|
"github.com/kyverno/kyverno/pkg/config"
|
|
"github.com/kyverno/kyverno/pkg/engine"
|
|
"github.com/kyverno/kyverno/pkg/engine/adapters"
|
|
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
|
"github.com/kyverno/kyverno/pkg/engine/jmespath"
|
|
"github.com/kyverno/kyverno/pkg/engine/variables/regex"
|
|
"github.com/kyverno/kyverno/pkg/logging"
|
|
datautils "github.com/kyverno/kyverno/pkg/utils/data"
|
|
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
|
yamlutils "github.com/kyverno/kyverno/pkg/utils/yaml"
|
|
yamlv2 "gopkg.in/yaml.v2"
|
|
"k8s.io/api/admissionregistration/v1alpha1"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
|
)
|
|
|
|
var log = logging.WithName("kubectl-kyverno")
|
|
|
|
type ResultCounts struct {
|
|
Pass int
|
|
Fail int
|
|
Warn int
|
|
Error int
|
|
Skip int
|
|
}
|
|
type Policy struct {
|
|
Name string `json:"name"`
|
|
Resources []Resource `json:"resources"`
|
|
Rules []Rule `json:"rules"`
|
|
}
|
|
|
|
type Rule struct {
|
|
Name string `json:"name"`
|
|
Values map[string]interface{} `json:"values"`
|
|
ForeachValues map[string][]interface{} `json:"foreachValues"`
|
|
}
|
|
|
|
type Values struct {
|
|
Policies []Policy `json:"policies"`
|
|
GlobalValues map[string]string `json:"globalValues"`
|
|
NamespaceSelectors []NamespaceSelector `json:"namespaceSelector"`
|
|
Subresources []Subresource `json:"subresources"`
|
|
}
|
|
|
|
type Resource struct {
|
|
Name string `json:"name"`
|
|
Values map[string]interface{} `json:"values"`
|
|
}
|
|
|
|
type Subresource struct {
|
|
APIResource metav1.APIResource `json:"subresource"`
|
|
ParentResource metav1.APIResource `json:"parentResource"`
|
|
}
|
|
|
|
type NamespaceSelector struct {
|
|
Name string `json:"name"`
|
|
Labels map[string]string `json:"labels"`
|
|
}
|
|
|
|
type ApplyPolicyConfig struct {
|
|
Policy kyvernov1.PolicyInterface
|
|
ValidatingAdmissionPolicy v1alpha1.ValidatingAdmissionPolicy
|
|
Resource *unstructured.Unstructured
|
|
MutateLogPath string
|
|
MutateLogPathIsDir bool
|
|
Variables map[string]interface{}
|
|
UserInfo kyvernov1beta1.RequestInfo
|
|
PolicyReport bool
|
|
NamespaceSelectorMap map[string]map[string]string
|
|
Stdin bool
|
|
Rc *ResultCounts
|
|
PrintPatchResource bool
|
|
RuleToCloneSourceResource map[string]string
|
|
Client dclient.Interface
|
|
AuditWarn bool
|
|
Subresources []Subresource
|
|
}
|
|
|
|
// HasVariables - check for variables in the policy
|
|
func HasVariables(policy kyvernov1.PolicyInterface) [][]string {
|
|
policyRaw, _ := json.Marshal(policy)
|
|
matches := regex.RegexVariables.FindAllStringSubmatch(string(policyRaw), -1)
|
|
return matches
|
|
}
|
|
|
|
// GetPolicies - Extracting the policies from multiple YAML
|
|
func GetPolicies(paths []string) (policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, errors []error) {
|
|
for _, path := range paths {
|
|
log.V(5).Info("reading policies", "path", path)
|
|
|
|
var (
|
|
fileDesc os.FileInfo
|
|
err error
|
|
)
|
|
|
|
isHTTPPath := IsHTTPRegex.MatchString(path)
|
|
|
|
// path clean and retrieving file info can be possible if it's not an HTTP URL
|
|
if !isHTTPPath {
|
|
path = filepath.Clean(path)
|
|
fileDesc, err = os.Stat(path)
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
}
|
|
|
|
// apply file from a directory is possible only if the path is not HTTP URL
|
|
if !isHTTPPath && fileDesc.IsDir() {
|
|
files, err := os.ReadDir(path)
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
|
|
listOfFiles := make([]string, 0)
|
|
for _, file := range files {
|
|
ext := filepath.Ext(file.Name())
|
|
if ext == "" || ext == ".yaml" || ext == ".yml" {
|
|
listOfFiles = append(listOfFiles, filepath.Join(path, file.Name()))
|
|
}
|
|
}
|
|
|
|
policiesFromDir, admissionPoliciesFromDir, errorsFromDir := GetPolicies(listOfFiles)
|
|
errors = append(errors, errorsFromDir...)
|
|
policies = append(policies, policiesFromDir...)
|
|
validatingAdmissionPolicies = append(validatingAdmissionPolicies, admissionPoliciesFromDir...)
|
|
} else {
|
|
var fileBytes []byte
|
|
if isHTTPPath {
|
|
// We accept here that a random URL might be called based on user provided input.
|
|
req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, path, nil)
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
|
|
fileBytes, err = io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
} else {
|
|
path = filepath.Clean(path)
|
|
// We accept the risk of including a user provided file here.
|
|
fileBytes, err = os.ReadFile(path) // #nosec G304
|
|
if err != nil {
|
|
err := fmt.Errorf("failed to process %v: %v", path, err.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
}
|
|
|
|
policiesFromFile, admissionPoliciesFromFile, errFromFile := yamlutils.GetPolicy(fileBytes)
|
|
if errFromFile != nil {
|
|
err := fmt.Errorf("failed to process %s: %v", path, errFromFile.Error())
|
|
errors = append(errors, err)
|
|
continue
|
|
}
|
|
|
|
policies = append(policies, policiesFromFile...)
|
|
validatingAdmissionPolicies = append(validatingAdmissionPolicies, admissionPoliciesFromFile...)
|
|
}
|
|
}
|
|
|
|
log.V(3).Info("read policies", "policies", len(policies), "errors", len(errors))
|
|
return policies, validatingAdmissionPolicies, errors
|
|
}
|
|
|
|
// IsInputFromPipe - check if input is passed using pipe
|
|
func IsInputFromPipe() bool {
|
|
fileInfo, _ := os.Stdin.Stat()
|
|
return fileInfo.Mode()&os.ModeCharDevice == 0
|
|
}
|
|
|
|
// RemoveDuplicateAndObjectVariables - remove duplicate variables
|
|
func RemoveDuplicateAndObjectVariables(matches [][]string) string {
|
|
var variableStr string
|
|
for _, m := range matches {
|
|
for _, v := range m {
|
|
foundVariable := strings.Contains(variableStr, v)
|
|
if !foundVariable {
|
|
if !strings.Contains(v, "request.object") && !strings.Contains(v, "element") && v == "elementIndex" {
|
|
variableStr = variableStr + " " + v
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return variableStr
|
|
}
|
|
|
|
func GetVariable(variablesString, valuesFile string, fs billy.Filesystem, isGit bool, policyResourcePath string) (map[string]string, map[string]string, map[string]map[string]Resource, map[string]map[string]string, []Subresource, error) {
|
|
valuesMapResource := make(map[string]map[string]Resource)
|
|
valuesMapRule := make(map[string]map[string]Rule)
|
|
namespaceSelectorMap := make(map[string]map[string]string)
|
|
variables := make(map[string]string)
|
|
subresources := make([]Subresource, 0)
|
|
globalValMap := make(map[string]string)
|
|
reqObjVars := ""
|
|
|
|
var yamlFile []byte
|
|
var err error
|
|
if variablesString != "" {
|
|
kvpairs := strings.Split(strings.Trim(variablesString, " "), ",")
|
|
for _, kvpair := range kvpairs {
|
|
kvs := strings.Split(strings.Trim(kvpair, " "), "=")
|
|
if strings.Contains(kvs[0], "request.object") {
|
|
if !strings.Contains(reqObjVars, kvs[0]) {
|
|
reqObjVars = reqObjVars + "," + kvs[0]
|
|
}
|
|
continue
|
|
}
|
|
|
|
variables[strings.Trim(kvs[0], " ")] = strings.Trim(kvs[1], " ")
|
|
}
|
|
}
|
|
|
|
if valuesFile != "" {
|
|
if isGit {
|
|
filep, err := fs.Open(filepath.Join(policyResourcePath, valuesFile))
|
|
if err != nil {
|
|
fmt.Printf("Unable to open variable file: %s. error: %s", valuesFile, err)
|
|
}
|
|
yamlFile, err = io.ReadAll(filep)
|
|
if err != nil {
|
|
fmt.Printf("Unable to read variable files: %s. error: %s \n", filep, err)
|
|
}
|
|
} else {
|
|
// We accept the risk of including a user provided file here.
|
|
yamlFile, err = os.ReadFile(filepath.Join(policyResourcePath, valuesFile)) // #nosec G304
|
|
if err != nil {
|
|
fmt.Printf("\n Unable to open variable file: %s. error: %s \n", valuesFile, err)
|
|
}
|
|
}
|
|
|
|
if err != nil {
|
|
return variables, globalValMap, valuesMapResource, namespaceSelectorMap, subresources, sanitizederror.NewWithError("unable to read yaml", err)
|
|
}
|
|
|
|
valuesBytes, err := yaml.ToJSON(yamlFile)
|
|
if err != nil {
|
|
return variables, globalValMap, valuesMapResource, namespaceSelectorMap, subresources, sanitizederror.NewWithError("failed to convert json", err)
|
|
}
|
|
|
|
values := &Values{}
|
|
if err := json.Unmarshal(valuesBytes, values); err != nil {
|
|
return variables, globalValMap, valuesMapResource, namespaceSelectorMap, subresources, sanitizederror.NewWithError("failed to decode yaml", err)
|
|
}
|
|
|
|
if values.GlobalValues == nil {
|
|
values.GlobalValues = make(map[string]string)
|
|
values.GlobalValues["request.operation"] = "CREATE"
|
|
log.V(3).Info("Defaulting request.operation to CREATE")
|
|
} else {
|
|
if val, ok := values.GlobalValues["request.operation"]; ok {
|
|
if val == "" {
|
|
values.GlobalValues["request.operation"] = "CREATE"
|
|
log.V(3).Info("Globally request.operation value provided by the user is empty, defaulting it to CREATE", "request.opearation: ", values.GlobalValues)
|
|
}
|
|
}
|
|
}
|
|
|
|
globalValMap = values.GlobalValues
|
|
|
|
for _, p := range values.Policies {
|
|
resourceMap := make(map[string]Resource)
|
|
for _, r := range p.Resources {
|
|
if val, ok := r.Values["request.operation"]; ok {
|
|
if val == "" {
|
|
r.Values["request.operation"] = "CREATE"
|
|
log.V(3).Info("No request.operation found, defaulting it to CREATE", "policy", p.Name)
|
|
}
|
|
}
|
|
for variableInFile := range r.Values {
|
|
if strings.Contains(variableInFile, "request.object") {
|
|
if !strings.Contains(reqObjVars, variableInFile) {
|
|
reqObjVars = reqObjVars + "," + variableInFile
|
|
}
|
|
delete(r.Values, variableInFile)
|
|
continue
|
|
}
|
|
}
|
|
resourceMap[r.Name] = r
|
|
}
|
|
valuesMapResource[p.Name] = resourceMap
|
|
|
|
if p.Rules != nil {
|
|
ruleMap := make(map[string]Rule)
|
|
for _, r := range p.Rules {
|
|
ruleMap[r.Name] = r
|
|
}
|
|
valuesMapRule[p.Name] = ruleMap
|
|
}
|
|
}
|
|
|
|
for _, n := range values.NamespaceSelectors {
|
|
namespaceSelectorMap[n.Name] = n.Labels
|
|
}
|
|
|
|
subresources = values.Subresources
|
|
}
|
|
|
|
if reqObjVars != "" {
|
|
fmt.Printf("\nNOTICE: request.object.* variables are automatically parsed from the supplied resource. Ignoring value of variables `%v`.\n", reqObjVars)
|
|
}
|
|
|
|
if globalValMap != nil {
|
|
if _, ok := globalValMap["request.operation"]; !ok {
|
|
globalValMap["request.operation"] = "CREATE"
|
|
log.V(3).Info("Defaulting request.operation to CREATE")
|
|
}
|
|
}
|
|
|
|
storePolicies := make([]store.Policy, 0)
|
|
for policyName, ruleMap := range valuesMapRule {
|
|
storeRules := make([]store.Rule, 0)
|
|
for _, rule := range ruleMap {
|
|
storeRules = append(storeRules, store.Rule{
|
|
Name: rule.Name,
|
|
Values: rule.Values,
|
|
ForEachValues: rule.ForeachValues,
|
|
})
|
|
}
|
|
storePolicies = append(storePolicies, store.Policy{
|
|
Name: policyName,
|
|
Rules: storeRules,
|
|
})
|
|
}
|
|
|
|
store.SetPolicies(storePolicies...)
|
|
|
|
return variables, globalValMap, valuesMapResource, namespaceSelectorMap, subresources, nil
|
|
}
|
|
|
|
func ProcessValidateEngineResponse(policy kyvernov1.PolicyInterface, validateResponse engineapi.EngineResponse, resPath string, rc *ResultCounts, policyReport bool, auditWarn bool) {
|
|
printCount := 0
|
|
for _, policyRule := range autogen.ComputeRules(policy) {
|
|
ruleFoundInEngineResponse := false
|
|
if !policyRule.HasValidate() && !policyRule.HasVerifyImageChecks() && !policyRule.HasVerifyImages() {
|
|
continue
|
|
}
|
|
|
|
for i, valResponseRule := range validateResponse.PolicyResponse.Rules {
|
|
if policyRule.Name == valResponseRule.Name() {
|
|
ruleFoundInEngineResponse = true
|
|
switch valResponseRule.Status() {
|
|
case engineapi.RuleStatusPass:
|
|
rc.Pass++
|
|
case engineapi.RuleStatusFail:
|
|
auditWarning := false
|
|
ann := policy.GetAnnotations()
|
|
if scored, ok := ann[kyvernov1.AnnotationPolicyScored]; ok && scored == "false" {
|
|
rc.Warn++
|
|
break
|
|
} else if auditWarn && validateResponse.GetValidationFailureAction().Audit() {
|
|
rc.Warn++
|
|
auditWarning = true
|
|
} else {
|
|
rc.Fail++
|
|
}
|
|
if !policyReport {
|
|
if printCount < 1 {
|
|
if auditWarning {
|
|
fmt.Printf("\npolicy %s -> resource %s failed as audit warning: \n", policy.GetName(), resPath)
|
|
} else {
|
|
fmt.Printf("\npolicy %s -> resource %s failed: \n", policy.GetName(), resPath)
|
|
}
|
|
printCount++
|
|
}
|
|
|
|
fmt.Printf("%d. %s: %s \n", i+1, valResponseRule.Name(), valResponseRule.Message())
|
|
}
|
|
case engineapi.RuleStatusError:
|
|
rc.Error++
|
|
case engineapi.RuleStatusWarn:
|
|
rc.Warn++
|
|
case engineapi.RuleStatusSkip:
|
|
rc.Skip++
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
if !ruleFoundInEngineResponse {
|
|
rc.Skip++
|
|
}
|
|
}
|
|
}
|
|
|
|
// PrintMutatedOutput - function to print output in provided file or directory
|
|
func PrintMutatedOutput(mutateLogPath string, mutateLogPathIsDir bool, yaml string, fileName string) error {
|
|
var f *os.File
|
|
var err error
|
|
yaml = yaml + ("\n---\n\n")
|
|
|
|
mutateLogPath = filepath.Clean(mutateLogPath)
|
|
if !mutateLogPathIsDir {
|
|
// truncation for the case when mutateLogPath is a file (not a directory) is handled under pkg/kyverno/apply/test_command.go
|
|
f, err = os.OpenFile(mutateLogPath, os.O_APPEND|os.O_WRONLY, 0o600) // #nosec G304
|
|
} else {
|
|
f, err = os.OpenFile(mutateLogPath+"/"+fileName+".yaml", os.O_CREATE|os.O_WRONLY, 0o600) // #nosec G304
|
|
}
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := f.Write([]byte(yaml)); err != nil {
|
|
closeErr := f.Close()
|
|
if closeErr != nil {
|
|
log.Error(closeErr, "failed to close file")
|
|
}
|
|
return err
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetPoliciesFromPaths - get policies according to the resource path
|
|
func GetPoliciesFromPaths(fs billy.Filesystem, dirPath []string, isGit bool, policyResourcePath string) (policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, err error) {
|
|
if isGit {
|
|
for _, pp := range dirPath {
|
|
filep, err := fs.Open(filepath.Join(policyResourcePath, pp))
|
|
if err != nil {
|
|
fmt.Printf("Error: file not available with path %s: %v", filep.Name(), err.Error())
|
|
continue
|
|
}
|
|
bytes, err := io.ReadAll(filep)
|
|
if err != nil {
|
|
fmt.Printf("Error: failed to read file %s: %v", filep.Name(), err.Error())
|
|
continue
|
|
}
|
|
policyBytes, err := yaml.ToJSON(bytes)
|
|
if err != nil {
|
|
fmt.Printf("failed to convert to JSON: %v", err)
|
|
continue
|
|
}
|
|
policiesFromFile, admissionPoliciesFromFile, errFromFile := yamlutils.GetPolicy(policyBytes)
|
|
if errFromFile != nil {
|
|
fmt.Printf("failed to process : %v", errFromFile.Error())
|
|
continue
|
|
}
|
|
policies = append(policies, policiesFromFile...)
|
|
validatingAdmissionPolicies = append(validatingAdmissionPolicies, admissionPoliciesFromFile...)
|
|
}
|
|
} else {
|
|
if len(dirPath) > 0 && dirPath[0] == "-" {
|
|
if IsInputFromPipe() {
|
|
policyStr := ""
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
for scanner.Scan() {
|
|
policyStr = policyStr + scanner.Text() + "\n"
|
|
}
|
|
yamlBytes := []byte(policyStr)
|
|
policies, validatingAdmissionPolicies, err = yamlutils.GetPolicy(yamlBytes)
|
|
if err != nil {
|
|
return nil, nil, sanitizederror.NewWithError("failed to extract the resources", err)
|
|
}
|
|
}
|
|
} else {
|
|
var errors []error
|
|
policies, validatingAdmissionPolicies, errors = GetPolicies(dirPath)
|
|
if len(policies) == 0 && len(validatingAdmissionPolicies) == 0 {
|
|
if len(errors) > 0 {
|
|
return nil, nil, sanitizederror.NewWithErrors("failed to read file", errors)
|
|
}
|
|
return nil, nil, sanitizederror.New(fmt.Sprintf("no file found in paths %v", dirPath))
|
|
}
|
|
if len(errors) > 0 && log.V(1).Enabled() {
|
|
fmt.Printf("ignoring errors: \n")
|
|
for _, e := range errors {
|
|
fmt.Printf(" %v \n", e.Error())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
// GetResourceAccordingToResourcePath - get resources according to the resource path
|
|
func GetResourceAccordingToResourcePath(fs billy.Filesystem, resourcePaths []string,
|
|
cluster bool, policies []kyvernov1.PolicyInterface, validatingAdmissionPolicies []v1alpha1.ValidatingAdmissionPolicy, dClient dclient.Interface, namespace string, policyReport bool, isGit bool, policyResourcePath string,
|
|
) (resources []*unstructured.Unstructured, err error) {
|
|
if isGit {
|
|
resources, err = GetResourcesWithTest(fs, policies, resourcePaths, isGit, policyResourcePath)
|
|
if err != nil {
|
|
return nil, sanitizederror.NewWithError("failed to extract the resources", err)
|
|
}
|
|
} else {
|
|
if len(resourcePaths) > 0 && resourcePaths[0] == "-" {
|
|
if IsInputFromPipe() {
|
|
resourceStr := ""
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
for scanner.Scan() {
|
|
resourceStr = resourceStr + scanner.Text() + "\n"
|
|
}
|
|
|
|
yamlBytes := []byte(resourceStr)
|
|
resources, err = GetResource(yamlBytes)
|
|
if err != nil {
|
|
return nil, sanitizederror.NewWithError("failed to extract the resources", err)
|
|
}
|
|
}
|
|
} else {
|
|
if len(resourcePaths) > 0 {
|
|
fileDesc, err := os.Stat(resourcePaths[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if fileDesc.IsDir() {
|
|
files, err := os.ReadDir(resourcePaths[0])
|
|
if err != nil {
|
|
return nil, sanitizederror.NewWithError(fmt.Sprintf("failed to parse %v", resourcePaths[0]), err)
|
|
}
|
|
listOfFiles := make([]string, 0)
|
|
for _, file := range files {
|
|
ext := filepath.Ext(file.Name())
|
|
if ext == ".yaml" || ext == ".yml" {
|
|
listOfFiles = append(listOfFiles, filepath.Join(resourcePaths[0], file.Name()))
|
|
}
|
|
}
|
|
resourcePaths = listOfFiles
|
|
}
|
|
}
|
|
|
|
resources, err = GetResources(policies, validatingAdmissionPolicies, resourcePaths, dClient, cluster, namespace, policyReport)
|
|
if err != nil {
|
|
return resources, err
|
|
}
|
|
}
|
|
}
|
|
return resources, err
|
|
}
|
|
|
|
func updateResultCounts(policy kyvernov1.PolicyInterface, engineResponse *engineapi.EngineResponse, resPath string, rc *ResultCounts, auditWarn bool) {
|
|
printCount := 0
|
|
for _, policyRule := range autogen.ComputeRules(policy) {
|
|
ruleFoundInEngineResponse := false
|
|
for i, ruleResponse := range engineResponse.PolicyResponse.Rules {
|
|
if policyRule.Name == ruleResponse.Name() {
|
|
ruleFoundInEngineResponse = true
|
|
|
|
if ruleResponse.Status() == engineapi.RuleStatusPass {
|
|
rc.Pass++
|
|
} else {
|
|
if printCount < 1 {
|
|
fmt.Println("\ninvalid resource", "policy", policy.GetName(), "resource", resPath)
|
|
printCount++
|
|
}
|
|
fmt.Printf("%d. %s - %s\n", i+1, ruleResponse.Name(), ruleResponse.Message())
|
|
|
|
if auditWarn && engineResponse.GetValidationFailureAction().Audit() {
|
|
rc.Warn++
|
|
} else {
|
|
rc.Fail++
|
|
}
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
|
|
if !ruleFoundInEngineResponse {
|
|
rc.Skip++
|
|
}
|
|
}
|
|
}
|
|
|
|
func SetInStoreContext(mutatedPolicies []kyvernov1.PolicyInterface, variables map[string]string) map[string]string {
|
|
storePolicies := make([]store.Policy, 0)
|
|
for _, policy := range mutatedPolicies {
|
|
storeRules := make([]store.Rule, 0)
|
|
for _, rule := range autogen.ComputeRules(policy) {
|
|
contextVal := make(map[string]interface{})
|
|
if len(rule.Context) != 0 {
|
|
for _, contextVar := range rule.Context {
|
|
for k, v := range variables {
|
|
if strings.HasPrefix(k, contextVar.Name) {
|
|
contextVal[k] = v
|
|
delete(variables, k)
|
|
}
|
|
}
|
|
}
|
|
storeRules = append(storeRules, store.Rule{
|
|
Name: rule.Name,
|
|
Values: contextVal,
|
|
})
|
|
}
|
|
}
|
|
storePolicies = append(storePolicies, store.Policy{
|
|
Name: policy.GetName(),
|
|
Rules: storeRules,
|
|
})
|
|
}
|
|
|
|
store.SetPolicies(storePolicies...)
|
|
|
|
return variables
|
|
}
|
|
|
|
func processMutateEngineResponse(c ApplyPolicyConfig, mutateResponse *engineapi.EngineResponse, resPath string) error {
|
|
var policyHasMutate bool
|
|
for _, rule := range autogen.ComputeRules(c.Policy) {
|
|
if rule.HasMutate() {
|
|
policyHasMutate = true
|
|
}
|
|
}
|
|
if !policyHasMutate {
|
|
return nil
|
|
}
|
|
|
|
printCount := 0
|
|
printMutatedRes := false
|
|
for _, policyRule := range autogen.ComputeRules(c.Policy) {
|
|
ruleFoundInEngineResponse := false
|
|
for i, mutateResponseRule := range mutateResponse.PolicyResponse.Rules {
|
|
if policyRule.Name == mutateResponseRule.Name() {
|
|
ruleFoundInEngineResponse = true
|
|
if mutateResponseRule.Status() == engineapi.RuleStatusPass {
|
|
c.Rc.Pass++
|
|
printMutatedRes = true
|
|
} else if mutateResponseRule.Status() == engineapi.RuleStatusSkip {
|
|
fmt.Printf("\nskipped mutate policy %s -> resource %s", c.Policy.GetName(), resPath)
|
|
c.Rc.Skip++
|
|
} else if mutateResponseRule.Status() == engineapi.RuleStatusError {
|
|
fmt.Printf("\nerror while applying mutate policy %s -> resource %s\nerror: %s", c.Policy.GetName(), resPath, mutateResponseRule.Message())
|
|
c.Rc.Error++
|
|
} else {
|
|
if printCount < 1 {
|
|
fmt.Printf("\nfailed to apply mutate policy %s -> resource %s", c.Policy.GetName(), resPath)
|
|
printCount++
|
|
}
|
|
fmt.Printf("%d. %s - %s \n", i+1, mutateResponseRule.Name(), mutateResponseRule.Message())
|
|
c.Rc.Fail++
|
|
}
|
|
continue
|
|
}
|
|
}
|
|
if !ruleFoundInEngineResponse {
|
|
c.Rc.Skip++
|
|
}
|
|
}
|
|
|
|
if printMutatedRes && c.PrintPatchResource {
|
|
yamlEncodedResource, err := yamlv2.Marshal(mutateResponse.PatchedResource.Object)
|
|
if err != nil {
|
|
return sanitizederror.NewWithError("failed to marshal", err)
|
|
}
|
|
|
|
if c.MutateLogPath == "" {
|
|
mutatedResource := string(yamlEncodedResource) + string("\n---")
|
|
if len(strings.TrimSpace(mutatedResource)) > 0 {
|
|
if !c.Stdin {
|
|
fmt.Printf("\nmutate policy %s applied to %s:", c.Policy.GetName(), resPath)
|
|
}
|
|
fmt.Printf("\n" + mutatedResource + "\n")
|
|
}
|
|
} else {
|
|
err := PrintMutatedOutput(c.MutateLogPath, c.MutateLogPathIsDir, string(yamlEncodedResource), c.Resource.GetName()+"-mutated")
|
|
if err != nil {
|
|
return sanitizederror.NewWithError("failed to print mutated result", err)
|
|
}
|
|
fmt.Printf("\n\nMutation:\nMutation has been applied successfully. Check the files.")
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func PrintMutatedPolicy(mutatedPolicies []kyvernov1.PolicyInterface) error {
|
|
for _, policy := range mutatedPolicies {
|
|
p, err := json.Marshal(policy)
|
|
if err != nil {
|
|
return sanitizederror.NewWithError("failed to marsal mutated policy", err)
|
|
}
|
|
log.V(5).Info("mutated Policy:", string(p))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func CheckVariableForPolicy(valuesMap map[string]map[string]Resource, globalValMap map[string]string, policyName string, resourceName string, resourceKind string, variables map[string]string, kindOnwhichPolicyIsApplied map[string]struct{}, variable string) (map[string]interface{}, error) {
|
|
// get values from file for this policy resource combination
|
|
thisPolicyResourceValues := make(map[string]interface{})
|
|
if len(valuesMap[policyName]) != 0 && !datautils.DeepEqual(valuesMap[policyName][resourceName], Resource{}) {
|
|
thisPolicyResourceValues = valuesMap[policyName][resourceName].Values
|
|
}
|
|
|
|
for k, v := range variables {
|
|
thisPolicyResourceValues[k] = v
|
|
}
|
|
|
|
if thisPolicyResourceValues == nil && len(globalValMap) > 0 {
|
|
thisPolicyResourceValues = make(map[string]interface{})
|
|
}
|
|
|
|
for k, v := range globalValMap {
|
|
if _, ok := thisPolicyResourceValues[k]; !ok {
|
|
thisPolicyResourceValues[k] = v
|
|
}
|
|
}
|
|
|
|
// skipping the variable check for non matching kind
|
|
if _, ok := kindOnwhichPolicyIsApplied[resourceKind]; ok {
|
|
if len(variable) > 0 && len(thisPolicyResourceValues) == 0 && store.HasPolicies() {
|
|
return thisPolicyResourceValues, sanitizederror.NewWithError(fmt.Sprintf("policy `%s` have variables. pass the values for the variables for resource `%s` using set/values_file flag", policyName, resourceName), nil)
|
|
}
|
|
}
|
|
return thisPolicyResourceValues, nil
|
|
}
|
|
|
|
func GetKindsFromPolicy(policy kyvernov1.PolicyInterface, subresources []Subresource, dClient dclient.Interface) map[string]struct{} {
|
|
kindOnwhichPolicyIsApplied := make(map[string]struct{})
|
|
for _, rule := range autogen.ComputeRules(policy) {
|
|
for _, kind := range rule.MatchResources.ResourceDescription.Kinds {
|
|
k, err := getKind(kind, subresources, dClient)
|
|
if err != nil {
|
|
fmt.Printf("Error: %s", err.Error())
|
|
continue
|
|
}
|
|
kindOnwhichPolicyIsApplied[k] = struct{}{}
|
|
}
|
|
for _, kind := range rule.ExcludeResources.ResourceDescription.Kinds {
|
|
k, err := getKind(kind, subresources, dClient)
|
|
if err != nil {
|
|
fmt.Printf("Error: %s", err.Error())
|
|
continue
|
|
}
|
|
kindOnwhichPolicyIsApplied[k] = struct{}{}
|
|
}
|
|
}
|
|
return kindOnwhichPolicyIsApplied
|
|
}
|
|
|
|
func getKind(kind string, subresources []Subresource, dClient dclient.Interface) (string, error) {
|
|
group, version, kind, subresource := kubeutils.ParseKindSelector(kind)
|
|
if subresource == "" {
|
|
return kind, nil
|
|
}
|
|
if dClient == nil {
|
|
gv := schema.GroupVersion{Group: group, Version: version}
|
|
return getSubresourceKind(gv.String(), kind, subresource, subresources)
|
|
}
|
|
gvrss, err := dClient.Discovery().FindResources(group, version, kind, subresource)
|
|
if err != nil {
|
|
return kind, err
|
|
}
|
|
if len(gvrss) != 1 {
|
|
return kind, fmt.Errorf("no unique match for kind %s", kind)
|
|
}
|
|
for _, api := range gvrss {
|
|
return api.Kind, nil
|
|
}
|
|
return kind, nil
|
|
}
|
|
|
|
func getSubresourceKind(groupVersion, parentKind, subresourceName string, subresources []Subresource) (string, error) {
|
|
for _, subresource := range subresources {
|
|
parentResourceGroupVersion := metav1.GroupVersion{
|
|
Group: subresource.ParentResource.Group,
|
|
Version: subresource.ParentResource.Version,
|
|
}.String()
|
|
if groupVersion == "" || kubeutils.GroupVersionMatches(groupVersion, parentResourceGroupVersion) {
|
|
if parentKind == subresource.ParentResource.Kind {
|
|
if strings.ToLower(subresourceName) == strings.Split(subresource.APIResource.Name, "/")[1] {
|
|
return subresource.APIResource.Kind, nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return "", sanitizederror.NewWithError(fmt.Sprintf("subresource %s not found for parent resource %s", subresourceName, parentKind), nil)
|
|
}
|
|
|
|
// GetResourceFromPath - get patchedResource and generatedResource from given path
|
|
func GetResourceFromPath(fs billy.Filesystem, path string, isGit bool, policyResourcePath string, resourceType string) (unstructured.Unstructured, error) {
|
|
var resourceBytes []byte
|
|
var resource unstructured.Unstructured
|
|
var err error
|
|
if isGit {
|
|
if len(path) > 0 {
|
|
filep, fileErr := fs.Open(filepath.Join(policyResourcePath, path))
|
|
if fileErr != nil {
|
|
fmt.Printf("Unable to open %s file: %s. \nerror: %s", resourceType, path, err)
|
|
}
|
|
resourceBytes, err = io.ReadAll(filep)
|
|
}
|
|
} else {
|
|
resourceBytes, err = getFileBytes(path)
|
|
}
|
|
|
|
if err != nil {
|
|
fmt.Printf("\n----------------------------------------------------------------------\nfailed to load %s: %s. \nerror: %s\n----------------------------------------------------------------------\n", resourceType, path, err)
|
|
return resource, err
|
|
}
|
|
|
|
resource, err = GetPatchedAndGeneratedResource(resourceBytes)
|
|
if err != nil {
|
|
return resource, err
|
|
}
|
|
|
|
return resource, nil
|
|
}
|
|
|
|
// initializeMockController initializes a basic Generate Controller with a fake dynamic client.
|
|
func initializeMockController(objects []runtime.Object) (*generate.GenerateController, error) {
|
|
client, err := dclient.NewFakeClient(runtime.NewScheme(), nil, objects...)
|
|
if err != nil {
|
|
fmt.Printf("Failed to mock dynamic client")
|
|
return nil, err
|
|
}
|
|
client.SetDiscovery(dclient.NewFakeDiscoveryClient(nil))
|
|
cfg := config.NewDefaultConfiguration(false)
|
|
c := generate.NewGenerateControllerWithOnlyClient(client, engine.NewEngine(
|
|
cfg,
|
|
config.NewDefaultMetricsConfiguration(),
|
|
jmespath.New(cfg),
|
|
adapters.Client(client),
|
|
nil,
|
|
store.ContextLoaderFactory(nil),
|
|
nil,
|
|
"",
|
|
))
|
|
return c, nil
|
|
}
|
|
|
|
// handleGeneratePolicy returns a new RuleResponse with the Kyverno generated resource configuration by applying the generate rule.
|
|
func handleGeneratePolicy(generateResponse *engineapi.EngineResponse, policyContext engine.PolicyContext, ruleToCloneSourceResource map[string]string) ([]engineapi.RuleResponse, error) {
|
|
resource := policyContext.NewResource()
|
|
objects := []runtime.Object{&resource}
|
|
resources := []*unstructured.Unstructured{}
|
|
for _, rule := range generateResponse.PolicyResponse.Rules {
|
|
if path, ok := ruleToCloneSourceResource[rule.Name()]; ok {
|
|
resourceBytes, err := getFileBytes(path)
|
|
if err != nil {
|
|
fmt.Printf("failed to get resource bytes\n")
|
|
} else {
|
|
resources, err = GetResource(resourceBytes)
|
|
if err != nil {
|
|
fmt.Printf("failed to convert resource bytes to unstructured format\n")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for _, res := range resources {
|
|
objects = append(objects, res)
|
|
}
|
|
|
|
c, err := initializeMockController(objects)
|
|
if err != nil {
|
|
fmt.Println("error at controller")
|
|
return nil, err
|
|
}
|
|
|
|
gr := kyvernov1beta1.UpdateRequest{
|
|
Spec: kyvernov1beta1.UpdateRequestSpec{
|
|
Type: kyvernov1beta1.Generate,
|
|
Policy: generateResponse.Policy().GetName(),
|
|
Resource: kyvernov1.ResourceSpec{
|
|
Kind: generateResponse.Resource.GetKind(),
|
|
Namespace: generateResponse.Resource.GetNamespace(),
|
|
Name: generateResponse.Resource.GetName(),
|
|
APIVersion: generateResponse.Resource.GetAPIVersion(),
|
|
},
|
|
},
|
|
}
|
|
|
|
var newRuleResponse []engineapi.RuleResponse
|
|
|
|
for _, rule := range generateResponse.PolicyResponse.Rules {
|
|
genResource, err := c.ApplyGeneratePolicy(log.V(2), &policyContext, gr, []string{rule.Name()})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if genResource != nil {
|
|
unstrGenResource, err := c.GetUnstrResource(genResource[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
newRuleResponse = append(newRuleResponse, *rule.WithGeneratedResource(*unstrGenResource))
|
|
}
|
|
}
|
|
|
|
return newRuleResponse, nil
|
|
}
|
|
|
|
// GetUserInfoFromPath - get the request info as user info from a given path
|
|
func GetUserInfoFromPath(fs billy.Filesystem, path string, isGit bool, policyResourcePath string) (kyvernov1beta1.RequestInfo, error) {
|
|
userInfo := &kyvernov1beta1.RequestInfo{}
|
|
if isGit {
|
|
filep, err := fs.Open(filepath.Join(policyResourcePath, path))
|
|
if err != nil {
|
|
fmt.Printf("Unable to open userInfo file: %s. \nerror: %s", path, err)
|
|
}
|
|
bytes, err := io.ReadAll(filep)
|
|
if err != nil {
|
|
fmt.Printf("Error: failed to read file %s: %v", filep.Name(), err.Error())
|
|
}
|
|
userInfoBytes, err := yaml.ToJSON(bytes)
|
|
if err != nil {
|
|
fmt.Printf("failed to convert to JSON: %v", err)
|
|
}
|
|
|
|
if err := json.Unmarshal(userInfoBytes, userInfo); err != nil {
|
|
fmt.Printf("failed to decode yaml: %v", err)
|
|
}
|
|
} else {
|
|
var errors []error
|
|
pathname := filepath.Clean(filepath.Join(policyResourcePath, path))
|
|
bytes, err := os.ReadFile(pathname)
|
|
if err != nil {
|
|
errors = append(errors, sanitizederror.NewWithError("unable to read yaml", err))
|
|
}
|
|
userInfoBytes, err := yaml.ToJSON(bytes)
|
|
if err != nil {
|
|
errors = append(errors, sanitizederror.NewWithError("failed to convert json", err))
|
|
}
|
|
if err := json.Unmarshal(userInfoBytes, userInfo); err != nil {
|
|
errors = append(errors, sanitizederror.NewWithError("failed to decode yaml", err))
|
|
}
|
|
if len(errors) > 0 && log.V(1).Enabled() {
|
|
fmt.Printf("ignoring errors: \n")
|
|
for _, e := range errors {
|
|
fmt.Printf(" %v \n", e.Error())
|
|
}
|
|
}
|
|
}
|
|
return *userInfo, nil
|
|
}
|
|
|
|
func IsGitSourcePath(policyPaths []string) bool {
|
|
return strings.Contains(policyPaths[0], "https://")
|
|
}
|
|
|
|
func GetGitBranchOrPolicyPaths(gitBranch, repoURL string, policyPaths []string) (string, string) {
|
|
var gitPathToYamls string
|
|
if gitBranch == "" {
|
|
gitPathToYamls = "/"
|
|
if string(policyPaths[0][len(policyPaths[0])-1]) == "/" {
|
|
gitBranch = strings.ReplaceAll(policyPaths[0], repoURL+"/", "")
|
|
} else {
|
|
gitBranch = strings.ReplaceAll(policyPaths[0], repoURL, "")
|
|
}
|
|
if gitBranch == "" {
|
|
gitBranch = "main"
|
|
} else if string(gitBranch[0]) == "/" {
|
|
gitBranch = gitBranch[1:]
|
|
}
|
|
return gitBranch, gitPathToYamls
|
|
}
|
|
if string(policyPaths[0][len(policyPaths[0])-1]) == "/" {
|
|
gitPathToYamls = strings.ReplaceAll(policyPaths[0], repoURL+"/", "/")
|
|
} else {
|
|
gitPathToYamls = strings.ReplaceAll(policyPaths[0], repoURL, "/")
|
|
}
|
|
return gitBranch, gitPathToYamls
|
|
}
|