1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00

Remove dependency on github.com/pkg/errors (#6165)

Signed-off-by: Fish-pro <zechun.chen@daocloud.io>
This commit is contained in:
Fish-pro 2023-02-01 14:38:04 +08:00 committed by GitHub
parent 7540daa906
commit fdfdcc058f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 145 additions and 160 deletions

View file

@ -2,8 +2,8 @@ package v1
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/util/validation/field"
)
@ -332,7 +332,7 @@ func (a *Attestor) Validate(path *field.Path) (errs field.ErrorList) {
func AttestorSetUnmarshal(o *apiextv1.JSON) (*AttestorSet, error) {
var as AttestorSet
if err := json.Unmarshal(o.Raw, &as); err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal attestor set %s", string(o.Raw))
return nil, fmt.Errorf("failed to unmarshal attestor set %s: %w", string(o.Raw), err)
}
return &as, nil

View file

@ -1,13 +1,14 @@
package cleanup
import (
"fmt"
"github.com/go-logr/logr"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov2beta1 "github.com/kyverno/kyverno/api/kyverno/v2beta1"
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/engine/variables/operator"
"github.com/pkg/errors"
)
func checkAnyAllConditions(logger logr.Logger, ctx enginecontext.Interface, condition kyvernov2beta1.AnyAllConditions) (bool, error) {
@ -31,15 +32,15 @@ func checkAnyAllConditions(logger logr.Logger, ctx enginecontext.Interface, cond
func checkCondition(logger logr.Logger, ctx enginecontext.Interface, condition kyvernov2beta1.Condition) (bool, error) {
key, err := variables.SubstituteAllInPreconditions(logger, ctx, condition.GetKey())
if err != nil {
return false, errors.Wrapf(err, "failed to substitute variables in condition key")
return false, fmt.Errorf("failed to substitute variables in condition key: %w", err)
}
value, err := variables.SubstituteAllInPreconditions(logger, ctx, condition.GetValue())
if err != nil {
return false, errors.Wrapf(err, "failed to substitute variables in condition value")
return false, fmt.Errorf("failed to substitute variables in condition value: %w", err)
}
handler := operator.CreateOperatorHandler(logger, ctx, kyvernov1.ConditionOperator(condition.Operator))
if handler == nil {
return false, errors.Wrapf(err, "failed to create handler for condition operator")
return false, fmt.Errorf("failed to create handler for condition operator: %w", err)
}
return handler.Evaluate(key, value), nil
}

2
go.mod
View file

@ -33,7 +33,6 @@ require (
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.26.0
github.com/orcaman/concurrent-map/v2 v2.0.1
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.14.0
github.com/robfig/cron v1.2.0
github.com/sigstore/cosign v1.13.1
@ -259,6 +258,7 @@ require (
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pierrec/lz4 v2.6.1+incompatible // indirect
github.com/pjbgf/sha1cd v0.2.3 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.39.0 // indirect

View file

@ -13,7 +13,6 @@ import (
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/engine/context"
admissionutils "github.com/kyverno/kyverno/pkg/utils/admission"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
@ -31,18 +30,18 @@ func NewBackgroundContext(dclient dclient.Interface, ur *kyvernov1beta1.UpdateRe
if ur.Spec.Context.AdmissionRequestInfo.AdmissionRequest != nil {
if err := ctx.AddRequest(ur.Spec.Context.AdmissionRequestInfo.AdmissionRequest); err != nil {
return nil, false, errors.Wrap(err, "failed to load request in context")
return nil, false, fmt.Errorf("failed to load request in context: %w", err)
}
new, old, err = admissionutils.ExtractResources(nil, ur.Spec.Context.AdmissionRequestInfo.AdmissionRequest)
if err != nil {
return nil, false, errors.Wrap(err, "failed to load request in context")
return nil, false, fmt.Errorf("failed to load request in context: %w", err)
}
if !reflect.DeepEqual(new, unstructured.Unstructured{}) {
if !check(&new, trigger) {
err := fmt.Errorf("resources don't match")
return nil, false, errors.Wrapf(err, "resource %v", ur.Spec.Resource)
return nil, false, fmt.Errorf("resource %v: %w", ur.Spec.Resource, err)
}
}
}
@ -52,27 +51,27 @@ func NewBackgroundContext(dclient dclient.Interface, ur *kyvernov1beta1.UpdateRe
}
if trigger == nil {
return nil, false, errors.New("trigger resource does not exist")
return nil, false, fmt.Errorf("trigger resource does not exist")
}
err = ctx.AddResource(trigger.Object)
if err != nil {
return nil, false, errors.Wrap(err, "failed to load resource in context")
return nil, false, fmt.Errorf("failed to load resource in contex: %w", err)
}
err = ctx.AddOldResource(old.Object)
if err != nil {
return nil, false, errors.Wrap(err, "failed to load resource in context")
return nil, false, fmt.Errorf("failed to load resource in context: %w", err)
}
err = ctx.AddUserInfo(ur.Spec.Context.UserRequestInfo)
if err != nil {
return nil, false, errors.Wrapf(err, "failed to load SA in context")
return nil, false, fmt.Errorf("failed to load SA in context: %w", err)
}
err = ctx.AddServiceAccount(ur.Spec.Context.UserRequestInfo.AdmissionUserInfo.Username)
if err != nil {
return nil, false, errors.Wrapf(err, "failed to load UserInfo in context")
return nil, false, fmt.Errorf("failed to load UserInfo in context: %w", err)
}
if err := ctx.AddImageInfos(trigger, cfg); err != nil {

View file

@ -22,7 +22,6 @@ import (
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/event"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"github.com/pkg/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
@ -518,7 +517,7 @@ func (c *controller) processDeletePolicyForCloneGenerateRule(policy kyvernov1.Po
func (c *controller) updateSourceResource(pName string, rule kyvernov1.Rule) error {
obj, err := c.client.GetResource(context.TODO(), "", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name)
if err != nil {
return errors.Wrapf(err, "source resource %s/%s/%s not found", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name)
return fmt.Errorf("source resource %s/%s/%s not found: %w", rule.Generation.Kind, rule.Generation.Clone.Namespace, rule.Generation.Clone.Name, err)
}
var update bool

View file

@ -16,7 +16,6 @@ import (
"github.com/kyverno/kyverno/pkg/tracing"
datautils "github.com/kyverno/kyverno/pkg/utils/data"
wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors"
"github.com/sigstore/cosign/cmd/cosign/cli/fulcio"
"github.com/sigstore/cosign/cmd/cosign/cli/options"
"github.com/sigstore/cosign/cmd/cosign/cli/rekor"
@ -120,7 +119,7 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
ro := options.RegistryOptions{}
remoteOpts, err = ro.ClientOpts(ctx)
if err != nil {
return nil, errors.Wrap(err, "constructing client options")
return nil, fmt.Errorf("constructing client options: %w", err)
}
remoteOpts = append(remoteOpts, rclient.BuildRemoteOption(ctx))
cosignOpts := &cosign.CheckOpts{
@ -137,7 +136,7 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
if opts.Roots != "" {
cp, err := loadCertPool([]byte(opts.Roots))
if err != nil {
return nil, errors.Wrap(err, "failed to load Root certificates")
return nil, fmt.Errorf("failed to load Root certificates: %w", err)
}
cosignOpts.RootCerts = cp
}
@ -146,13 +145,13 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
if strings.HasPrefix(strings.TrimSpace(opts.Key), "-----BEGIN PUBLIC KEY-----") {
cosignOpts.SigVerifier, err = decodePEM([]byte(opts.Key), signatureAlgorithmMap[opts.SignatureAlgorithm])
if err != nil {
return nil, errors.Wrap(err, "failed to load public key from PEM")
return nil, fmt.Errorf("failed to load public key from PEM: %w", err)
}
} else {
// this supports Kubernetes secrets and KMS
cosignOpts.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, opts.Key)
if err != nil {
return nil, errors.Wrapf(err, "failed to load public key from %s", opts.Key)
return nil, fmt.Errorf("failed to load public key from %s: %w", opts.Key, err)
}
}
} else {
@ -160,30 +159,30 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
// load cert and optionally a cert chain as a verifier
cert, err := loadCert([]byte(opts.Cert))
if err != nil {
return nil, errors.Wrapf(err, "failed to load certificate from %s", opts.Cert)
return nil, fmt.Errorf("failed to load certificate from %s: %w", opts.Cert, err)
}
if opts.CertChain == "" {
cosignOpts.SigVerifier, err = signature.LoadVerifier(cert.PublicKey, crypto.SHA256)
if err != nil {
return nil, errors.Wrap(err, "failed to load signature from certificate")
return nil, fmt.Errorf("failed to load signature from certificate: %w", err)
}
} else {
// Verify certificate with chain
chain, err := loadCertChain([]byte(opts.CertChain))
if err != nil {
return nil, errors.Wrap(err, "failed to load load certificate chain")
return nil, fmt.Errorf("failed to load load certificate chain: %w", err)
}
cosignOpts.SigVerifier, err = cosign.ValidateAndUnpackCertWithChain(cert, chain, cosignOpts)
if err != nil {
return nil, errors.Wrap(err, "failed to load validate certificate chain")
return nil, fmt.Errorf("failed to load validate certificate chain: %w", err)
}
}
} else if opts.CertChain != "" {
// load cert chain as roots
cp, err := loadCertPool([]byte(opts.CertChain))
if err != nil {
return nil, errors.Wrap(err, "failed to load certificates")
return nil, fmt.Errorf("failed to load certificates: %w", err)
}
cosignOpts.RootCerts = cp
} else {
@ -191,7 +190,7 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
if cosignOpts.RootCerts == nil {
roots, err := fulcio.GetRoots()
if err != nil {
return nil, fmt.Errorf("failed to get roots from fulcio")
return nil, fmt.Errorf("failed to get roots from fulcio: %w", err)
}
cosignOpts.RootCerts = roots
if cosignOpts.RootCerts == nil {
@ -204,14 +203,14 @@ func buildCosignOptions(ctx context.Context, rclient registryclient.Client, opts
if opts.RekorURL != "" {
cosignOpts.RekorClient, err = rekor.NewClient(opts.RekorURL)
if err != nil {
return nil, errors.Wrapf(err, "failed to create Rekor client from URL %s", opts.RekorURL)
return nil, fmt.Errorf("failed to create Rekor client from URL %s: %w", opts.RekorURL, err)
}
}
if opts.Repository != "" {
signatureRepo, err := name.NewRepository(opts.Repository)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse signature repository %s", opts.Repository)
return nil, fmt.Errorf("failed to parse signature repository %s: %w", opts.Repository, err)
}
cosignOpts.RegistryClientOpts = append(cosignOpts.RegistryClientOpts, remote.WithTargetRepository(signatureRepo))
@ -239,10 +238,10 @@ func loadCert(pem []byte) (*x509.Certificate, error) {
certs, err := cryptoutils.UnmarshalCertificatesFromPEM(out)
if err != nil {
return nil, errors.Wrap(err, "failed to unmarshal certificate from PEM format")
return nil, fmt.Errorf("failed to unmarshal certificate from PEM format: %w", err)
}
if len(certs) == 0 {
return nil, errors.New("no certs found in pem file")
return nil, fmt.Errorf("no certs found in pem file")
}
return certs[0], nil
}
@ -266,7 +265,7 @@ func FetchAttestations(ctx context.Context, rclient registryclient.Client, opts
func(ctx context.Context, span trace.Span) (checkedAttestations []oci.Signature, bundleVerified bool, err error) {
ref, err := name.ParseReference(opts.ImageRef)
if err != nil {
return nil, false, errors.Wrap(err, "failed to parse image")
return nil, false, fmt.Errorf("failed to parse image: %w", err)
}
return client.VerifyImageAttestations(ctx, ref, cosignOpts)
},
@ -275,7 +274,7 @@ func FetchAttestations(ctx context.Context, rclient registryclient.Client, opts
msg := err.Error()
logger.Info("failed to fetch attestations", "error", msg)
if strings.Contains(msg, "MANIFEST_UNKNOWN: manifest unknown") {
return nil, errors.Wrap(fmt.Errorf("not found"), "")
return nil, fmt.Errorf("not found")
}
return nil, err
@ -320,7 +319,7 @@ func matchPredicateType(sig oci.Signature, expectedPredicateType string) (bool,
if expectedPredicateType != "" {
statement, _, err := decodeStatement(sig)
if err != nil {
return false, "", errors.Wrapf(err, "failed to decode predicateType")
return false, "", fmt.Errorf("failed to decode predicateType: %w", err)
}
if pType, ok := statement["predicateType"]; ok {
@ -358,12 +357,12 @@ func decodeStatement(sig oci.Signature) (map[string]interface{}, string, error)
pld, err := sig.Payload()
if err != nil {
return nil, "", errors.Wrap(err, "failed to decode payload")
return nil, "", fmt.Errorf("failed to decode payload: %w", err)
}
sci := payload.SimpleContainerImage{}
if err := json.Unmarshal(pld, &sci); err != nil {
return nil, "", errors.Wrap(err, "error decoding the payload")
return nil, "", fmt.Errorf("error decoding the payload: %w", err)
}
if d := sci.Critical.Image.DockerManifestDigest; d != "" {
@ -372,7 +371,7 @@ func decodeStatement(sig oci.Signature) (map[string]interface{}, string, error)
data := make(map[string]interface{})
if err := json.Unmarshal(pld, &data); err != nil {
return nil, "", errors.Wrapf(err, "failed to unmarshal JSON payload: %v", sig)
return nil, "", fmt.Errorf("failed to unmarshal JSON payload: %v: %w", sig, err)
}
if dataPayload, ok := data["payload"]; !ok {
@ -380,7 +379,7 @@ func decodeStatement(sig oci.Signature) (map[string]interface{}, string, error)
} else {
decodedStatement, err := decodePayload(dataPayload.(string))
if err != nil {
return nil, "", errors.Wrapf(err, "failed to decode statement %s", string(pld))
return nil, "", fmt.Errorf("failed to decode statement %s: %w", string(pld), err)
}
return decodedStatement, digest, nil
@ -390,7 +389,7 @@ func decodeStatement(sig oci.Signature) (map[string]interface{}, string, error)
func decodePayload(payloadBase64 string) (map[string]interface{}, error) {
statementRaw, err := base64.StdEncoding.DecodeString(payloadBase64)
if err != nil {
return nil, errors.Wrapf(err, "failed to base64 decode payload for %v", statementRaw)
return nil, fmt.Errorf("failed to base64 decode payload for %v: %w", statementRaw, err)
}
var statement in_toto.Statement
@ -443,7 +442,7 @@ func stringToJSONMap(i interface{}) (map[string]interface{}, error) {
data := map[string]interface{}{}
if err := json.Unmarshal([]byte(s), &data); err != nil {
return nil, fmt.Errorf("failed to marshal JSON: %s", err.Error())
return nil, fmt.Errorf("failed to marshal JSON: %w", err)
}
return data, nil
@ -453,7 +452,7 @@ func decodePEM(raw []byte, signatureAlgorithm crypto.Hash) (signature.Verifier,
// PEM encoded file.
pubKey, err := cryptoutils.UnmarshalPEMToPublicKey(raw)
if err != nil {
return nil, errors.Wrap(err, "pem to public key")
return nil, fmt.Errorf("pem to public key: %w", err)
}
return signature.LoadVerifier(pubKey, signatureAlgorithm)
@ -464,12 +463,12 @@ func extractPayload(verified []oci.Signature) ([]payload.SimpleContainerImage, e
for _, sig := range verified {
pld, err := sig.Payload()
if err != nil {
return nil, errors.Wrap(err, "failed to get payload")
return nil, fmt.Errorf("failed to get payload: %w", err)
}
sci := payload.SimpleContainerImage{}
if err := json.Unmarshal(pld, &sci); err != nil {
return nil, errors.Wrap(err, "error decoding the payload")
return nil, fmt.Errorf("error decoding the payload: %w", err)
}
sigPayloads = append(sigPayloads, sci)
@ -482,10 +481,10 @@ func extractDigest(imgRef string, payload []payload.SimpleContainerImage) (strin
if digest := p.Critical.Image.DockerManifestDigest; digest != "" {
return digest, nil
} else {
return "", fmt.Errorf("failed to extract image digest from signature payload for " + imgRef)
return "", fmt.Errorf("failed to extract image digest from signature payload for %s", imgRef)
}
}
return "", fmt.Errorf("digest not found for " + imgRef)
return "", fmt.Errorf("digest not found for %s", imgRef)
}
func matchSignatures(signatures []oci.Signature, subject, issuer string, extensions map[string]string) error {
@ -497,11 +496,11 @@ func matchSignatures(signatures []oci.Signature, subject, issuer string, extensi
for _, sig := range signatures {
cert, err := sig.Cert()
if err != nil {
return errors.Wrap(err, "failed to read certificate")
return fmt.Errorf("failed to read certificate: %w", err)
}
if cert == nil {
return errors.Errorf("certificate not found")
return fmt.Errorf("certificate not found")
}
if err := matchCertificateData(cert, subject, issuer, extensions); err != nil {
@ -574,7 +573,7 @@ func extractCertExtensionValue(key string, ce cosign.CertExtensions) (string, er
case cosign.CertExtensionGithubWorkflowRef, cosign.CertExtensionMap[cosign.CertExtensionGithubWorkflowRef]:
return ce.GetCertExtensionGithubWorkflowRef(), nil
default:
return "", errors.Errorf("invalid certificate extension %s", key)
return "", fmt.Errorf("invalid certificate extension %s", key)
}
}

View file

@ -17,7 +17,6 @@ import (
"github.com/kyverno/kyverno/pkg/engine/context"
"github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/pkg/errors"
)
type apiCall struct {
@ -91,12 +90,12 @@ func (a *apiCall) executeServiceCall(service *kyvernov1.ServiceCall) ([]byte, er
req, err := a.buildHTTPRequest(service)
if err != nil {
return nil, errors.Wrapf(err, "failed to build HTTP request for APICall %s", a.entry.Name)
return nil, fmt.Errorf("failed to build HTTP request for APICall %s: %w", a.entry.Name, err)
}
resp, err := client.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "failed to execute HTTP request for APICall %s", a.entry.Name)
return nil, fmt.Errorf("failed to execute HTTP request for APICall %s: %w", a.entry.Name, err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
@ -106,7 +105,7 @@ func (a *apiCall) executeServiceCall(service *kyvernov1.ServiceCall) ([]byte, er
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrapf(err, "failed to read data from APICall %s", a.entry.Name)
return nil, fmt.Errorf("failed to read data from APICall %s: %w", a.entry.Name, err)
}
a.log.Info("executed service APICall", "name", a.entry.Name, "len", len(body))
@ -177,7 +176,7 @@ func (a *apiCall) buildPostData(data []kyvernov1.RequestData) (io.Reader, error)
buffer := new(bytes.Buffer)
if err := json.NewEncoder(buffer).Encode(dataMap); err != nil {
return nil, errors.Wrapf(err, "failed to encode HTTP POST data %v for APICall %s", dataMap, a.entry.Name)
return nil, fmt.Errorf("failed to encode HTTP POST data %v for APICall %s: %w", dataMap, a.entry.Name, err)
}
return buffer, nil
@ -187,7 +186,7 @@ func (a *apiCall) transformAndStore(jsonData []byte) ([]byte, error) {
if a.entry.APICall.JMESPath == "" {
err := a.jsonCtx.AddContextEntry(a.entry.Name, jsonData)
if err != nil {
return nil, errors.Wrapf(err, "failed to add resource data to context entry %s", a.entry.Name)
return nil, fmt.Errorf("failed to add resource data to context entry %s: %w", a.entry.Name, err)
}
return jsonData, nil
@ -195,22 +194,22 @@ func (a *apiCall) transformAndStore(jsonData []byte) ([]byte, error) {
path, err := variables.SubstituteAll(a.log, a.jsonCtx, a.entry.APICall.JMESPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to substitute variables in context entry %s JMESPath %s", a.entry.Name, a.entry.APICall.JMESPath)
return nil, fmt.Errorf("failed to substitute variables in context entry %s JMESPath %s: %w", a.entry.Name, a.entry.APICall.JMESPath, err)
}
results, err := applyJMESPathJSON(path.(string), jsonData)
if err != nil {
return nil, errors.Wrapf(err, "failed to apply JMESPath %s for context entry %s", path, a.entry.Name)
return nil, fmt.Errorf("failed to apply JMESPath %s for context entry %s: %w", path, a.entry.Name, err)
}
contextData, err := json.Marshal(results)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshall APICall data for context entry %s", a.entry.Name)
return nil, fmt.Errorf("failed to marshall APICall data for context entry %s: %w", a.entry.Name, err)
}
err = a.jsonCtx.AddContextEntry(a.entry.Name, contextData)
if err != nil {
return nil, errors.Wrapf(err, "failed to add APICall results for context entry %s", a.entry.Name)
return nil, fmt.Errorf("failed to add APICall results for context entry %s: %w", a.entry.Name, err)
}
a.log.V(4).Info("added context data", "name", a.entry.Name, "len", len(contextData))
@ -221,7 +220,7 @@ func applyJMESPathJSON(jmesPath string, jsonData []byte) (interface{}, error) {
var data interface{}
err := json.Unmarshal(jsonData, &data)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON: %s, error: %v", string(jsonData), err)
return nil, fmt.Errorf("failed to unmarshal JSON: %s, error: %w", string(jsonData), err)
}
jp, err := jmespath.New(jmesPath)

View file

@ -12,7 +12,6 @@ import (
"github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/logging"
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
"github.com/pkg/errors"
admissionv1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
@ -125,7 +124,7 @@ func (ctx *context) addJSON(dataRaw []byte) error {
defer ctx.mutex.Unlock()
json, err := jsonpatch.MergeMergePatches(ctx.jsonRaw, dataRaw)
if err != nil {
return errors.Wrap(err, "failed to merge JSON data")
return fmt.Errorf("failed to merge JSON data: %w", err)
}
ctx.jsonRaw = json
return nil
@ -283,7 +282,7 @@ func (ctx *context) AddImageInfos(resource *unstructured.Unstructured, cfg confi
func (ctx *context) GenerateCustomImageInfo(resource *unstructured.Unstructured, imageExtractorConfigs kyvernov1.ImageExtractorConfigs, cfg config.Configuration) (map[string]map[string]apiutils.ImageInfo, error) {
images, err := apiutils.ExtractImagesFromResource(*resource, imageExtractorConfigs, cfg)
if err != nil {
return nil, errors.Wrapf(err, "failed to extract images")
return nil, fmt.Errorf("failed to extract images: %w", err)
}
if len(images) == 0 {

View file

@ -7,7 +7,6 @@ import (
"strings"
"github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/pkg/errors"
)
// Query the JSON context with JMESPATH search path
@ -27,11 +26,11 @@ func (ctx *context) Query(query string) (interface{}, error) {
defer ctx.mutex.RUnlock()
var data interface{}
if err := json.Unmarshal(ctx.jsonRaw, &data); err != nil {
return nil, errors.Wrap(err, "failed to unmarshal context")
return nil, fmt.Errorf("failed to unmarshal context: %w", err)
}
result, err := queryPath.Search(data)
if err != nil {
return nil, errors.Wrap(err, "JMESPath query failed")
return nil, fmt.Errorf("JMESPath query failed: %w", err)
}
return result, nil
}
@ -39,14 +38,14 @@ func (ctx *context) Query(query string) (interface{}, error) {
func (ctx *context) HasChanged(jmespath string) (bool, error) {
objData, err := ctx.Query("request.object." + jmespath)
if err != nil {
return false, errors.Wrap(err, "failed to query request.object")
return false, fmt.Errorf("failed to query request.object: %w", err)
}
if objData == nil {
return false, fmt.Errorf("request.object.%s not found", jmespath)
}
oldObjData, err := ctx.Query("request.oldObject." + jmespath)
if err != nil {
return false, errors.Wrap(err, "failed to query request.object")
return false, fmt.Errorf("failed to query request.object: %w", err)
}
if oldObjData == nil {
return false, fmt.Errorf("request.oldObject.%s not found", jmespath)

View file

@ -11,7 +11,6 @@ import (
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils/api"
"github.com/pkg/errors"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
@ -60,7 +59,7 @@ func applyForEachMutate(name string, foreach []kyvernov1.ForEachMutation, resour
if fe.ForEachMutation != nil {
nestedForEach, err := api.DeserializeJSONArray[kyvernov1.ForEachMutation](fe.ForEachMutation)
if err != nil {
return patchedResource, errors.Wrapf(err, "failed to deserialize foreach")
return patchedResource, fmt.Errorf("failed to deserialize foreach: %w", err)
}
return applyForEachMutate(name, nestedForEach, patchedResource, ctx, logger)

View file

@ -3,6 +3,7 @@ package engine
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"reflect"
@ -23,7 +24,6 @@ import (
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
"github.com/kyverno/kyverno/pkg/utils/jsonpointer"
"github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/trace"
"go.uber.org/multierr"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -284,7 +284,7 @@ func (iv *imageVerifier) handleMutateDigest(ctx context.Context, digest string,
patch, err := makeAddDigestPatch(imageInfo, digest)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to create image digest patch")
return nil, "", fmt.Errorf("failed to create image digest patch: %w", err)
}
iv.logger.V(4).Info("adding digest patch", "image", imageInfo.String(), "patch", string(patch))
@ -451,7 +451,7 @@ func (iv *imageVerifier) verifyAttestations(
attestationError = iv.verifyAttestation(cosignResp.Statements, attestation, imageInfo)
if attestationError != nil {
attestationError = errors.Wrapf(attestationError, entryPath+subPath)
attestationError = fmt.Errorf("%s: %w", entryPath+subPath, attestationError)
return ruleResponse(*iv.rule, engineapi.ImageVerify, attestationError.Error(), engineapi.RuleStatusFail), ""
}
@ -498,7 +498,7 @@ func (iv *imageVerifier) verifyAttestorSet(
if a.Attestor != nil {
nestedAttestorSet, err := kyvernov1.AttestorSetUnmarshal(a.Attestor)
if err != nil {
entryError = errors.Wrapf(err, "failed to unmarshal nested attestor %s", attestorPath)
entryError = fmt.Errorf("failed to unmarshal nested attestor %s: %w", attestorPath, err)
} else {
attestorPath += ".attestor"
cosignResp, entryError = iv.verifyAttestorSet(ctx, *nestedAttestorSet, imageVerify, imageInfo, attestorPath)
@ -507,7 +507,7 @@ func (iv *imageVerifier) verifyAttestorSet(
opts, subPath := iv.buildOptionsAndPath(a, imageVerify, image, nil)
cosignResp, entryError = cosign.VerifySignature(ctx, iv.rclient, *opts)
if entryError != nil {
entryError = errors.Wrapf(entryError, attestorPath+subPath)
entryError = fmt.Errorf("%s: %w", attestorPath+subPath, entryError)
}
}
@ -667,7 +667,7 @@ func (iv *imageVerifier) verifyAttestation(statements []map[string]interface{},
iv.logger.Info("checking attestation", "predicates", types, "image", imageInfo.String())
val, err := iv.checkAttestations(attestation, s)
if err != nil {
return errors.Wrap(err, "failed to check attestations")
return fmt.Errorf("failed to check attestations: %w", err)
}
if !val {
@ -718,12 +718,12 @@ func evaluateConditions(
}
if err := enginecontext.AddJSONObject(ctx, predicate); err != nil {
return false, errors.Wrapf(err, fmt.Sprintf("failed to add Statement to the context %v", s))
return false, fmt.Errorf("failed to add Statement to the context %v: %w", s, err)
}
c, err := variables.SubstituteAllInConditions(log, ctx, conditions)
if err != nil {
return false, errors.Wrapf(err, "failed to substitute variables in attestation conditions")
return false, fmt.Errorf("failed to substitute variables in attestation conditions: %w", err)
}
pass := variables.EvaluateAnyAllConditions(log, ctx, c)

View file

@ -2,10 +2,10 @@ package engine
import (
"encoding/json"
"fmt"
"strings"
"github.com/go-logr/logr"
"github.com/pkg/errors"
)
const imageVerifyAnnotationKey = "kyverno.io/verify-images"
@ -64,7 +64,7 @@ func (ivm *ImageVerificationMetadata) Patches(hasAnnotations bool, log logr.Logg
data, err := json.Marshal(ivm.Data)
if err != nil {
return nil, errors.Wrapf(err, "failed to marshal metadata value: %v", data)
return nil, fmt.Errorf("failed to marshal metadata value: %v: %w", data, err)
}
addKeyPatch := make(map[string]interface{})

View file

@ -11,7 +11,6 @@ import (
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
@ -103,7 +102,7 @@ func validateImage(ctx engineapi.PolicyContext, imageVerify *kyvernov1.ImageVeri
func isImageVerified(resource unstructured.Unstructured, image string, log logr.Logger) (bool, error) {
if reflect.DeepEqual(resource, unstructured.Unstructured{}) {
return false, errors.Errorf("nil resource")
return false, fmt.Errorf("nil resource")
}
annotations := resource.GetAnnotations()
@ -115,13 +114,13 @@ func isImageVerified(resource unstructured.Unstructured, image string, log logr.
data, ok := annotations[key]
if !ok {
log.V(2).Info("missing image metadata in annotation", "key", key)
return false, errors.Errorf("image is not verified")
return false, fmt.Errorf("image is not verified")
}
ivm, err := parseImageMetadata(data)
if err != nil {
log.Error(err, "failed to parse image verification metadata", "data", data)
return false, errors.Wrapf(err, "failed to parse image metadata")
return false, fmt.Errorf("failed to parse image metadata: %w", err)
}
return ivm.isVerified(image), nil

View file

@ -12,11 +12,10 @@ import (
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/engine/apicall"
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
jmespath "github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/registryclient"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
)
@ -285,10 +284,10 @@ func fetchImageDataMap(ctx context.Context, rclient registryclient.Client, ref s
func loadAPIData(ctx context.Context, logger logr.Logger, entry kyvernov1.ContextEntry, enginectx enginecontext.Interface, client dclient.Interface) error {
executor, err := apicall.New(ctx, entry, enginectx, client, logger)
if err != nil {
return errors.Wrapf(err, "failed to initialize APICall")
return fmt.Errorf("failed to initialize APICall: %w", err)
}
if _, err := executor.Execute(); err != nil {
return errors.Wrapf(err, "failed to execute APICall")
return fmt.Errorf("failed to execute APICall: %w", err)
}
return nil
}

View file

@ -20,7 +20,6 @@ import (
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/pkg/errors"
"github.com/sigstore/k8s-manifest-sigstore/pkg/k8smanifest"
"go.uber.org/multierr"
admissionv1 "k8s.io/api/admission/v1"
@ -60,20 +59,20 @@ func verifyManifest(policyContext engineapi.PolicyContext, verifyRule kyvernov1.
// load AdmissionRequest
request, err := policyContext.JSONContext().Query("request")
if err != nil {
return false, "", errors.Wrapf(err, "failed to get a request from policyContext")
return false, "", fmt.Errorf("failed to get a request from policyContext: %w", err)
}
reqByte, _ := json.Marshal(request)
var adreq *admissionv1.AdmissionRequest
err = json.Unmarshal(reqByte, &adreq)
if err != nil {
return false, "", errors.Wrapf(err, "failed to unmarshal a request from requestByte")
return false, "", fmt.Errorf("failed to unmarshal a request from requestByte: %w", err)
}
// unmarshal admission request object
var resource unstructured.Unstructured
objectBytes := adreq.Object.Raw
err = json.Unmarshal(objectBytes, &resource)
if err != nil {
return false, "", errors.Wrapf(err, "failed to Unmarshal a requested object")
return false, "", fmt.Errorf("failed to Unmarshal a requested object: %w", err)
}
logger.V(4).Info("verifying manifest", "namespace", adreq.Namespace, "kind", adreq.Kind.Kind,
@ -168,12 +167,12 @@ func verifyManifestAttestorSet(resource unstructured.Unstructured, attestorSet k
if a.Attestor != nil {
nestedAttestorSet, err := kyvernov1.AttestorSetUnmarshal(a.Attestor)
if err != nil {
entryError = errors.Wrapf(err, "failed to unmarshal nested attestor %s", attestorPath)
entryError = fmt.Errorf("failed to unmarshal nested attestor %s: %w", attestorPath, err)
} else {
attestorPath += ".attestor"
verified, reason, err = verifyManifestAttestorSet(resource, *nestedAttestorSet, vo, attestorPath, uid, logger)
if err != nil {
entryError = errors.Wrapf(err, "failed to verify signature; %s", attestorPath)
entryError = fmt.Errorf("failed to verify signature; %s: %w", attestorPath, err)
}
}
} else {
@ -227,7 +226,7 @@ func k8sVerifyResource(resource unstructured.Unstructured, a kyvernov1.Attestor,
defer cleanEnvVariables(envVariables)
if err != nil {
logger.V(4).Info("failed to build verify option", err.Error())
return false, "", errors.Wrapf(err, attestorPath+subPath)
return false, "", fmt.Errorf("%s: %w", attestorPath+subPath, err)
}
logger.V(4).Info("verifying resource by k8s-manifest-sigstore")
@ -243,7 +242,7 @@ func k8sVerifyResource(resource unstructured.Unstructured, a kyvernov1.Attestor,
failReason := fmt.Sprintf("%s: %s", attestorPath+subPath, err.Error())
return false, failReason, nil
} else {
return false, "", errors.Wrapf(err, attestorPath+subPath)
return false, "", fmt.Errorf("%s: %w", attestorPath+subPath, err)
}
} else {
resBytes, _ := json.Marshal(result)
@ -279,7 +278,7 @@ func buildVerifyResourceOptionsAndPath(a kyvernov1.Attestor, vo *k8smanifest.Ver
err := os.Setenv(pubkeyEnv, Key)
envVariables = append(envVariables, pubkeyEnv)
if err != nil {
entryError = errors.Wrapf(err, "failed to set env variable; %s", pubkeyEnv)
entryError = fmt.Errorf("failed to set env variable; %s: %w", pubkeyEnv, err)
} else {
keyPath := fmt.Sprintf("env://%s", pubkeyEnv)
vo.KeyPath = keyPath
@ -300,7 +299,7 @@ func buildVerifyResourceOptionsAndPath(a kyvernov1.Attestor, vo *k8smanifest.Ver
err := os.Setenv(certEnv, Cert)
envVariables = append(envVariables, certEnv)
if err != nil {
entryError = errors.Wrapf(err, "failed to set env variable; %s", certEnv)
entryError = fmt.Errorf("failed to set env variable; %s: %w", certEnv, err)
} else {
certPath := fmt.Sprintf("env://%s", certEnv)
vo.Certificate = certPath
@ -313,7 +312,7 @@ func buildVerifyResourceOptionsAndPath(a kyvernov1.Attestor, vo *k8smanifest.Ver
err := os.Setenv(certChainEnv, CertChain)
envVariables = append(envVariables, certChainEnv)
if err != nil {
entryError = errors.Wrapf(err, "failed to set env variable; %s", certChainEnv)
entryError = fmt.Errorf("failed to set env variable; %s: %w", certChainEnv, err)
} else {
certChainPath := fmt.Sprintf("env://%s", certChainEnv)
vo.CertificateChain = certChainPath
@ -333,7 +332,7 @@ func buildVerifyResourceOptionsAndPath(a kyvernov1.Attestor, vo *k8smanifest.Ver
Roots := a.Keyless.Roots
cp, err := loadCertPool([]byte(Roots))
if err != nil {
entryError = errors.Wrap(err, "failed to load Root certificates")
entryError = fmt.Errorf("failed to load Root certificates: %w", err)
} else {
vo.RootCerts = cp
}

View file

@ -7,7 +7,6 @@ import (
"github.com/go-logr/logr"
"github.com/kyverno/kyverno/pkg/engine/anchor"
"github.com/kyverno/kyverno/pkg/engine/validate"
"github.com/pkg/errors"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
@ -67,7 +66,7 @@ func preProcessRecursive(logger logr.Logger, pattern, resource *yaml.RNode) erro
func walkMap(logger logr.Logger, pattern, resource *yaml.RNode) error {
if _, err := handleAddIfNotPresentAnchor(pattern, resource); err != nil {
return errors.Wrap(err, "failed to process addIfNotPresent anchor")
return fmt.Errorf("failed to process addIfNotPresent anchor: %w", err)
}
if err := validateConditions(logger, pattern, resource); err != nil {
@ -157,7 +156,7 @@ func processListOfMaps(logger logr.Logger, pattern, resource *yaml.RNode) error
anyGlobalConditionPassed = true
} else {
if err := handlePatternName(pattern, patternElementCopy, resourceElement); err != nil {
return errors.Wrap(err, "failed to update name in pattern")
return fmt.Errorf("failed to update name in pattern: %w", err)
}
}
}
@ -466,7 +465,7 @@ func deleteAnchorsInMap(node *yaml.RNode, traverseMappingNodes bool) (bool, erro
if anchorsExist {
if err := stripAnchorsFromNode(node, ""); err != nil {
return false, errors.Wrap(err, "failed to remove anchor tags")
return false, fmt.Errorf("failed to remove anchor tags: %w", err)
}
}
@ -527,7 +526,7 @@ func deleteAnchorsInList(node *yaml.RNode, traverseMappingNodes bool) (bool, err
if traverseMappingNodes && isMappingNode(element) {
shouldDelete, err = deleteAnchors(element, true, traverseMappingNodes)
if err != nil {
return false, errors.Wrap(err, "failed to delete anchors")
return false, fmt.Errorf("failed to delete anchors: %w", err)
}
}
@ -539,7 +538,7 @@ func deleteAnchorsInList(node *yaml.RNode, traverseMappingNodes bool) (bool, err
// inside sub-arrays. Delete them too.
canDelete, err := deleteAnchors(element, false, traverseMappingNodes)
if err != nil {
return false, errors.Wrap(err, "failed to delete anchors")
return false, fmt.Errorf("failed to delete anchors: %w", err)
}
if canDelete {
deleteListElement(node, i)

View file

@ -2,6 +2,7 @@ package engine
import (
"context"
"fmt"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
@ -11,7 +12,6 @@ import (
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
enginectx "github.com/kyverno/kyverno/pkg/engine/context"
admissionutils "github.com/kyverno/kyverno/pkg/utils/admission"
"github.com/pkg/errors"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -158,7 +158,7 @@ func (c *PolicyContext) FindExceptions(rule string) ([]*kyvernov2alpha1.PolicyEx
var result []*kyvernov2alpha1.PolicyException
policyName, err := cache.MetaNamespaceKeyFunc(c.policy)
if err != nil {
return nil, errors.Wrap(err, "failed to compute policy key")
return nil, fmt.Errorf("failed to compute policy key: %w", err)
}
for _, polex := range polexs {
if polex.Contains(policyName, rule) {
@ -299,14 +299,14 @@ func NewPolicyContextFromAdmissionRequest(
) (*PolicyContext, error) {
ctx, err := newVariablesContext(request, &admissionInfo)
if err != nil {
return nil, errors.Wrap(err, "failed to create policy rule context")
return nil, fmt.Errorf("failed to create policy rule context: %w", err)
}
newResource, oldResource, err := admissionutils.ExtractResources(nil, request)
if err != nil {
return nil, errors.Wrap(err, "failed to parse resource")
return nil, fmt.Errorf("failed to parse resource: %w", err)
}
if err := ctx.AddImageInfos(&newResource, configuration); err != nil {
return nil, errors.Wrap(err, "failed to add image information to the policy rule context")
return nil, fmt.Errorf("failed to add image information to the policy rule context: %w", err)
}
requestResource := request.RequestResource.DeepCopy()
policyContext := NewPolicyContextWithJsonContext(ctx).
@ -326,13 +326,13 @@ func NewPolicyContextFromAdmissionRequest(
func newVariablesContext(request *admissionv1.AdmissionRequest, userRequestInfo *kyvernov1beta1.RequestInfo) (enginectx.Interface, error) {
ctx := enginectx.NewContext()
if err := ctx.AddRequest(request); err != nil {
return nil, errors.Wrap(err, "failed to load incoming request in context")
return nil, fmt.Errorf("failed to load incoming request in context: %w", err)
}
if err := ctx.AddUserInfo(*userRequestInfo); err != nil {
return nil, errors.Wrap(err, "failed to load userInfo in context")
return nil, fmt.Errorf("failed to load userInfo in context: %w", err)
}
if err := ctx.AddServiceAccount(userRequestInfo.AdmissionUserInfo.Username); err != nil {
return nil, errors.Wrap(err, "failed to load service account in context")
return nil, fmt.Errorf("failed to load service account in context: %w", err)
}
return ctx, nil
}

View file

@ -17,7 +17,6 @@ import (
datautils "github.com/kyverno/kyverno/pkg/utils/data"
matchutils "github.com/kyverno/kyverno/pkg/utils/match"
"github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors"
"golang.org/x/exp/slices"
authenticationv1 "k8s.io/api/authentication/v1"
rbacv1 "k8s.io/api/rbac/v1"
@ -189,7 +188,7 @@ func MatchesResourceDescription(subresourceGVKToAPIResource map[string]*metav1.A
var reasonsForFailure []error
if policyNamespace != "" && policyNamespace != resourceRef.GetNamespace() {
return errors.New(" The policy and resource namespace are different. Therefore, policy skip this resource.")
return fmt.Errorf(" The policy and resource namespace are different. Therefore, policy skip this resource.")
}
if len(rule.MatchResources.Any) > 0 {
@ -249,7 +248,7 @@ func MatchesResourceDescription(subresourceGVKToAPIResource map[string]*metav1.A
}
if len(reasonsForFailure) > 0 {
return errors.New(errorMessage)
return fmt.Errorf(errorMessage)
}
return nil
@ -328,12 +327,12 @@ func ManagedPodResource(policy kyvernov1.PolicyInterface, resource unstructured.
func checkPreconditions(logger logr.Logger, ctx engineapi.PolicyContext, anyAllConditions apiextensions.JSON) (bool, error) {
preconditions, err := variables.SubstituteAllInPreconditions(logger, ctx.JSONContext(), anyAllConditions)
if err != nil {
return false, errors.Wrapf(err, "failed to substitute variables in preconditions")
return false, fmt.Errorf("failed to substitute variables in preconditions: %w", err)
}
typeConditions, err := utils.TransformConditions(preconditions)
if err != nil {
return false, errors.Wrapf(err, "failed to parse preconditions")
return false, fmt.Errorf("failed to parse preconditions: %w", err)
}
pass := variables.EvaluateConditions(logger, ctx.JSONContext(), typeConditions)

View file

@ -24,7 +24,6 @@ import (
"github.com/kyverno/kyverno/pkg/utils/api"
datautils "github.com/kyverno/kyverno/pkg/utils/data"
matched "github.com/kyverno/kyverno/pkg/utils/match"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/trace"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
@ -250,12 +249,12 @@ func newForEachValidator(
ruleCopy := rule.DeepCopy()
anyAllConditions, err := datautils.ToMap(foreach.AnyAllConditions)
if err != nil {
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
return nil, fmt.Errorf("failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions: %w", err)
}
nestedForEach, err := api.DeserializeJSONArray[kyvernov1.ForEachValidation](foreach.ForEachValidation)
if err != nil {
return nil, errors.Wrap(err, "failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions")
return nil, fmt.Errorf("failed to convert ruleCopy.Validation.ForEachValidation.AnyAllConditions: %w", err)
}
return &validator{
@ -394,7 +393,7 @@ func addElementToContext(ctx engineapi.PolicyContext, element interface{}, index
return err
}
if err := ctx.JSONContext().AddElement(data, index, nesting); err != nil {
return errors.Wrapf(err, "failed to add element (%v) to JSON context", element)
return fmt.Errorf("failed to add element (%v) to JSON context: %w", element, err)
}
dataMap, ok := data.(map[string]interface{})
// We set scoped to true by default if the data is a map

View file

@ -2,12 +2,12 @@ package leaderelection
import (
"context"
"fmt"
"os"
"sync/atomic"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
@ -60,7 +60,7 @@ func New(log logr.Logger, name, namespace string, kubeClient kubernetes.Interfac
},
)
if err != nil {
return nil, errors.Wrapf(err, "error initializing resource lock: %s/%s", namespace, name)
return nil, fmt.Errorf("error initializing resource lock: %s/%s: %w", namespace, name, err)
}
e := &config{
name: name,

View file

@ -13,7 +13,6 @@ import (
"github.com/kyverno/kyverno/pkg/engine"
"github.com/kyverno/kyverno/pkg/logging"
cmap "github.com/orcaman/concurrent-map/v2"
"github.com/pkg/errors"
"gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@ -160,7 +159,7 @@ func (o *manager) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) error
if kind != "*" {
err = o.ValidateResource(*patchedResource.DeepCopy(), "", kind)
if err != nil {
return errors.Wrapf(err, "mutate result violates resource schema")
return fmt.Errorf("mutate result violates resource schema: %w", err)
}
}
}
@ -241,13 +240,13 @@ func (c *manager) UpdateKindToAPIVersions(apiResourceLists, preferredAPIResource
// For crd, we do not store definition in document
func (o *manager) getCRDSchema(kind string) (proto.Schema, error) {
if kind == "" {
return nil, errors.New("invalid kind")
return nil, fmt.Errorf("invalid kind")
}
path := proto.NewPath(kind)
definition, _ := o.definitions.Get(kind)
if definition == nil {
return nil, errors.New("could not find definition")
return nil, fmt.Errorf("could not find definition")
}
// This was added so crd's can access

View file

@ -5,7 +5,6 @@ import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/utils/api"
"github.com/pkg/errors"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
)
@ -61,7 +60,7 @@ func (m *Mutate) validateForEach(tag string, foreach []kyvernov1.ForEachMutation
func (m *Mutate) validateNestedForEach(tag string, j *v1.JSON) (string, error) {
nestedForeach, err := api.DeserializeJSONArray[kyvernov1.ForEachMutation](j)
if err != nil {
return tag, errors.Wrapf(err, "invalid foreach syntax")
return tag, fmt.Errorf("invalid foreach syntax: %w", err)
}
return m.validateForEach(tag, nestedForeach)

View file

@ -26,7 +26,6 @@ import (
"github.com/kyverno/kyverno/pkg/event"
"github.com/kyverno/kyverno/pkg/metrics"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"github.com/pkg/errors"
"go.uber.org/multierr"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
@ -510,7 +509,7 @@ func (pc *PolicyController) updateUR(policyKey string, policy kyvernov1.PolicyIn
func (pc *PolicyController) handleUpdateRequest(ur *kyvernov1beta1.UpdateRequest, triggerResource *unstructured.Unstructured, rule kyvernov1.Rule, policy kyvernov1.PolicyInterface) (skip bool, err error) {
policyContext, _, err := backgroundcommon.NewBackgroundContext(pc.client, ur, policy, triggerResource, pc.configHandler, pc.informerCacheResolvers, nil, pc.log)
if err != nil {
return false, errors.Wrapf(err, "failed to build policy context for rule %s", rule.Name)
return false, fmt.Errorf("failed to build policy context for rule %s: %w", rule.Name, err)
}
engineResponse := engine.ApplyBackgroundChecks(pc.contextLoader, policyContext)

View file

@ -3,6 +3,7 @@ package policy
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
@ -25,7 +26,6 @@ import (
apiutils "github.com/kyverno/kyverno/pkg/utils/api"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
"github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors"
"golang.org/x/exp/slices"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -292,7 +292,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the any match resource is invalid")
return warnings, fmt.Errorf("the kind defined in the any match resource is invalid: %w", err)
}
}
}
@ -304,7 +304,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the all match resource is invalid")
return warnings, fmt.Errorf("the kind defined in the all match resource is invalid: %w", err)
}
}
}
@ -316,7 +316,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the any exclude resource is invalid")
return warnings, fmt.Errorf("the kind defined in the any exclude resource is invalid: %w", err)
}
}
}
@ -328,7 +328,7 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if !slices.Contains(value.ResourceDescription.Kinds, "*") {
err := validateKinds(value.ResourceDescription.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "the kind defined in the all exclude resource is invalid")
return warnings, fmt.Errorf("the kind defined in the all exclude resource is invalid: %w", err)
}
}
}
@ -336,11 +336,11 @@ func Validate(policy kyvernov1.PolicyInterface, client dclient.Interface, mock b
if !slices.Contains(rule.MatchResources.Kinds, "*") {
err := validateKinds(rule.MatchResources.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "match resource kind is invalid")
return warnings, fmt.Errorf("match resource kind is invalid: %w", err)
}
err = validateKinds(rule.ExcludeResources.Kinds, mock, background, rule.HasValidate(), client)
if err != nil {
return warnings, errors.Wrapf(err, "exclude resource kind is invalid")
return warnings, fmt.Errorf("exclude resource kind is invalid: %w", err)
}
} else {
wildcardErr := validateWildcard(rule.MatchResources.Kinds, spec, rule)
@ -1072,7 +1072,7 @@ func validateImageRegistry(entry kyvernov1.ContextEntry) error {
if !strings.Contains(ref, "kyvernoimageref") {
_, err := reference.Parse(ref)
if err != nil {
return errors.Wrapf(err, "bad image: %s", ref)
return fmt.Errorf("bad image: %s: %w", ref, err)
}
}

View file

@ -1,8 +1,9 @@
package tls
import (
"fmt"
"github.com/kyverno/kyverno/pkg/config"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
corev1listers "k8s.io/client-go/listers/core/v1"
)
@ -23,7 +24,7 @@ func ReadRootCASecret(client corev1listers.SecretNamespaceLister) ([]byte, error
result = stlsca.Data[rootCAKey]
}
if len(result) == 0 {
return nil, errors.Errorf("%s in secret %s/%s", ErrorsNotFound, config.KyvernoNamespace(), stlsca.Name)
return nil, fmt.Errorf("%s in secret %s/%s", ErrorsNotFound, config.KyvernoNamespace(), stlsca.Name)
}
return result, nil
}

View file

@ -6,7 +6,6 @@ import (
"github.com/distribution/distribution/reference"
"github.com/kyverno/kyverno/pkg/config"
"github.com/pkg/errors"
"sigs.k8s.io/controller-runtime/pkg/log"
)
@ -62,7 +61,7 @@ func GetImageInfo(image string, cfg config.Configuration) (*ImageInfo, error) {
fullImageName := addDefaultRegistry(image, cfg)
ref, err := reference.Parse(fullImageName)
if err != nil {
return nil, errors.Wrapf(err, "bad image: %s", fullImageName)
return nil, fmt.Errorf("bad image: %s: %w", fullImageName, err)
}
var registry, path, name, tag, digest string

View file

@ -2,9 +2,9 @@ package kube
import (
"encoding/json"
"fmt"
datautils "github.com/kyverno/kyverno/pkg/utils/data"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
@ -18,7 +18,7 @@ func RedactSecret(resource *unstructured.Unstructured) (unstructured.Unstructure
}
err = json.Unmarshal(data, &secret)
if err != nil {
return *resource, errors.Wrap(err, "unable to convert object to secret")
return *resource, fmt.Errorf("unable to convert object to secret: %w", err)
}
stringSecret := struct {
Data map[string]string `json:"string_data"`
@ -41,27 +41,27 @@ func RedactSecret(resource *unstructured.Unstructured) (unstructured.Unstructure
}
err = json.Unmarshal(raw, &updateSecret)
if err != nil {
return *resource, errors.Wrap(err, "unable to convert object from secret")
return *resource, fmt.Errorf("unable to convert object from secret: %w", err)
}
if secret.Data != nil {
v := updateSecret["string_data"].(map[string]interface{})
err = unstructured.SetNestedMap(resource.Object, v, "data")
if err != nil {
return *resource, errors.Wrap(err, "failed to set secret.data")
return *resource, fmt.Errorf("failed to set secret.data: %w", err)
}
}
if secret.Annotations != nil {
metadata, err := datautils.ToMap(resource.Object["metadata"])
if err != nil {
return *resource, errors.Wrap(err, "unable to convert metadata to map")
return *resource, fmt.Errorf("unable to convert metadata to map: %w", err)
}
updatedMeta := updateSecret["metadata"].(map[string]interface{})
if err != nil {
return *resource, errors.Wrap(err, "unable to convert object from secret")
return *resource, fmt.Errorf("unable to convert object from secret: %w", err)
}
err = unstructured.SetNestedMap(metadata, updatedMeta["annotations"].(map[string]interface{}), "annotations")
if err != nil {
return *resource, errors.Wrap(err, "failed to set secret.annotations")
return *resource, fmt.Errorf("failed to set secret.annotations: %w", err)
}
}
return *resource, nil

View file

@ -2,10 +2,10 @@ package retry
import (
"context"
"fmt"
"time"
"github.com/go-logr/logr"
"github.com/pkg/errors"
)
// RetryFunc allows retrying a function on error within a given timeout
@ -25,7 +25,7 @@ func RetryFunc(ctx context.Context, retryInterval, timeout time.Duration, logger
return nil
}
case <-ctx.Done():
return errors.Wrap(err, "retry times out")
return fmt.Errorf("retry times out: %w", err)
}
}
}

View file

@ -18,7 +18,6 @@ import (
engineutils "github.com/kyverno/kyverno/pkg/utils/engine"
jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
webhookutils "github.com/kyverno/kyverno/pkg/webhooks/utils"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/trace"
admissionv1 "k8s.io/api/admission/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -167,7 +166,7 @@ func (h *mutationHandler) applyMutation(ctx context.Context, request *admissionv
if policyContext.Policy().ValidateSchema() && engineResponse.PatchedResource.GetKind() != "*" {
err := h.openApiManager.ValidateResource(*engineResponse.PatchedResource.DeepCopy(), engineResponse.PatchedResource.GetAPIVersion(), engineResponse.PatchedResource.GetKind())
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to validate resource mutated by policy %s", policyContext.Policy().GetName())
return nil, nil, fmt.Errorf("failed to validate resource mutated by policy %s: %w", policyContext.Policy().GetName(), err)
}
}
@ -181,7 +180,7 @@ func logMutationResponse(patches [][]byte, engineResponses []*engineapi.EngineRe
// if any of the policies fails, print out the error
if !engineutils.IsResponseSuccessful(engineResponses) {
logger.Error(errors.New(webhookutils.GetErrorMsg(engineResponses)), "failed to apply mutation rules on the resource, reporting policy violation")
logger.Error(fmt.Errorf(webhookutils.GetErrorMsg(engineResponses)), "failed to apply mutation rules on the resource, reporting policy violation")
}
}

View file

@ -1,13 +1,14 @@
package utils
import (
"fmt"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/engine"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/userinfo"
"github.com/pkg/errors"
admissionv1 "k8s.io/api/admission/v1"
rbacv1listers "k8s.io/client-go/listers/rbac/v1"
)
@ -48,7 +49,7 @@ func (b *policyContextBuilder) Build(request *admissionv1.AdmissionRequest) (*en
AdmissionUserInfo: *request.UserInfo.DeepCopy(),
}
if roles, clusterRoles, err := userinfo.GetRoleRef(b.rbLister, b.crbLister, request, b.configuration); err != nil {
return nil, errors.Wrap(err, "failed to fetch RBAC information for request")
return nil, fmt.Errorf("failed to fetch RBAC information for request: %w", err)
} else {
userRequestInfo.Roles = roles
userRequestInfo.ClusterRoles = clusterRoles