From 24b1428860e67096788a280e1a35c1e6a947cbe1 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:09:30 +0900 Subject: [PATCH] pkg/cosign: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- pkg/cosign/attestation/attestation.go | 7 ++--- pkg/cosign/common.go | 2 +- pkg/cosign/fetch.go | 15 +++++----- pkg/cosign/git/github/github.go | 12 ++++---- pkg/cosign/git/gitlab/gitlab.go | 28 +++++++++--------- pkg/cosign/keys.go | 20 ++++++------- pkg/cosign/kubernetes/secret.go | 18 ++++++------ .../clusterimagepolicy_types.go | 4 +-- pkg/cosign/kubernetes/webhook/validator.go | 24 +++++++-------- pkg/cosign/pivkey/pivkey.go | 10 +++---- pkg/cosign/pkcs11key/pkcs11key.go | 18 ++++++------ pkg/cosign/pkcs11key/util.go | 17 +++++------ pkg/cosign/tlog.go | 28 +++++++++--------- pkg/cosign/tuf/client.go | 29 +++++++++---------- pkg/cosign/tuf/policy.go | 10 +++---- pkg/cosign/verifiers.go | 2 +- pkg/cosign/verify.go | 28 +++++++++--------- pkg/cosign/verify_test.go | 2 +- 18 files changed, 135 insertions(+), 139 deletions(-) diff --git a/pkg/cosign/attestation/attestation.go b/pkg/cosign/attestation/attestation.go index 3215c32ca87..fac5c991975 100644 --- a/pkg/cosign/attestation/attestation.go +++ b/pkg/cosign/attestation/attestation.go @@ -26,7 +26,6 @@ import ( slsa "github.com/in-toto/in-toto-golang/in_toto/slsa_provenance/v0.2" "github.com/in-toto/in-toto-golang/in_toto" - "github.com/pkg/errors" ) const ( @@ -189,7 +188,7 @@ func generateCustomPredicate(rawPayload []byte, customType, timestamp string) (i var result map[string]interface{} if err := json.Unmarshal(rawPayload, &result); err != nil { - return nil, errors.Wrapf(err, "invalid JSON payload for predicate type %s", customType) + return nil, fmt.Errorf("invalid JSON payload for predicate type %s: %w", customType, err) } return result, nil @@ -203,7 +202,7 @@ func generateSLSAProvenanceStatement(rawPayload []byte, digest string, repo stri } err = json.Unmarshal(rawPayload, &predicate) if err != nil { - return "", errors.Wrap(err, "unmarshal Provenance predicate") + return "", fmt.Errorf("unmarshal Provenance predicate: %w", err) } return in_toto.ProvenanceStatement{ StatementHeader: generateStatementHeader(digest, repo, slsa.PredicateSLSAProvenance), @@ -219,7 +218,7 @@ func generateLinkStatement(rawPayload []byte, digest string, repo string) (inter } err = json.Unmarshal(rawPayload, &link) if err != nil { - return "", errors.Wrap(err, "unmarshal Link statement") + return "", fmt.Errorf("unmarshal Link statement: %w", err) } return in_toto.LinkStatement{ StatementHeader: generateStatementHeader(digest, repo, in_toto.PredicateLinkV1), diff --git a/pkg/cosign/common.go b/pkg/cosign/common.go index 1f8034a6b8d..4a8601c1cc7 100644 --- a/pkg/cosign/common.go +++ b/pkg/cosign/common.go @@ -17,12 +17,12 @@ package cosign import ( "bufio" + "errors" "fmt" "os" "strings" "syscall" - "github.com/pkg/errors" "golang.org/x/term" ) diff --git a/pkg/cosign/fetch.go b/pkg/cosign/fetch.go index 80b85762bfd..03324498bea 100644 --- a/pkg/cosign/fetch.go +++ b/pkg/cosign/fetch.go @@ -24,7 +24,6 @@ import ( "runtime" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" ociremote "github.com/sigstore/cosign/pkg/oci/remote" "knative.dev/pkg/pool" @@ -69,14 +68,14 @@ func FetchSignaturesForReference(ctx context.Context, ref name.Reference, opts . sigs, err := simg.Signatures() if err != nil { - return nil, errors.Wrap(err, "remote image") + return nil, fmt.Errorf("remote image: %w", err) } l, err := sigs.Get() if err != nil { - return nil, errors.Wrap(err, "fetching signatures") + return nil, fmt.Errorf("fetching signatures: %w", err) } if len(l) == 0 { - return nil, fmt.Errorf("no signatures associated with %v", ref) + return nil, fmt.Errorf("no signatures associated with %v: %w", ref, err) } g := pool.New(runtime.NumCPU()) @@ -119,14 +118,14 @@ func FetchAttestationsForReference(ctx context.Context, ref name.Reference, opts atts, err := simg.Attestations() if err != nil { - return nil, errors.Wrap(err, "remote image") + return nil, fmt.Errorf("remote image: %w", err) } l, err := atts.Get() if err != nil { - return nil, errors.Wrap(err, "fetching attestations") + return nil, fmt.Errorf("fetching attestations: %w", err) } if len(l) == 0 { - return nil, fmt.Errorf("no attestations associated with %v", ref) + return nil, fmt.Errorf("no attestations associated with %v: %w", ref, err) } g := pool.New(runtime.NumCPU()) @@ -153,7 +152,7 @@ func FetchAttestationsForReference(ctx context.Context, ref name.Reference, opts func FetchLocalSignedPayloadFromPath(path string) (*LocalSignedPayload, error) { contents, err := ioutil.ReadFile(path) if err != nil { - return nil, errors.Wrapf(err, "reading %s", path) + return nil, fmt.Errorf("reading %s: %w", path, err) } var b *LocalSignedPayload if err := json.Unmarshal(contents, &b); err != nil { diff --git a/pkg/cosign/git/github/github.go b/pkg/cosign/git/github/github.go index f92b733af99..9bfb6d9b9fa 100644 --- a/pkg/cosign/git/github/github.go +++ b/pkg/cosign/git/github/github.go @@ -18,6 +18,7 @@ package github import ( "context" "encoding/base64" + "errors" "fmt" "io" "net/http" @@ -25,7 +26,6 @@ import ( "strings" "github.com/google/go-github/v42/github" - "github.com/pkg/errors" "golang.org/x/oauth2" "github.com/sigstore/cosign/pkg/cosign" @@ -44,7 +44,7 @@ func New() *Gh { func (g *Gh) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) error { keys, err := cosign.GenerateKeyPair(pf) if err != nil { - return errors.Wrap(err, "generating key pair") + return fmt.Errorf("generating key pair: %w", err) } var httpClient *http.Client @@ -66,7 +66,7 @@ func (g *Gh) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro key, getRepoPubKeyResp, err := client.Actions.GetRepoPublicKey(ctx, owner, repo) if err != nil { - return errors.Wrap(err, "could not get repository public key") + return fmt.Errorf("could not get repository public key: %w", err) } if getRepoPubKeyResp.StatusCode < 200 && getRepoPubKeyResp.StatusCode >= 300 { @@ -82,7 +82,7 @@ func (g *Gh) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro passwordSecretEnvResp, err := client.Actions.CreateOrUpdateRepoSecret(ctx, owner, repo, passwordSecretEnv) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PASSWORD\" github actions secret") + return fmt.Errorf("could not create \"COSIGN_PASSWORD\" github actions secret: %w", err) } if passwordSecretEnvResp.StatusCode < 200 && passwordSecretEnvResp.StatusCode >= 300 { @@ -100,7 +100,7 @@ func (g *Gh) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro privateKeySecretEnvResp, err := client.Actions.CreateOrUpdateRepoSecret(ctx, owner, repo, privateKeySecretEnv) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PRIVATE_KEY\" github actions secret") + return fmt.Errorf("could not create \"COSIGN_PRIVATE_KEY\" github actions secret: %w", err) } if privateKeySecretEnvResp.StatusCode < 200 && privateKeySecretEnvResp.StatusCode >= 300 { @@ -118,7 +118,7 @@ func (g *Gh) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro publicKeySecretEnvResp, err := client.Actions.CreateOrUpdateRepoSecret(ctx, owner, repo, publicKeySecretEnv) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PUBLIC_KEY\" github actions secret") + return fmt.Errorf("could not create \"COSIGN_PUBLIC_KEY\" github actions secret: %w", err) } if publicKeySecretEnvResp.StatusCode < 200 && publicKeySecretEnvResp.StatusCode >= 300 { diff --git a/pkg/cosign/git/gitlab/gitlab.go b/pkg/cosign/git/gitlab/gitlab.go index c1439235156..d06b21785a7 100644 --- a/pkg/cosign/git/gitlab/gitlab.go +++ b/pkg/cosign/git/gitlab/gitlab.go @@ -17,11 +17,11 @@ package gitlab import ( "context" + "errors" "fmt" "io" "os" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign" "github.com/xanzy/go-gitlab" ) @@ -39,7 +39,7 @@ func New() *Gl { func (g *Gl) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) error { keys, err := cosign.GenerateKeyPair(pf) if err != nil { - return errors.Wrap(err, "generating key pair") + return fmt.Errorf("generating key pair: %w", err) } token, tokenExists := os.LookupEnv("GITLAB_TOKEN") @@ -52,12 +52,12 @@ func (g *Gl) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro if url, baseURLExists := os.LookupEnv("GITLAB_HOST"); baseURLExists { client, err = gitlab.NewClient(token, gitlab.WithBaseURL(url)) if err != nil { - return errors.Wrap(err, "could not create GitLab client") + return fmt.Errorf("could not create GitLab client: %w", err) } } else { client, err = gitlab.NewClient(token) if err != nil { - return errors.Wrap(err, "could not create GitLab client") + return fmt.Errorf("could not create GitLab client: %w", err) } } @@ -70,12 +70,12 @@ func (g *Gl) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro EnvironmentScope: gitlab.String("*"), }) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PASSWORD\" variable") + return fmt.Errorf("could not create \"COSIGN_PASSWORD\" variable: %w", err) } if passwordResp.StatusCode < 200 && passwordResp.StatusCode >= 300 { bodyBytes, _ := io.ReadAll(passwordResp.Body) - return errors.Errorf("%s", bodyBytes) + return fmt.Errorf("%s", bodyBytes) } fmt.Fprintln(os.Stderr, "Password written to \"COSIGN_PASSWORD\" variable") @@ -88,12 +88,12 @@ func (g *Gl) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro Masked: gitlab.Bool(false), }) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PRIVATE_KEY\" variable") + return fmt.Errorf("could not create \"COSIGN_PRIVATE_KEY\" variable: %w", err) } if privateKeyResp.StatusCode < 200 && privateKeyResp.StatusCode >= 300 { bodyBytes, _ := io.ReadAll(privateKeyResp.Body) - return errors.Errorf("%s", bodyBytes) + return fmt.Errorf("%s", bodyBytes) } fmt.Fprintln(os.Stderr, "Private key written to \"COSIGN_PRIVATE_KEY\" variable") @@ -106,12 +106,12 @@ func (g *Gl) PutSecret(ctx context.Context, ref string, pf cosign.PassFunc) erro Masked: gitlab.Bool(false), }) if err != nil { - return errors.Wrap(err, "could not create \"COSIGN_PUBLIC_KEY\" variable") + return fmt.Errorf("could not create \"COSIGN_PUBLIC_KEY\" variable: %w", err) } if publicKeyResp.StatusCode < 200 && publicKeyResp.StatusCode >= 300 { bodyBytes, _ := io.ReadAll(publicKeyResp.Body) - return errors.Errorf("%s", bodyBytes) + return fmt.Errorf("%s", bodyBytes) } fmt.Fprintln(os.Stderr, "Public key written to \"COSIGN_PUBLIC_KEY\" variable") @@ -136,25 +136,25 @@ func (g *Gl) GetSecret(ctx context.Context, ref string, key string) (string, err if url, baseURLExists := os.LookupEnv("GITLAB_HOST"); baseURLExists { client, err = gitlab.NewClient(token, gitlab.WithBaseURL(url)) if err != nil { - return varPubKeyValue, errors.Wrap(err, "could not create GitLab client") + return varPubKeyValue, fmt.Errorf("could not create GitLab client): %w", err) } } else { client, err = gitlab.NewClient(token) if err != nil { - return varPubKeyValue, errors.Wrap(err, "could not create GitLab client") + return varPubKeyValue, fmt.Errorf("could not create GitLab client: %w", err) } } varPubKey, pubKeyResp, err := client.ProjectVariables.GetVariable(ref, key, nil) if err != nil { - return varPubKeyValue, errors.Wrap(err, "could not retrieve \"COSIGN_PUBLIC_KEY\" variable") + return varPubKeyValue, fmt.Errorf("could not retrieve \"COSIGN_PUBLIC_KEY\" variable: %w", err) } varPubKeyValue = varPubKey.Value if pubKeyResp.StatusCode < 200 && pubKeyResp.StatusCode >= 300 { bodyBytes, _ := io.ReadAll(pubKeyResp.Body) - return varPubKeyValue, errors.Errorf("%s", bodyBytes) + return varPubKeyValue, fmt.Errorf("%s", bodyBytes) } return varPubKeyValue, nil diff --git a/pkg/cosign/keys.go b/pkg/cosign/keys.go index a0855f7f17f..a3cd8053e35 100644 --- a/pkg/cosign/keys.go +++ b/pkg/cosign/keys.go @@ -25,11 +25,11 @@ import ( _ "crypto/sha256" // for `crypto.SHA256` "crypto/x509" "encoding/pem" + "errors" "fmt" "os" "path/filepath" - "github.com/pkg/errors" "github.com/theupdateframework/go-tuf/encrypted" "github.com/sigstore/cosign/pkg/oci/static" @@ -84,10 +84,10 @@ func ImportKeyPair(keyPath string, pf PassFunc) (*KeysBytes, error) { case RSAPrivateKeyPemType: rsaPk, err := x509.ParsePKCS1PrivateKey(p.Bytes) if err != nil { - return nil, fmt.Errorf("error parsing rsa private key") + return nil, fmt.Errorf("error parsing rsa private key: %w", err) } if err = cryptoutils.ValidatePubKey(rsaPk.Public()); err != nil { - return nil, errors.Wrap(err, "error validating rsa key") + return nil, fmt.Errorf("error validating rsa key: %w", err) } pk = rsaPk case ECPrivateKeyPemType: @@ -96,7 +96,7 @@ func ImportKeyPair(keyPath string, pf PassFunc) (*KeysBytes, error) { return nil, fmt.Errorf("error parsing ecdsa private key") } if err = cryptoutils.ValidatePubKey(ecdsaPk.Public()); err != nil { - return nil, errors.Wrap(err, "error validating ecdsa key") + return nil, fmt.Errorf("error validating ecdsa key: %w", err) } pk = ecdsaPk case PrivateKeyPemType: @@ -107,17 +107,17 @@ func ImportKeyPair(keyPath string, pf PassFunc) (*KeysBytes, error) { switch k := pkcs8Pk.(type) { case *rsa.PrivateKey: if err = cryptoutils.ValidatePubKey(k.Public()); err != nil { - return nil, errors.Wrap(err, "error validating rsa key") + return nil, fmt.Errorf("error validating rsa key: %w", err) } pk = k case *ecdsa.PrivateKey: if err = cryptoutils.ValidatePubKey(k.Public()); err != nil { - return nil, errors.Wrap(err, "error validating ecdsa key") + return nil, fmt.Errorf("error validating ecdsa key: %w", err) } pk = k case ed25519.PrivateKey: if err = cryptoutils.ValidatePubKey(k.Public()); err != nil { - return nil, errors.Wrap(err, "error validating ed25519 key") + return nil, fmt.Errorf("error validating ed25519 key: %w", err) } pk = k default: @@ -132,7 +132,7 @@ func ImportKeyPair(keyPath string, pf PassFunc) (*KeysBytes, error) { func marshalKeyPair(keypair Keys, pf PassFunc) (key *KeysBytes, err error) { x509Encoded, err := x509.MarshalPKCS8PrivateKey(keypair.private) if err != nil { - return nil, errors.Wrap(err, "x509 encoding private key") + return nil, fmt.Errorf("x509 encoding private key: %w", err) } password := []byte{} @@ -204,12 +204,12 @@ func LoadPrivateKey(key []byte, pass []byte) (signature.SignerVerifier, error) { x509Encoded, err := encrypted.Decrypt(p.Bytes, pass) if err != nil { - return nil, errors.Wrap(err, "decrypt") + return nil, fmt.Errorf("decrypt: %w", err) } pk, err := x509.ParsePKCS8PrivateKey(x509Encoded) if err != nil { - return nil, errors.Wrap(err, "parsing private key") + return nil, fmt.Errorf("parsing private key: %w", err) } switch pk := pk.(type) { case *rsa.PrivateKey: diff --git a/pkg/cosign/kubernetes/secret.go b/pkg/cosign/kubernetes/secret.go index 385846fed8e..1461c314c17 100644 --- a/pkg/cosign/kubernetes/secret.go +++ b/pkg/cosign/kubernetes/secret.go @@ -16,13 +16,13 @@ package kubernetes import ( "context" + "errors" "fmt" "os" "strings" "k8s.io/utils/pointer" - "github.com/pkg/errors" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -42,12 +42,12 @@ func GetKeyPairSecret(ctx context.Context, k8sRef string) (*v1.Secret, error) { client, err := Client() if err != nil { - return nil, errors.Wrap(err, "new for config") + return nil, fmt.Errorf("new for config: %w", err) } var s *v1.Secret if s, err = client.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}); err != nil { - return nil, errors.Wrap(err, "checking if secret exists") + return nil, fmt.Errorf("checking if secret exists: %w", err) } return s, nil @@ -61,32 +61,32 @@ func KeyPairSecret(ctx context.Context, k8sRef string, pf cosign.PassFunc) error // now, generate the key in memory keys, err := cosign.GenerateKeyPair(pf) if err != nil { - return errors.Wrap(err, "generating key pair") + return fmt.Errorf("generating key pair: %w", err) } // create the k8s client client, err := Client() if err != nil { - return errors.Wrap(err, "new for config") + return fmt.Errorf("new for config: %w", err) } immutable, err := checkImmutableSecretSupported(client) if err != nil { - return errors.Wrap(err, "check immutable") + return fmt.Errorf("check immutable: %w", err) } var s *v1.Secret if s, err = client.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}); err != nil { if k8serrors.IsNotFound(err) { s, err = client.CoreV1().Secrets(namespace).Create(ctx, secret(keys, namespace, name, nil, immutable), metav1.CreateOptions{}) if err != nil { - return errors.Wrapf(err, "creating secret %s in ns %s", name, namespace) + return fmt.Errorf("creating secret %s in ns %s: %w", name, namespace, err) } } else { - return errors.Wrap(err, "checking if secret exists") + return fmt.Errorf("checking if secret exists: %w", err) } } else { // Update the existing secret s, err = client.CoreV1().Secrets(namespace).Update(ctx, secret(keys, namespace, name, s.Data, immutable), metav1.UpdateOptions{}) if err != nil { - return errors.Wrapf(err, "updating secret %s in ns %s", name, namespace) + return fmt.Errorf("updating secret %s in ns %s: %w", name, namespace, err) } } diff --git a/pkg/cosign/kubernetes/webhook/clusterimagepolicy/clusterimagepolicy_types.go b/pkg/cosign/kubernetes/webhook/clusterimagepolicy/clusterimagepolicy_types.go index d283519705d..2a6ccf576aa 100644 --- a/pkg/cosign/kubernetes/webhook/clusterimagepolicy/clusterimagepolicy_types.go +++ b/pkg/cosign/kubernetes/webhook/clusterimagepolicy/clusterimagepolicy_types.go @@ -20,11 +20,11 @@ import ( "crypto/x509" "encoding/json" "encoding/pem" + "fmt" "github.com/google/go-containerregistry/pkg/authn/k8schain" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" ociremote "github.com/sigstore/cosign/pkg/oci/remote" "knative.dev/pkg/apis" @@ -141,7 +141,7 @@ func (a *Authority) UnmarshalJSON(data []byte) error { if len(rawAuthority.Sources) > 0 { for _, source := range rawAuthority.Sources { if targetRepoOverride, err := name.NewRepository(source.OCI); err != nil { - return errors.Wrap(err, "failed to determine source") + return fmt.Errorf("failed to determine source: %w", err) } else if (targetRepoOverride != name.Repository{}) { rawAuthority.RemoteOpts = append(rawAuthority.RemoteOpts, ociremote.WithTargetRepository(targetRepoOverride)) } diff --git a/pkg/cosign/kubernetes/webhook/validator.go b/pkg/cosign/kubernetes/webhook/validator.go index 8371eb21b8c..c2f92c673f5 100644 --- a/pkg/cosign/kubernetes/webhook/validator.go +++ b/pkg/cosign/kubernetes/webhook/validator.go @@ -20,12 +20,12 @@ import ( "crypto" "crypto/x509" "encoding/json" + "errors" "fmt" "github.com/google/go-containerregistry/pkg/authn/k8schain" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/apis/config" webhookcip "github.com/sigstore/cosign/pkg/cosign/kubernetes/webhook/clusterimagepolicy" "github.com/sigstore/cosign/pkg/oci" @@ -421,7 +421,7 @@ func ValidatePolicySignaturesForAuthority(ctx context.Context, ref name.Referenc rekorClient, err = rekor.GetRekorClient(authority.CTLog.URL.String()) if err != nil { logging.FromContext(ctx).Errorf("failed creating rekor client: +v", err) - return nil, errors.Wrap(err, "creating Rekor client") + return nil, fmt.Errorf("creating Rekor client: %w", err) } } @@ -433,7 +433,7 @@ func ValidatePolicySignaturesForAuthority(ctx context.Context, ref name.Referenc // https://github.com/sigstore/cosign/issues/1652 sps, err := valid(ctx, ref, rekorClient, authority.Key.PublicKeys, remoteOpts...) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("failed to validate public keys with authority %s for %s", name, ref.Name())) + return nil, fmt.Errorf(fmt.Sprintf("failed to validate public keys with authority %s for %s: %w", name, ref.Name()), err) } else if len(sps) > 0 { logging.FromContext(ctx).Debugf("validated signature for %s with authority %s got %d signatures", ref.Name(), authority.Name, len(sps)) return ociSignatureToPolicySignature(ctx, sps), nil @@ -445,12 +445,12 @@ func ValidatePolicySignaturesForAuthority(ctx context.Context, ref name.Referenc logging.FromContext(ctx).Debugf("Fetching FulcioRoot for %s : From: %s ", ref.Name(), authority.Keyless.URL) fulcioroot, err := getFulcioCert(authority.Keyless.URL) if err != nil { - return nil, errors.Wrap(err, "fetching FulcioRoot") + return nil, fmt.Errorf("fetching FulcioRoot: %w", err) } sps, err := validSignaturesWithFulcio(ctx, ref, fulcioroot, rekorClient, authority.Keyless.Identities, remoteOpts...) if err != nil { logging.FromContext(ctx).Errorf("failed validSignatures for authority %s with fulcio for %s: %v", name, ref.Name(), err) - return nil, errors.Wrap(err, "validate signatures with fulcio") + return nil, fmt.Errorf("validate signatures with fulcio: %w", err) } else if len(sps) > 0 { logging.FromContext(ctx).Debugf("validated signature for %s, got %d signatures", ref.Name(), len(sps)) return ociSignatureToPolicySignature(ctx, sps), nil @@ -475,7 +475,7 @@ func ValidatePolicyAttestationsForAuthority(ctx context.Context, ref name.Refere rekorClient, err = rekor.GetRekorClient(authority.CTLog.URL.String()) if err != nil { logging.FromContext(ctx).Errorf("failed creating rekor client: +v", err) - return nil, errors.Wrap(err, "creating Rekor client") + return nil, fmt.Errorf("creating Rekor client: %w", err) } } @@ -486,12 +486,12 @@ func ValidatePolicyAttestationsForAuthority(ctx context.Context, ref name.Refere verifier, err := signature.LoadVerifier(k, crypto.SHA256) if err != nil { logging.FromContext(ctx).Errorf("error creating verifier: %v", err) - return nil, errors.Wrap(err, "creating verifier") + return nil, fmt.Errorf("creating verifier: %w", err) } va, err := validAttestations(ctx, ref, verifier, rekorClient, remoteOpts...) if err != nil { logging.FromContext(ctx).Errorf("error validating attestations: %v", err) - return nil, errors.Wrap(err, "validating attestations") + return nil, fmt.Errorf("validating attestations: %w", err) } verifiedAttestations = append(verifiedAttestations, va...) } @@ -501,12 +501,12 @@ func ValidatePolicyAttestationsForAuthority(ctx context.Context, ref name.Refere logging.FromContext(ctx).Debugf("Fetching FulcioRoot for %s : From: %s ", ref.Name(), authority.Keyless.URL) fulcioroot, err := getFulcioCert(authority.Keyless.URL) if err != nil { - return nil, errors.Wrap(err, "fetching FulcioRoot") + return nil, fmt.Errorf("fetching FulcioRoot: %w", err) } va, err := validAttestationsWithFulcio(ctx, ref, fulcioroot, rekorClient, authority.Keyless.Identities, remoteOpts...) if err != nil { logging.FromContext(ctx).Errorf("failed validAttestationsWithFulcio for authority %s with fulcio for %s: %v", name, ref.Name(), err) - return nil, errors.Wrap(err, "validate signatures with fulcio") + return nil, fmt.Errorf("validate signatures with fulcio: %w", err) } verifiedAttestations = append(verifiedAttestations, va...) } @@ -535,7 +535,7 @@ func ValidatePolicyAttestationsForAuthority(ctx context.Context, ref name.Refere for _, va := range verifiedAttestations { attBytes, err := policy.AttestationToPayloadJSON(ctx, wantedAttestation.PredicateType, va) if err != nil { - return nil, errors.Wrap(err, "failed to convert attestation payload to json") + return nil, fmt.Errorf("failed to convert attestation payload to json: %w", err) } if attBytes == nil { // This happens when we ask for a predicate type that this @@ -647,7 +647,7 @@ func getFulcioCert(u *apis.URL) (*x509.CertPool, error) { fClient := api.NewClient(u.URL()) rootCertResponse, err := fClient.RootCert() if err != nil { - return nil, errors.Wrap(err, "getting root cert") + return nil, fmt.Errorf("getting root cert: %w", err) } cp := x509.NewCertPool() diff --git a/pkg/cosign/pivkey/pivkey.go b/pkg/cosign/pivkey/pivkey.go index 409e6c8a7e9..d179e301a6e 100644 --- a/pkg/cosign/pivkey/pivkey.go +++ b/pkg/cosign/pivkey/pivkey.go @@ -25,13 +25,13 @@ import ( "crypto/rsa" "crypto/sha256" "crypto/x509" + "errors" "fmt" "io" "os" "syscall" "github.com/go-piv/piv-go/piv" - "github.com/pkg/errors" "golang.org/x/term" "github.com/sigstore/sigstore/pkg/signature" @@ -72,7 +72,7 @@ func GetKey() (*Key, error) { func GetKeyWithSlot(slot string) (*Key, error) { card, err := GetKey() if err != nil { - return nil, errors.Wrap(err, "open key") + return nil, fmt.Errorf("open key: %w", err) } card.slot = SlotForName(slot) @@ -168,17 +168,17 @@ func (k *Key) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, er func (k *Key) VerifySignature(signature, message io.Reader, opts ...signature.VerifyOption) error { sig, err := io.ReadAll(signature) if err != nil { - return errors.Wrap(err, "read signature") + return fmt.Errorf("read signature: %w", err) } msg, err := io.ReadAll(message) if err != nil { - return errors.Wrap(err, "read message") + return fmt.Errorf("read message: %w", err) } digest := sha256.Sum256(msg) att, err := k.Attest() if err != nil { - return errors.Wrap(err, "get attestation") + return fmt.Errorf("get attestation: %w", err) } switch kt := att.PublicKey.(type) { case *ecdsa.PublicKey: diff --git a/pkg/cosign/pkcs11key/pkcs11key.go b/pkg/cosign/pkcs11key/pkcs11key.go index 6d17ef96d1a..f1c7adf33e3 100644 --- a/pkg/cosign/pkcs11key/pkcs11key.go +++ b/pkg/cosign/pkcs11key/pkcs11key.go @@ -25,6 +25,7 @@ import ( "crypto/rsa" "crypto/sha256" "crypto/x509" + "errors" "fmt" "io" "os" @@ -33,7 +34,6 @@ import ( "github.com/ThalesIgnite/crypto11" "github.com/miekg/pkcs11" - "github.com/pkg/errors" "github.com/sigstore/sigstore/pkg/signature" "golang.org/x/term" ) @@ -72,7 +72,7 @@ func GetKeyWithURIConfig(config *Pkcs11UriConfig, askForPinIfNeeded bool) (*Key, } info, err := os.Stat(config.ModulePath) if err != nil { - return nil, errors.Wrap(err, "access modulePath") + return nil, fmt.Errorf("access modulePath: %w", err) } if !info.Mode().IsRegular() { return nil, errors.New("modulePath does not point to a regular file") @@ -93,7 +93,7 @@ func GetKeyWithURIConfig(config *Pkcs11UriConfig, askForPinIfNeeded bool) (*Key, } err := p.Initialize() if err != nil { - return errors.Wrap(err, "initialize PKCS11 module") + return fmt.Errorf("initialize PKCS11 module: %w", err) } defer p.Destroy() defer p.Finalize() @@ -103,18 +103,18 @@ func GetKeyWithURIConfig(config *Pkcs11UriConfig, askForPinIfNeeded bool) (*Key, if config.SlotID != nil { tokenInfo, err = p.GetTokenInfo(uint(*config.SlotID)) if err != nil { - return errors.Wrap(err, "get token info") + return fmt.Errorf("get token info: %w", err) } } else { slots, err := p.GetSlotList(true) if err != nil { - return errors.Wrap(err, "get slot list of PKCS11 module") + return fmt.Errorf("get slot list of PKCS11 module: %w", err) } for _, slot := range slots { currentTokenInfo, err := p.GetTokenInfo(slot) if err != nil { - return errors.Wrap(err, "get token info") + return fmt.Errorf("get token info: %w", err) } if currentTokenInfo.Label == config.TokenLabel { tokenInfo = currentTokenInfo @@ -134,7 +134,7 @@ func GetKeyWithURIConfig(config *Pkcs11UriConfig, askForPinIfNeeded bool) (*Key, // nolint:unconvert b, err := term.ReadPassword(int(syscall.Stdin)) if err != nil { - return errors.Wrap(err, "get pin") + return fmt.Errorf("get pin: %w", err) } conf.Pin = string(b) } @@ -196,11 +196,11 @@ func (k *Key) PublicKey(opts ...signature.PublicKeyOption) (crypto.PublicKey, er func (k *Key) VerifySignature(signature, message io.Reader, opts ...signature.VerifyOption) error { sig, err := io.ReadAll(signature) if err != nil { - return errors.Wrap(err, "read signature") + return fmt.Errorf("read signature: %w", err) } msg, err := io.ReadAll(message) if err != nil { - return errors.Wrap(err, "read message") + return fmt.Errorf("read message: %w", err) } digest := sha256.Sum256(msg) diff --git a/pkg/cosign/pkcs11key/util.go b/pkg/cosign/pkcs11key/util.go index 5d29b6d87db..43c513fa689 100644 --- a/pkg/cosign/pkcs11key/util.go +++ b/pkg/cosign/pkcs11key/util.go @@ -15,13 +15,12 @@ package pkcs11key import ( + "errors" "fmt" "net/url" "os" "strconv" "strings" - - "github.com/pkg/errors" ) const ( @@ -117,7 +116,7 @@ func (conf *Pkcs11UriConfig) Parse(uriString string) error { uri, err := url.Parse(uriString) if err != nil { - return errors.Wrap(err, "parse uri") + return fmt.Errorf("parse uri: %w", err) } if uri.Scheme != "pkcs11" { return errors.New("invalid uri: not a PKCS11 uri") @@ -129,12 +128,12 @@ func (conf *Pkcs11UriConfig) Parse(uriString string) error { uri.Opaque = strings.ReplaceAll(uri.Opaque, ";", "&") uriPathAttributes, err := url.ParseQuery(uri.Opaque) if err != nil { - return errors.Wrap(err, "parse uri path") + return fmt.Errorf("parse uri path: %w", err) } uri.RawQuery = strings.ReplaceAll(uri.RawQuery, ";", "&") uriQueryAttributes, err := url.ParseQuery(uri.RawQuery) if err != nil { - return errors.Wrap(err, "parse uri query") + return fmt.Errorf("parse uri query: %w", err) } modulePath := uriQueryAttributes.Get("module-path") pinValue := uriQueryAttributes.Get("pin-value") @@ -213,7 +212,7 @@ func (conf *Pkcs11UriConfig) Construct() (string, error) { if conf.TokenLabel != "" { tokenLabel, err = EncodeURIComponent(conf.TokenLabel, true, true) if err != nil { - return "", errors.Wrap(err, "encode token label") + return "", fmt.Errorf("encode token label: %w", err) } uriString += "token=" + tokenLabel } @@ -228,19 +227,19 @@ func (conf *Pkcs11UriConfig) Construct() (string, error) { if len(conf.KeyLabel) != 0 { keyLabel, err = EncodeURIComponent(string(conf.KeyLabel), true, true) if err != nil { - return "", errors.Wrap(err, "encode key label") + return "", fmt.Errorf("encode key label: %w", err) } uriString += ";object=" + keyLabel } modulePath, err = EncodeURIComponent(conf.ModulePath, false, true) if err != nil { - return "", errors.Wrap(err, "encode module path") + return "", fmt.Errorf("encode module path: %w", err) } uriString += "?module-path=" + modulePath if conf.Pin != "" { pinValue, err = EncodeURIComponent(conf.Pin, false, true) if err != nil { - return "", errors.Wrap(err, "encode pin") + return "", fmt.Errorf("encode pin: %w", err) } uriString += "&pin-value=" + pinValue } diff --git a/pkg/cosign/tlog.go b/pkg/cosign/tlog.go index 21970b280e8..18ed437ada0 100644 --- a/pkg/cosign/tlog.go +++ b/pkg/cosign/tlog.go @@ -23,6 +23,7 @@ import ( "crypto/x509" "encoding/base64" "encoding/hex" + "errors" "fmt" "os" "strings" @@ -31,7 +32,6 @@ import ( "github.com/go-openapi/swag" "github.com/google/trillian/merkle/logverifier" "github.com/google/trillian/merkle/rfc6962" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" "github.com/sigstore/cosign/pkg/cosign/tuf" "github.com/sigstore/rekor/pkg/generated/client/index" @@ -93,26 +93,26 @@ func GetRekorPubs(ctx context.Context) (map[string]RekorPubKey, error) { fmt.Fprintf(os.Stderr, "**Warning** Using a non-standard public key for Rekor: %s\n", altRekorPub) raw, err := os.ReadFile(altRekorPub) if err != nil { - return nil, errors.Wrap(err, "error reading alternate Rekor public key file") + return nil, fmt.Errorf("error reading alternate Rekor public key file: %w", err) } extra, err := PemToECDSAKey(raw) if err != nil { - return nil, errors.Wrap(err, "error converting PEM to ECDSAKey") + return nil, fmt.Errorf("error converting PEM to ECDSAKey: %w", err) } keyID, err := getLogID(extra) if err != nil { - return nil, errors.Wrap(err, "error generating log ID") + return nil, fmt.Errorf("error generating log ID: %w", err) } publicKeys[keyID] = RekorPubKey{PubKey: extra, Status: tuf.Active} } else { for _, t := range targets { rekorPubKey, err := PemToECDSAKey(t.Target) if err != nil { - return nil, errors.Wrap(err, "pem to ecdsa") + return nil, fmt.Errorf("pem to ecdsa: %w", err) } keyID, err := getLogID(rekorPubKey) if err != nil { - return nil, errors.Wrap(err, "error generating log ID") + return nil, fmt.Errorf("error generating log ID: %w", err) } publicKeys[keyID] = RekorPubKey{PubKey: rekorPubKey, Status: t.Status} } @@ -252,7 +252,7 @@ func proposedEntry(b64Sig string, payload, pubKey []byte) ([]models.ProposedEntr var proposedEntry []models.ProposedEntry signature, err := base64.StdEncoding.DecodeString(b64Sig) if err != nil { - return nil, errors.Wrap(err, "decoding base64 signature") + return nil, fmt.Errorf("decoding base64 signature: %w", err) } // The fact that there's no signature (or empty rather), implies @@ -288,7 +288,7 @@ func FindTlogEntry(ctx context.Context, rekorClient *client.Rekor, b64Sig string searchParams.SetEntry(&searchLogQuery) resp, err := rekorClient.Entries.SearchLogQuery(searchParams) if err != nil { - return nil, errors.Wrap(err, "searching log query") + return nil, fmt.Errorf("searching log query: %w", err) } if len(resp.Payload) == 0 { return nil, errors.New("signature not found in transparency log") @@ -347,7 +347,7 @@ func VerifyTLogEntry(ctx context.Context, rekorClient *client.Rekor, e *models.L // Verify the inclusion proof. v := logverifier.New(rfc6962.DefaultHasher) if err := v.VerifyInclusionProof(*e.Verification.InclusionProof.LogIndex, *e.Verification.InclusionProof.TreeSize, hashes, rootHash, leafHash); err != nil { - return errors.Wrap(err, "verifying inclusion proof") + return fmt.Errorf("verifying inclusion proof: %w", err) } // Verify rekor's signature over the SET. @@ -360,22 +360,22 @@ func VerifyTLogEntry(ctx context.Context, rekorClient *client.Rekor, e *models.L rekorPubKeys, err := GetRekorPubs(ctx) if err != nil { - return errors.Wrap(err, "unable to fetch Rekor public keys from TUF repository") + return fmt.Errorf("unable to fetch Rekor public keys from TUF repository: %w", err) } addRekorPublic := os.Getenv(addRekorPublicKeyFromRekor) if addRekorPublic != "" { pubOK, err := rekorClient.Pubkey.GetPublicKey(nil) if err != nil { - return errors.Wrap(err, "unable to fetch rekor public key from rekor") + return fmt.Errorf("unable to fetch rekor public key from rekor: %w", err) } pubFromAPI, err := PemToECDSAKey([]byte(pubOK.Payload)) if err != nil { - return errors.Wrap(err, "error converting rekor PEM public key from rekor to ECDSAKey") + return fmt.Errorf("error converting rekor PEM public key from rekor to ECDSAKey: %w", err) } keyID, err := getLogID(pubFromAPI) if err != nil { - return errors.Wrap(err, "error generating log ID") + return fmt.Errorf("error generating log ID: %w", err) } rekorPubKeys[keyID] = RekorPubKey{PubKey: pubFromAPI, Status: tuf.Active} } @@ -386,7 +386,7 @@ func VerifyTLogEntry(ctx context.Context, rekorClient *client.Rekor, e *models.L } err = VerifySET(payload, []byte(e.Verification.SignedEntryTimestamp), pubKey.PubKey) if err != nil { - return errors.Wrap(err, "verifying signedEntryTimestamp") + return fmt.Errorf("verifying signedEntryTimestamp: %w", err) } if pubKey.Status != tuf.Active { fmt.Fprintf(os.Stderr, "**Info** Successfully verified Rekor entry using an expired verification key\n") diff --git a/pkg/cosign/tuf/client.go b/pkg/cosign/tuf/client.go index b37902bc3bc..2d115a4ec15 100644 --- a/pkg/cosign/tuf/client.go +++ b/pkg/cosign/tuf/client.go @@ -32,7 +32,6 @@ import ( "strings" "time" - "github.com/pkg/errors" "github.com/theupdateframework/go-tuf/client" tuf_leveldbstore "github.com/theupdateframework/go-tuf/client/leveldbstore" "github.com/theupdateframework/go-tuf/data" @@ -167,7 +166,7 @@ func (t *TUF) getRootStatus() (*RootStatus, error) { // Get metadata expiration trustedMeta, err := t.local.GetMeta() if err != nil { - return nil, errors.Wrap(err, "getting trusted meta") + return nil, fmt.Errorf("getting trusted meta: %w", err) } for role, md := range trustedMeta { mdStatus, err := getMetadataStatus(md) @@ -250,20 +249,20 @@ func initializeTUF(ctx context.Context, embed bool, mirror string, root []byte, trustedMeta, err := t.local.GetMeta() if err != nil { t.Close() - return nil, errors.Wrap(err, "getting trusted meta") + return nil, fmt.Errorf("getting trusted meta: %w", err) } if root == nil { root, err = getRoot(trustedMeta) if err != nil { t.Close() - return nil, errors.Wrap(err, "getting trusted root") + return nil, fmt.Errorf("getting trusted root: %w", err) } } if err := t.client.InitLocal(root); err != nil { t.Close() - return nil, errors.Wrap(err, "unable to initialize client, local cache may be corrupt") + return nil, fmt.Errorf("unable to initialize client, local cache may be corrupt: %w", err) } // We have our local store, whether it was embedded or not! @@ -276,7 +275,7 @@ func initializeTUF(ctx context.Context, embed bool, mirror string, root []byte, // Update when timestamp is out of date. if err := t.updateMetadataAndDownloadTargets(); err != nil { t.Close() - return nil, errors.Wrap(err, "updating local metadata and targets") + return nil, fmt.Errorf("updating local metadata and targets: %w", err) } return t, err @@ -330,7 +329,7 @@ func Initialize(ctx context.Context, mirror string, root []byte) error { return err } if err := os.WriteFile(cachedRemote(rootCacheDir()), b, 0600); err != nil { - return errors.Wrap(err, "storing remote") + return fmt.Errorf("storing remote: %w", err) } return nil } @@ -339,7 +338,7 @@ func (t *TUF) GetTarget(name string) ([]byte, error) { // Get valid target metadata. Does a local verification. validMeta, err := t.client.Target(name) if err != nil { - return nil, errors.Wrap(err, "error verifying local metadata; local cache may be corrupt") + return nil, fmt.Errorf("error verifying local metadata; local cache may be corrupt: %w", err) } targetBytes, err := t.targets.Get(name) @@ -363,7 +362,7 @@ func (t *TUF) GetTarget(name string) ([]byte, error) { func (t *TUF) GetTargetsByMeta(usage UsageKind, fallbacks []string) ([]TargetFile, error) { targets, err := t.client.Targets() if err != nil { - return nil, errors.Wrap(err, "error getting targets") + return nil, fmt.Errorf("error getting targets: %w", err) } var matchedTargets []TargetFile for name, targetMeta := range targets { @@ -380,7 +379,7 @@ func (t *TUF) GetTargetsByMeta(usage UsageKind, fallbacks []string) ([]TargetFil if scm.Sigstore.Usage == usage { target, err := t.GetTarget(name) if err != nil { - return nil, errors.Wrap(err, "error getting target by usage") + return nil, fmt.Errorf("error getting target by usage: %w", err) } matchedTargets = append(matchedTargets, TargetFile{Target: target, Status: scm.Sigstore.Status}) } @@ -404,7 +403,7 @@ func (t *TUF) GetTargetsByMeta(usage UsageKind, fallbacks []string) ([]TargetFil func localStore(cacheRoot string) (client.LocalStore, error) { local, err := tuf_leveldbstore.FileLocalStore(cacheRoot) if err != nil { - return nil, errors.Wrap(err, "creating cached local store") + return nil, fmt.Errorf("creating cached local store: %w", err) } return local, nil } @@ -414,10 +413,10 @@ func embeddedLocalStore() (client.LocalStore, error) { for _, mdFilename := range []string{"root.json", "targets.json", "snapshot.json", "timestamp.json"} { b, err := embeddedRootRepo.ReadFile(path.Join("repository", mdFilename)) if err != nil { - return nil, errors.Wrap(err, "reading embedded file") + return nil, fmt.Errorf("reading embedded file: %w", err) } if err := local.SetMeta(mdFilename, b); err != nil { - return nil, errors.Wrap(err, "setting local meta") + return nil, fmt.Errorf("setting local meta: %w", err) } } return local, nil @@ -491,7 +490,7 @@ func (t *targetDestination) Delete() error { func downloadRemoteTarget(name string, c *client.Client, w io.Writer) error { dest := targetDestination{} if err := c.Download(name, &dest); err != nil { - return errors.Wrap(err, "downloading target") + return fmt.Errorf("downloading target: %w", err) } _, err := io.Copy(w, &dest.buf) return err @@ -575,7 +574,7 @@ type diskCache struct { func (d *diskCache) Set(p string, b []byte) error { if err := os.MkdirAll(d.base, 0700); err != nil { - return errors.Wrap(err, "creating targets dir") + return fmt.Errorf("creating targets dir: %w", err) } fp := filepath.Join(d.base, p) return os.WriteFile(fp, b, 0600) diff --git a/pkg/cosign/tuf/policy.go b/pkg/cosign/tuf/policy.go index f8fd45730a6..d7d277b6611 100644 --- a/pkg/cosign/tuf/policy.go +++ b/pkg/cosign/tuf/policy.go @@ -23,11 +23,11 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" + "fmt" "sync" "time" - "github.com/pkg/errors" - cjson "github.com/secure-systems-lab/go-securesystemslib/cjson" ) @@ -139,14 +139,14 @@ func (r *Root) ValidKey(key *Key, role string) (string, error) { // Returns the key ID or an error if invalid key. fulcioKeyVal, err := GetFulcioKeyVal(key) if err != nil { - return "", errors.Wrap(err, "error parsing signer key") + return "", fmt.Errorf("error parsing signer key: %w", err) } result := "" for keyid, rootKey := range r.Keys { fulcioRootKeyVal, err := GetFulcioKeyVal(rootKey) if err != nil { - return "", errors.Wrap(err, "error parsing root key") + return "", fmt.Errorf("error parsing root key: %w", err) } if fulcioKeyVal.Identity == fulcioRootKeyVal.Identity { if fulcioRootKeyVal.Issuer == "" || fulcioRootKeyVal.Issuer == fulcioKeyVal.Issuer { @@ -189,7 +189,7 @@ func (s *Signed) JSONMarshal(prefix, indent string) ([]byte, error) { func (s *Signed) AddOrUpdateSignature(key *Key, signature Signature) error { root := &Root{} if err := json.Unmarshal(s.Signed, root); err != nil { - return errors.Wrap(err, "unmarshalling root policy") + return fmt.Errorf("unmarshalling root policy: %w", err) } var err error signature.KeyID, err = root.ValidKey(key, "root") diff --git a/pkg/cosign/verifiers.go b/pkg/cosign/verifiers.go index 57641440043..7e9efea202d 100644 --- a/pkg/cosign/verifiers.go +++ b/pkg/cosign/verifiers.go @@ -18,11 +18,11 @@ package cosign import ( "encoding/base64" "encoding/json" + "errors" "fmt" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/in-toto/in-toto-golang/in_toto" - "github.com/pkg/errors" "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/cosign/pkg/oci" diff --git a/pkg/cosign/verify.go b/pkg/cosign/verify.go index b212ef6ba8b..8424e0fbd8b 100644 --- a/pkg/cosign/verify.go +++ b/pkg/cosign/verify.go @@ -25,6 +25,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "regexp" @@ -42,7 +43,6 @@ import ( "github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/pkg/errors" ssldsse "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/cosign/pkg/oci" @@ -164,7 +164,7 @@ func verifyOCIAttestation(_ context.Context, verifier signature.Verifier, att pa func ValidateAndUnpackCert(cert *x509.Certificate, co *CheckOpts) (signature.Verifier, error) { verifier, err := signature.LoadVerifier(cert.PublicKey, crypto.SHA256) if err != nil { - return nil, errors.Wrap(err, "invalid certificate found on signature") + return nil, fmt.Errorf("invalid certificate found on signature: %w", err) } // Now verify the cert, then the signature. @@ -512,7 +512,7 @@ func VerifyImageSignature(ctx context.Context, sig oci.Signature, h v1.Hash, co bundleVerified, err = VerifyBundle(ctx, sig) if err != nil && co.RekorClient == nil { - return false, errors.Wrap(err, "unable to verify bundle") + return false, fmt.Errorf("unable to verify bundle: %w", err) } if !bundleVerified && co.RekorClient != nil { @@ -691,7 +691,7 @@ func verifyImageAttestations(ctx context.Context, atts oci.Signatures, h v1.Hash verified, err := VerifyBundle(ctx, att) if err != nil && co.RekorClient == nil { - return errors.Wrap(err, "unable to verify bundle") + return fmt.Errorf("unable to verify bundle: %w", err) } bundleVerified = bundleVerified || verified @@ -751,7 +751,7 @@ func VerifyBundle(ctx context.Context, sig oci.Signature) (bool, error) { publicKeys, err := GetRekorPubs(ctx) if err != nil { - return false, errors.Wrap(err, "retrieving rekor public key") + return false, fmt.Errorf("retrieving rekor public key: %w", err) } pubKey, ok := publicKeys[bundle.Payload.LogID] @@ -775,17 +775,17 @@ func VerifyBundle(ctx context.Context, sig oci.Signature) (bool, error) { // Verify the cert against the integrated time. // Note that if the caller requires the certificate to be present, it has to ensure that itself. if err := CheckExpiry(cert, time.Unix(bundle.Payload.IntegratedTime, 0)); err != nil { - return false, errors.Wrap(err, "checking expiry on cert") + return false, fmt.Errorf("checking expiry on cert: %w", err) } } payload, err := sig.Payload() if err != nil { - return false, errors.Wrap(err, "reading payload") + return false, fmt.Errorf("reading payload: %w", err) } signature, err := sig.Base64Signature() if err != nil { - return false, errors.Wrap(err, "reading base64signature") + return false, fmt.Errorf("reading base64signature: %w", err) } alg, bundlehash, err := bundleHash(bundle.Payload.Body.(string), signature) @@ -793,7 +793,7 @@ func VerifyBundle(ctx context.Context, sig oci.Signature) (bool, error) { payloadHash := hex.EncodeToString(h[:]) if alg != "sha256" || bundlehash != payloadHash { - return false, errors.Wrap(err, "matching bundle to payload") + return false, fmt.Errorf("matching bundle to payload: %w", err) } return true, nil } @@ -804,7 +804,7 @@ func compareSigs(bundleBody string, sig oci.Signature) error { // we've returned nil (there are several reasons possible here). actualSig, err := sig.Base64Signature() if err != nil { - return errors.Wrap(err, "base64 signature") + return fmt.Errorf("base64 signature: %w", err) } if actualSig == "" { // NB: empty sig means this is an attestation @@ -812,7 +812,7 @@ func compareSigs(bundleBody string, sig oci.Signature) error { } bundleSignature, err := bundleSig(bundleBody) if err != nil { - return errors.Wrap(err, "failed to extract signature from bundle") + return fmt.Errorf("failed to extract signature from bundle: %w", err) } if bundleSignature == "" { return nil @@ -893,7 +893,7 @@ func bundleSig(bundleBody string) (string, error) { bodyDecoded, err := base64.StdEncoding.DecodeString(bundleBody) if err != nil { - return "", errors.Wrap(err, "decoding bundleBody") + return "", fmt.Errorf("decoding bundleBody: %w", err) } // Try Rekord @@ -925,11 +925,11 @@ func bundleSig(bundleBody string) (string, error) { func VerifySET(bundlePayload cbundle.RekorPayload, signature []byte, pub *ecdsa.PublicKey) error { contents, err := json.Marshal(bundlePayload) if err != nil { - return errors.Wrap(err, "marshaling") + return fmt.Errorf("marshaling: %w", err) } canonicalized, err := jsoncanonicalizer.Transform(contents) if err != nil { - return errors.Wrap(err, "canonicalizing") + return fmt.Errorf("canonicalizing: %w", err) } // verify the SET against the public key diff --git a/pkg/cosign/verify_test.go b/pkg/cosign/verify_test.go index 771ff3e0ac0..e82e31b23d8 100644 --- a/pkg/cosign/verify_test.go +++ b/pkg/cosign/verify_test.go @@ -25,6 +25,7 @@ import ( "encoding/base64" "encoding/json" "encoding/pem" + "errors" "io" "net" "net/url" @@ -38,7 +39,6 @@ import ( "github.com/google/certificate-transparency-go/testdata" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/in-toto/in-toto-golang/in_toto" - "github.com/pkg/errors" "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/cosign/internal/pkg/cosign/rekor/mock" "github.com/sigstore/cosign/pkg/cosign/bundle"