From 7025f69d8cab9710c34662fc99a554abf79cc60b Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 03:06:13 +0900 Subject: [PATCH 01/11] cmd/cosign/cli: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- cmd/cosign/cli/attach/attestation.go | 3 +- cmd/cosign/cli/attest.go | 5 +- cmd/cosign/cli/attest/attest.go | 7 ++- cmd/cosign/cli/commands.go | 4 +- cmd/cosign/cli/dockerfile/verify.go | 3 +- cmd/cosign/cli/fulcio/fulcio.go | 9 ++-- .../cli/fulcio/fulcioroots/fulcioroots.go | 11 ++-- .../cli/fulcio/fulcioverifier/ctl/verify.go | 18 +++---- .../fulcio/fulcioverifier/fulcioverifier.go | 4 +- cmd/cosign/cli/generate/generate_key_pair.go | 4 +- cmd/cosign/cli/load.go | 6 +-- cmd/cosign/cli/manifest/verify.go | 4 +- cmd/cosign/cli/options/oidc.go | 3 +- cmd/cosign/cli/pkcs11cli/commands.go | 28 +++++----- cmd/cosign/cli/policy_init.go | 14 ++--- cmd/cosign/cli/publickey/public_key.go | 6 +-- cmd/cosign/cli/save.go | 11 ++-- cmd/cosign/cli/sign.go | 6 +-- cmd/cosign/cli/sign/sign.go | 52 +++++++++---------- cmd/cosign/cli/sign/sign_blob.go | 7 ++- cmd/cosign/cli/signblob.go | 3 +- cmd/cosign/cli/triangulate/triangulate.go | 3 +- cmd/cosign/cli/verify.go | 5 +- cmd/cosign/cli/verify/verify.go | 16 +++--- cmd/cosign/cli/verify/verify_attestation.go | 20 +++---- cmd/cosign/cli/verify/verify_blob.go | 10 ++-- 26 files changed, 127 insertions(+), 135 deletions(-) diff --git a/cmd/cosign/cli/attach/attestation.go b/cmd/cosign/cli/attach/attestation.go index e6f35c7527c..9f928969b4a 100644 --- a/cmd/cosign/cli/attach/attestation.go +++ b/cmd/cosign/cli/attach/attestation.go @@ -21,7 +21,6 @@ import ( "os" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" ssldsse "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/pkg/oci/mutate" @@ -33,7 +32,7 @@ import ( func AttestationCmd(ctx context.Context, regOpts options.RegistryOptions, signedPayload, imageRef string) error { ociremoteOpts, err := regOpts.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } fmt.Fprintln(os.Stderr, "Using payload from:", signedPayload) diff --git a/cmd/cosign/cli/attest.go b/cmd/cosign/cli/attest.go index ffc30866681..13182b93d31 100644 --- a/cmd/cosign/cli/attest.go +++ b/cmd/cosign/cli/attest.go @@ -16,7 +16,8 @@ package cli import ( - "github.com/pkg/errors" + "fmt" + "github.com/spf13/cobra" "github.com/sigstore/cosign/cmd/cosign/cli/attest" @@ -79,7 +80,7 @@ func Attest() *cobra.Command { for _, img := range args { if err := attest.AttestCmd(cmd.Context(), ko, o.Registry, img, o.Cert, o.CertChain, o.NoUpload, o.Predicate.Path, o.Force, o.Predicate.Type, o.Replace, ro.Timeout); err != nil { - return errors.Wrapf(err, "signing %s", img) + return fmt.Errorf("signing %s: %w", img, err) } } return nil diff --git a/cmd/cosign/cli/attest/attest.go b/cmd/cosign/cli/attest/attest.go index 473064b376f..2442f766e6d 100644 --- a/cmd/cosign/cli/attest/attest.go +++ b/cmd/cosign/cli/attest/attest.go @@ -26,7 +26,6 @@ import ( "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/cmd/cosign/cli/rekor" @@ -94,7 +93,7 @@ func AttestCmd(ctx context.Context, ko options.KeyOpts, regOpts options.Registry ref, err := name.ParseReference(imageRef) if err != nil { - return errors.Wrap(err, "parsing reference") + return fmt.Errorf("parsing reference: %w", err) } if timeout != 0 { @@ -119,7 +118,7 @@ func AttestCmd(ctx context.Context, ko options.KeyOpts, regOpts options.Registry sv, err := sign.SignerFromKeyOpts(ctx, certPath, certChainPath, ko) if err != nil { - return errors.Wrap(err, "getting signer") + return fmt.Errorf("getting signer: %w", err) } defer sv.Close() wrapped := dsse.WrapSigner(sv, types.IntotoPayloadType) @@ -148,7 +147,7 @@ func AttestCmd(ctx context.Context, ko options.KeyOpts, regOpts options.Registry } signedPayload, err := wrapped.SignMessage(bytes.NewReader(payload), signatureoptions.WithContext(ctx)) if err != nil { - return errors.Wrap(err, "signing") + return fmt.Errorf("signing: %w", err) } if noUpload { diff --git a/cmd/cosign/cli/commands.go b/cmd/cosign/cli/commands.go index 22ae98a9c7c..0d8765cc09c 100644 --- a/cmd/cosign/cli/commands.go +++ b/cmd/cosign/cli/commands.go @@ -16,10 +16,10 @@ package cli import ( + "fmt" "os" "github.com/google/go-containerregistry/pkg/logs" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" "sigs.k8s.io/release-utils/version" @@ -63,7 +63,7 @@ func New() *cobra.Command { var err error out, err = os.Create(ro.OutputFile) if err != nil { - return errors.Wrapf(err, "Error creating output file %s", ro.OutputFile) + return fmt.Errorf("error creating output file %s: %w", ro.OutputFile, err) } stdout = os.Stdout os.Stdout = out // TODO: don't do this. diff --git a/cmd/cosign/cli/dockerfile/verify.go b/cmd/cosign/cli/dockerfile/verify.go index 72af8be668d..da6cb4412ff 100644 --- a/cmd/cosign/cli/dockerfile/verify.go +++ b/cmd/cosign/cli/dockerfile/verify.go @@ -17,14 +17,13 @@ package dockerfile import ( "bufio" "context" + "errors" "flag" "fmt" "io" "os" "strings" - "github.com/pkg/errors" - "github.com/sigstore/cosign/cmd/cosign/cli/verify" ) diff --git a/cmd/cosign/cli/fulcio/fulcio.go b/cmd/cosign/cli/fulcio/fulcio.go index 689789cc2fe..b0ef7cf5d85 100644 --- a/cmd/cosign/cli/fulcio/fulcio.go +++ b/cmd/cosign/cli/fulcio/fulcio.go @@ -26,7 +26,6 @@ import ( "net/url" "os" - "github.com/pkg/errors" "golang.org/x/term" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio/fulcioroots" @@ -114,7 +113,7 @@ type Signer struct { func NewSigner(ctx context.Context, ko options.KeyOpts) (*Signer, error) { fClient, err := NewClient(ko.FulcioURL) if err != nil { - return nil, errors.Wrap(err, "creating Fulcio client") + return nil, fmt.Errorf("creating Fulcio client: %w", err) } idToken := ko.IDToken @@ -122,13 +121,13 @@ func NewSigner(ctx context.Context, ko options.KeyOpts) (*Signer, error) { if idToken == "" && providers.Enabled(ctx) && !ko.OIDCDisableProviders { idToken, err = providers.Provide(ctx, "sigstore") if err != nil { - return nil, errors.Wrap(err, "fetching ambient OIDC credentials") + return nil, fmt.Errorf("fetching ambient OIDC credentials: %w", err) } } priv, err := cosign.GeneratePrivateKey() if err != nil { - return nil, errors.Wrap(err, "generating cert") + return nil, fmt.Errorf("generating cert: %w", err) } signer, err := signature.LoadECDSASignerVerifier(priv, crypto.SHA256) if err != nil { @@ -151,7 +150,7 @@ func NewSigner(ctx context.Context, ko options.KeyOpts) (*Signer, error) { } Resp, err := GetCert(ctx, priv, idToken, flow, ko.OIDCIssuer, ko.OIDCClientID, ko.OIDCClientSecret, ko.OIDCRedirectURL, fClient) // TODO, use the chain. if err != nil { - return nil, errors.Wrap(err, "retrieving cert") + return nil, fmt.Errorf("retrieving cert: %w", err) } f := &Signer{ diff --git a/cmd/cosign/cli/fulcio/fulcioroots/fulcioroots.go b/cmd/cosign/cli/fulcio/fulcioroots/fulcioroots.go index c0890bd77c2..c77378a9b3a 100644 --- a/cmd/cosign/cli/fulcio/fulcioroots/fulcioroots.go +++ b/cmd/cosign/cli/fulcio/fulcioroots/fulcioroots.go @@ -19,10 +19,11 @@ import ( "bytes" "context" "crypto/x509" + "errors" + "fmt" "os" "sync" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/tuf" "github.com/sigstore/sigstore/pkg/cryptoutils" ) @@ -90,11 +91,11 @@ func initRoots() (*x509.CertPool, *x509.CertPool, error) { if rootEnv != "" { raw, err := os.ReadFile(rootEnv) if err != nil { - return nil, nil, errors.Wrap(err, "error reading root PEM file") + return nil, nil, fmt.Errorf("error reading root PEM file: %w", err) } certs, err := cryptoutils.UnmarshalCertificatesFromPEM(raw) if err != nil { - return nil, nil, errors.Wrap(err, "error unmarshalling certificates") + return nil, nil, fmt.Errorf("error unmarshalling certificates: %w", err) } for _, cert := range certs { // root certificates are self-signed @@ -113,7 +114,7 @@ func initRoots() (*x509.CertPool, *x509.CertPool, error) { } else { tufClient, err := tuf.NewFromEnv(context.Background()) if err != nil { - return nil, nil, errors.Wrap(err, "initializing tuf") + return nil, nil, fmt.Errorf("initializing tuf: %w", err) } defer tufClient.Close() // Retrieve from the embedded or cached TUF root. If expired, a network @@ -128,7 +129,7 @@ func initRoots() (*x509.CertPool, *x509.CertPool, error) { for _, t := range targets { certs, err := cryptoutils.UnmarshalCertificatesFromPEM(t.Target) if err != nil { - return nil, nil, errors.Wrap(err, "error unmarshalling certificates") + return nil, nil, fmt.Errorf("error unmarshalling certificates: %w", err) } for _, cert := range certs { // root certificates are self-signed diff --git a/cmd/cosign/cli/fulcio/fulcioverifier/ctl/verify.go b/cmd/cosign/cli/fulcio/fulcioverifier/ctl/verify.go index c2af470cc21..4031d6ae87a 100644 --- a/cmd/cosign/cli/fulcio/fulcioverifier/ctl/verify.go +++ b/cmd/cosign/cli/fulcio/fulcioverifier/ctl/verify.go @@ -21,13 +21,13 @@ import ( "crypto/x509" "encoding/json" "encoding/pem" + "errors" "fmt" "os" ct "github.com/google/certificate-transparency-go" ctx509 "github.com/google/certificate-transparency-go/x509" "github.com/google/certificate-transparency-go/x509util" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio/fulcioverifier/ctutil" "github.com/sigstore/cosign/pkg/cosign/tuf" @@ -94,7 +94,7 @@ func VerifySCT(ctx context.Context, certPEM, chainPEM, rawSCT []byte) error { } keyID, err := ctutil.GetCTLogID(pub) if err != nil { - return errors.Wrap(err, "error getting CTFE public key hash") + return fmt.Errorf("error getting CTFE public key hash") } pubKeys[keyID] = logIDMetadata{pub, t.Status} } @@ -102,15 +102,15 @@ func VerifySCT(ctx context.Context, certPEM, chainPEM, rawSCT []byte) error { fmt.Fprintf(os.Stderr, "**Warning** Using a non-standard public key for verifying SCT: %s\n", rootEnv) raw, err := os.ReadFile(rootEnv) if err != nil { - return errors.Wrap(err, "error reading alternate public key file") + return fmt.Errorf("error reading alternate public key file") } pubKey, err := getPublicKey(raw) if err != nil { - return errors.Wrap(err, "error parsing alternate public key from the file") + return fmt.Errorf("error parsing alternate public key from the file") } keyID, err := ctutil.GetCTLogID(pubKey) if err != nil { - return errors.Wrap(err, "error getting CTFE public key hash") + return fmt.Errorf("error getting CTFE public key hash") } pubKeys[keyID] = logIDMetadata{pubKey, tuf.Active} } @@ -150,7 +150,7 @@ func VerifySCT(ctx context.Context, certPEM, chainPEM, rawSCT []byte) error { } err := ctutil.VerifySCT(pubKeyMetadata.pubKey, []*ctx509.Certificate{cert, certChain[0]}, sct, true) if err != nil { - return errors.Wrap(err, "error verifying embedded SCT") + return fmt.Errorf("error verifying embedded SCT") } if pubKeyMetadata.status != tuf.Active { fmt.Fprintf(os.Stderr, "**Info** Successfully verified embedded SCT using an expired verification key\n") @@ -162,7 +162,7 @@ func VerifySCT(ctx context.Context, certPEM, chainPEM, rawSCT []byte) error { // check SCT in response header var addChainResp ct.AddChainResponse if err := json.Unmarshal(rawSCT, &addChainResp); err != nil { - return errors.Wrap(err, "unmarshal") + return fmt.Errorf("unmarshal") } sct, err := addChainResp.ToSignedCertificateTimestamp() if err != nil { @@ -174,7 +174,7 @@ func VerifySCT(ctx context.Context, certPEM, chainPEM, rawSCT []byte) error { } err = ctutil.VerifySCT(pubKeyMetadata.pubKey, []*ctx509.Certificate{cert}, sct, false) if err != nil { - return errors.Wrap(err, "error verifying SCT") + return fmt.Errorf("error verifying SCT") } if pubKeyMetadata.status != tuf.Active { fmt.Fprintf(os.Stderr, "**Info** Successfully verified SCT using an expired verification key\n") @@ -217,7 +217,7 @@ func getPublicKey(in []byte) (crypto.PublicKey, error) { // Try using the PKCS1 before giving up. pubKey, err = x509.ParsePKCS1PublicKey(derBytes) if err != nil { - return nil, errors.Wrap(err, "failed to parse CT log public key") + return nil, fmt.Errorf("failed to parse CT log public key: %w", err) } } return pubKey, nil diff --git a/cmd/cosign/cli/fulcio/fulcioverifier/fulcioverifier.go b/cmd/cosign/cli/fulcio/fulcioverifier/fulcioverifier.go index c2905ec12a9..0c8f8ccb7e1 100644 --- a/cmd/cosign/cli/fulcio/fulcioverifier/fulcioverifier.go +++ b/cmd/cosign/cli/fulcio/fulcioverifier/fulcioverifier.go @@ -20,8 +20,6 @@ import ( "fmt" "os" - "github.com/pkg/errors" - "github.com/sigstore/cosign/cmd/cosign/cli/fulcio" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio/fulcioverifier/ctl" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -35,7 +33,7 @@ func NewSigner(ctx context.Context, ko options.KeyOpts) (*fulcio.Signer, error) // verify the sct if err := ctl.VerifySCT(ctx, fs.Cert, fs.Chain, fs.SCT); err != nil { - return nil, errors.Wrap(err, "verifying SCT") + return nil, fmt.Errorf("verifying SCT: %w", err) } fmt.Fprintln(os.Stderr, "Successfully verified SCT...") diff --git a/cmd/cosign/cli/generate/generate_key_pair.go b/cmd/cosign/cli/generate/generate_key_pair.go index fc98a86fbd5..95f373e8b7f 100644 --- a/cmd/cosign/cli/generate/generate_key_pair.go +++ b/cmd/cosign/cli/generate/generate_key_pair.go @@ -18,12 +18,12 @@ package generate import ( "context" "crypto" + "errors" "fmt" "io" "os" "strings" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/git" "github.com/sigstore/cosign/pkg/cosign/git/github" "github.com/sigstore/cosign/pkg/cosign/git/gitlab" @@ -48,7 +48,7 @@ func GenerateKeyPairCmd(ctx context.Context, kmsVal string, args []string) error } pubKey, err := k.CreateKey(ctx, k.DefaultAlgorithm()) if err != nil { - return errors.Wrap(err, "creating key") + return fmt.Errorf("creating key: %w", err) } pemBytes, err := cryptoutils.MarshalPublicKeyToPEM(pubKey) if err != nil { diff --git a/cmd/cosign/cli/load.go b/cmd/cosign/cli/load.go index 1a2a6db7117..26c8b1ecb42 100644 --- a/cmd/cosign/cli/load.go +++ b/cmd/cosign/cli/load.go @@ -17,9 +17,9 @@ package cli import ( "context" + "fmt" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/pkg/oci/layout" "github.com/sigstore/cosign/pkg/oci/remote" @@ -47,13 +47,13 @@ func Load() *cobra.Command { func LoadCmd(ctx context.Context, opts options.LoadOptions, imageRef string) error { ref, err := name.ParseReference(imageRef) if err != nil { - return errors.Wrapf(err, "parsing image name %s", imageRef) + return fmt.Errorf("parsing image name %s: %w", imageRef, err) } // get the signed image from disk sii, err := layout.SignedImageIndex(opts.Directory) if err != nil { - return errors.Wrap(err, "signed image index") + return fmt.Errorf("signed image index: %w", err) } return remote.WriteSignedImageIndexImages(ref, sii) } diff --git a/cmd/cosign/cli/manifest/verify.go b/cmd/cosign/cli/manifest/verify.go index ad086a8d0f5..3129918cdea 100644 --- a/cmd/cosign/cli/manifest/verify.go +++ b/cmd/cosign/cli/manifest/verify.go @@ -17,6 +17,7 @@ package manifest import ( "bytes" "context" + "errors" "flag" "fmt" "io" @@ -24,7 +25,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" "k8s.io/apimachinery/pkg/util/yaml" "github.com/sigstore/cosign/cmd/cosign/cli/verify" @@ -45,7 +45,7 @@ func (c *VerifyManifestCommand) Exec(ctx context.Context, args []string) error { err := isExtensionAllowed(manifestPath) if err != nil { - return errors.Wrap(err, "check if extension is valid") + return fmt.Errorf("check if extension is valid: %w", err) } manifest, err := os.ReadFile(manifestPath) if err != nil { diff --git a/cmd/cosign/cli/options/oidc.go b/cmd/cosign/cli/options/oidc.go index 848706487f5..b5c87fb2158 100644 --- a/cmd/cosign/cli/options/oidc.go +++ b/cmd/cosign/cli/options/oidc.go @@ -21,7 +21,6 @@ import ( "strings" "unicode/utf8" - "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -40,7 +39,7 @@ func (o *OIDCOptions) ClientSecret() (string, error) { if o.clientSecretFile != "" { clientSecretBytes, err := os.ReadFile(o.clientSecretFile) if err != nil { - return "", errors.Wrap(err, "reading OIDC client secret") + return "", fmt.Errorf("reading OIDC client secret: %w", err) } if !utf8.Valid(clientSecretBytes) { return "", fmt.Errorf("OIDC client secret in file %s not valid utf8", o.clientSecretFile) diff --git a/cmd/cosign/cli/pkcs11cli/commands.go b/cmd/cosign/cli/pkcs11cli/commands.go index 5d478dd828f..76193afd23c 100644 --- a/cmd/cosign/cli/pkcs11cli/commands.go +++ b/cmd/cosign/cli/pkcs11cli/commands.go @@ -20,6 +20,7 @@ package pkcs11cli import ( "context" "encoding/hex" + "errors" "flag" "fmt" "os" @@ -27,7 +28,6 @@ import ( "syscall" "github.com/miekg/pkcs11" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/pkcs11key" "golang.org/x/term" ) @@ -57,7 +57,7 @@ func GetTokens(_ context.Context, modulePath string) ([]Token, error) { } err := p.Initialize() if err != nil { - return nil, errors.Wrap(err, "initialize PKCS11 module") + return nil, fmt.Errorf("initialize PKCS11 module: %w", err) } defer p.Destroy() defer p.Finalize() @@ -65,7 +65,7 @@ func GetTokens(_ context.Context, modulePath string) ([]Token, error) { // Get list of all slots with a token, and get info of each. slots, err := p.GetSlotList(true) if err != nil { - return nil, errors.Wrap(err, "get slot list") + return nil, fmt.Errorf("get slot list: %w", err) } for _, slot := range slots { tokenInfo, err := p.GetTokenInfo(slot) @@ -92,7 +92,7 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) } err := ctx.Initialize() if err != nil { - return nil, errors.Wrap(err, "initialize PKCS11 module") + return nil, fmt.Errorf("initialize PKCS11 module: %w", err) } defer ctx.Destroy() defer ctx.Finalize() @@ -101,7 +101,7 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) var tokenInfo pkcs11.TokenInfo tokenInfo, err = ctx.GetTokenInfo(uint(slotID)) if err != nil { - return nil, errors.Wrap(err, "get token info") + return nil, fmt.Errorf("get token info: %w", err) } // If pin was not given, check COSIGN_PKCS11_PIN environment variable. @@ -117,7 +117,7 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) // nolint:unconvert b, err := term.ReadPassword(int(syscall.Stdin)) if err != nil { - return nil, errors.Wrap(err, "get pin") + return nil, fmt.Errorf("get pin: %w", err) } pin = string(b) } @@ -127,14 +127,14 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) // Open a new session to the token. session, err := ctx.OpenSession(slotID, pkcs11.CKF_SERIAL_SESSION|pkcs11.CKF_RW_SESSION) if err != nil { - return nil, errors.Wrap(err, "open session") + return nil, fmt.Errorf("open session: %w", err) } defer ctx.CloseSession(session) // Login user. err = ctx.Login(session, pkcs11.CKU_USER, pin) if err != nil { - return nil, errors.Wrap(err, "login") + return nil, fmt.Errorf("login: %w", err) } defer ctx.Logout(session) @@ -145,22 +145,22 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY), } if err = ctx.FindObjectsInit(session, findAttributes); err != nil { - return nil, errors.Wrap(err, "init find objects") + return nil, fmt.Errorf("init find objects: %w", err) } newhandles, _, err := ctx.FindObjects(session, maxHandlePerFind) if err != nil { - return nil, errors.Wrap(err, "find objects") + return nil, fmt.Errorf("find objects: %w", err) } for len(newhandles) > 0 { handles = append(handles, newhandles...) newhandles, _, err = ctx.FindObjects(session, maxHandlePerFind) if err != nil { - return nil, errors.Wrap(err, "find objects") + return nil, fmt.Errorf("find objects: %w", err) } } err = ctx.FindObjectsFinal(session) if err != nil { - return nil, errors.Wrap(err, "finalize find objects") + return nil, fmt.Errorf("finalize find objects: %w", err) } // For each private key, get key label and key id then construct uri. @@ -172,7 +172,7 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) pkcs11.NewAttribute(pkcs11.CKA_LABEL, nil), } if attributes, err = ctx.GetAttributeValue(session, handle, attributes); err != nil { - return nil, errors.Wrap(err, "get attributes") + return nil, fmt.Errorf("get attributes: %w", err) } keyID := attributes[0].Value keyLabel := attributes[1].Value @@ -187,7 +187,7 @@ func GetKeysInfo(_ context.Context, modulePath string, slotID uint, pin string) pkcs11Uri := pkcs11key.NewPkcs11UriConfigFromInput(modulePath, &slotIDInt, tokenInfo.Label, keyLabel, keyID, pin) pkcs11UriStr, err := pkcs11Uri.Construct() if err != nil { - return nil, errors.Wrap(err, "construct pkcs11 uri") + return nil, fmt.Errorf("construct pkcs11 uri: %w", err) } if keyLabel != nil && len(keyLabel) != 0 { diff --git a/cmd/cosign/cli/policy_init.go b/cmd/cosign/cli/policy_init.go index 89e100c36d0..a4ab3710891 100644 --- a/cmd/cosign/cli/policy_init.go +++ b/cmd/cosign/cli/policy_init.go @@ -20,6 +20,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/mail" @@ -31,7 +32,6 @@ import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/cmd/cosign/cli/rekor" "github.com/sigstore/cosign/cmd/cosign/cli/sign" @@ -135,7 +135,7 @@ func initPolicy() *cobra.Command { outfile = o.OutFile err = os.WriteFile(o.OutFile, policyFile, 0600) if err != nil { - return errors.Wrapf(err, "error writing to %s", outfile) + return fmt.Errorf("error writing to %s: %w", outfile, err) } } else { tempFile, err := os.CreateTemp("", "root") @@ -226,24 +226,24 @@ func signPolicy() *cobra.Command { result := &bytes.Buffer{} if err := sget.New(imgName+"@"+dgst.String(), "", result).Do(ctx); err != nil { - return errors.Wrap(err, "error getting result") + return fmt.Errorf("error getting result: %w", err) } b, err := io.ReadAll(result) if err != nil { - return errors.Wrap(err, "error reading bytes from root.json") + return fmt.Errorf("error reading bytes from root.json: %w", err) } // Unmarshal policy and verify that Fulcio signer email is in the trusted signed := &tuf.Signed{} if err := json.Unmarshal(b, signed); err != nil { - return errors.Wrap(err, "unmarshalling signed root policy") + return fmt.Errorf("unmarshalling signed root policy: %w", err) } // Create and add signature key := tuf.FulcioVerificationKey(signerEmail, signerIssuer) sig, err := sv.SignMessage(bytes.NewReader(signed.Signed), signatureoptions.WithContext(ctx)) if err != nil { - return errors.Wrap(err, "error occurred while during artifact signing") + return fmt.Errorf("error occurred while during artifact signing): %w", err) } signature := tuf.Signature{ Signature: base64.StdEncoding.EncodeToString(sig), @@ -279,7 +279,7 @@ func signPolicy() *cobra.Command { outfile = o.OutFile err = os.WriteFile(o.OutFile, policyFile, 0600) if err != nil { - return errors.Wrapf(err, "error writing to %s", outfile) + return fmt.Errorf("error writing to %s: %w", outfile, err) } } else { tempFile, err := os.CreateTemp("", "root") diff --git a/cmd/cosign/cli/publickey/public_key.go b/cmd/cosign/cli/publickey/public_key.go index 24e8f94ee08..164b2a81948 100644 --- a/cmd/cosign/cli/publickey/public_key.go +++ b/cmd/cosign/cli/publickey/public_key.go @@ -21,8 +21,6 @@ import ( "io" "os" - "github.com/pkg/errors" - "github.com/sigstore/cosign/pkg/cosign" "github.com/sigstore/cosign/pkg/cosign/pivkey" "github.com/sigstore/cosign/pkg/cosign/pkcs11key" @@ -58,12 +56,12 @@ func GetPublicKey(ctx context.Context, opts Pkopts, writer NamedWriter, pf cosig case opts.Sk: sk, err := pivkey.GetKeyWithSlot(opts.Slot) if err != nil { - return errors.Wrap(err, "opening piv token") + return fmt.Errorf("opening piv token: %w", err) } defer sk.Close() pk, err := sk.Verifier() if err != nil { - return errors.Wrap(err, "initializing piv token verifier") + return fmt.Errorf("initializing piv token verifier: %w", err) } k = pk } diff --git a/cmd/cosign/cli/save.go b/cmd/cosign/cli/save.go index f081393e4f9..e72f8688cd9 100644 --- a/cmd/cosign/cli/save.go +++ b/cmd/cosign/cli/save.go @@ -17,9 +17,10 @@ package cli import ( "context" + "errors" + "fmt" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/cosign/pkg/oci/layout" @@ -48,18 +49,18 @@ func Save() *cobra.Command { func SaveCmd(ctx context.Context, opts options.SaveOptions, imageRef string) error { ref, err := name.ParseReference(imageRef) if err != nil { - return errors.Wrapf(err, "parsing image name %s", imageRef) + return fmt.Errorf("parsing image name %s: %w", imageRef, err) } se, err := ociremote.SignedEntity(ref) if err != nil { - return errors.Wrap(err, "signed entity") + return fmt.Errorf("signed entity: %w", err) } if _, ok := se.(oci.SignedImage); ok { si, err := ociremote.SignedImage(ref) if err != nil { - return errors.Wrap(err, "getting signed image") + return fmt.Errorf("getting signed image: %w", err) } return layout.WriteSignedImage(opts.Directory, si) } @@ -67,7 +68,7 @@ func SaveCmd(ctx context.Context, opts options.SaveOptions, imageRef string) err if _, ok := se.(oci.SignedImageIndex); ok { sii, err := ociremote.SignedImageIndex(ref) if err != nil { - return errors.Wrap(err, "getting signed image index") + return fmt.Errorf("getting signed image index: %w", err) } return layout.WriteSignedImageIndex(opts.Directory, sii) } diff --git a/cmd/cosign/cli/sign.go b/cmd/cosign/cli/sign.go index 620825f7031..f9355b2891c 100644 --- a/cmd/cosign/cli/sign.go +++ b/cmd/cosign/cli/sign.go @@ -17,8 +17,8 @@ package cli import ( "flag" + "fmt" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/sigstore/cosign/cmd/cosign/cli/generate" @@ -104,9 +104,9 @@ func Sign() *cobra.Command { if err := sign.SignCmd(ro, ko, o.Registry, annotationsMap.Annotations, args, o.Cert, o.CertChain, o.Upload, o.OutputSignature, o.OutputCertificate, o.PayloadPath, o.Force, o.Recursive, o.Attachment); err != nil { if o.Attachment == "" { - return errors.Wrapf(err, "signing %v", args) + return fmt.Errorf("signing %v: %w", args, err) } - return errors.Wrapf(err, "signing attachment %s for image %v", o.Attachment, args) + return fmt.Errorf("signing attachment %s for image %v: %w", o.Attachment, args, err) } return nil }, diff --git a/cmd/cosign/cli/sign/sign.go b/cmd/cosign/cli/sign/sign.go index b76a0dbd4e4..43aa11dfae8 100644 --- a/cmd/cosign/cli/sign/sign.go +++ b/cmd/cosign/cli/sign/sign.go @@ -20,6 +20,7 @@ import ( "context" "crypto/x509" "encoding/pem" + "errors" "fmt" "os" "path/filepath" @@ -28,7 +29,6 @@ import ( "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio/fulcioverifier" @@ -113,7 +113,7 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Regist sv, err := SignerFromKeyOpts(ctx, certPath, certChainPath, ko) if err != nil { - return errors.Wrap(err, "getting signer") + return fmt.Errorf("getting signer: %w", err) } defer sv.Close() dd := cremote.NewDupeDetector(sv) @@ -123,7 +123,7 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Regist fmt.Fprintln(os.Stderr, "Using payload from:", payloadPath) staticPayload, err = os.ReadFile(filepath.Clean(payloadPath)) if err != nil { - return errors.Wrap(err, "payload from file") + return fmt.Errorf("payload from file: %w", err) } } @@ -136,11 +136,11 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Regist for _, inputImg := range imgs { ref, err := name.ParseReference(inputImg) if err != nil { - return errors.Wrap(err, "parsing reference") + return fmt.Errorf("parsing reference: %w", err) } opts, err := regOpts.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } ref, err = GetAttachedImageRef(ref, attachment, opts...) if err != nil { @@ -150,35 +150,35 @@ func SignCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Regist if digest, ok := ref.(name.Digest); ok && !recursive { se, err := ociremote.SignedEntity(ref, opts...) if err != nil { - return errors.Wrap(err, "accessing image") + return fmt.Errorf("accessing image: %w", err) } err = signDigest(ctx, digest, staticPayload, ko, regOpts, annotations, upload, outputSignature, outputCertificate, force, recursive, dd, sv, se) if err != nil { - return errors.Wrap(err, "signing digest") + return fmt.Errorf("signing digest: %w", err) } continue } se, err := ociremote.SignedEntity(ref, opts...) if err != nil { - return errors.Wrap(err, "accessing entity") + return fmt.Errorf("accessing entity: %w", err) } if err := walk.SignedEntity(ctx, se, func(ctx context.Context, se oci.SignedEntity) error { // Get the digest for this entity in our walk. d, err := se.(interface{ Digest() (v1.Hash, error) }).Digest() if err != nil { - return errors.Wrap(err, "computing digest") + return fmt.Errorf("computing digest: %w", err) } digest := ref.Context().Digest(d.String()) err = signDigest(ctx, digest, staticPayload, ko, regOpts, annotations, upload, outputSignature, outputCertificate, force, recursive, dd, sv, se) if err != nil { - return errors.Wrap(err, "signing digest") + return fmt.Errorf("signing digest: %w", err) } return ErrDone }); err != nil { - return errors.Wrap(err, "recursively signing") + return fmt.Errorf("recursively signing: %w", err) } } @@ -196,7 +196,7 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti Annotations: annotations, }).MarshalJSON() if err != nil { - return errors.Wrap(err, "payload") + return fmt.Errorf("payload: %w", err) } } @@ -229,18 +229,18 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti outputSignature = fmt.Sprintf("%s-%s", outputSignature, strings.Replace(digest.DigestStr(), ":", "-", 1)) } if err := os.WriteFile(outputSignature, []byte(b64sig), 0600); err != nil { - return errors.Wrap(err, "create signature file") + return fmt.Errorf("create signature file: %w", err) } } if outputCertificate != "" { rekorBytes, err := sv.Bytes(ctx) if err != nil { - return errors.Wrap(err, "create certificate file") + return fmt.Errorf("create certificate file: %w", err) } if err := os.WriteFile(outputCertificate, rekorBytes, 0600); err != nil { - return errors.Wrap(err, "create certificate file") + return fmt.Errorf("create certificate file: %w", err) } // TODO: maybe accept a --b64 flag as well? fmt.Printf("Certificate wrote in the file %s\n", outputCertificate) @@ -259,7 +259,7 @@ func signDigest(ctx context.Context, digest name.Digest, payload []byte, ko opti // Publish the signatures associated with this entity walkOpts, err := regOpts.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } // Check if we are overriding the signatures repository location @@ -315,7 +315,7 @@ func signerFromSecurityKey(keySlot string) (*SignerVerifier, error) { func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef string, passFunc cosign.PassFunc) (*SignerVerifier, error) { k, err := sigs.SignerVerifierFromKeyRef(ctx, keyRef, passFunc) if err != nil { - return nil, errors.Wrap(err, "reading key") + return nil, fmt.Errorf("reading key: %w", err) } certSigner := &SignerVerifier{ SignerVerifier: k, @@ -359,7 +359,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin // Allow both DER and PEM encoding certBytes, err := os.ReadFile(certPath) if err != nil { - return nil, errors.Wrap(err, "read certificate") + return nil, fmt.Errorf("read certificate: %w", err) } // Handle PEM if bytes.HasPrefix(certBytes, []byte("-----")) { @@ -371,18 +371,18 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin } parsedCert, err := x509.ParseCertificate(certBytes) if err != nil { - return nil, errors.Wrap(err, "parse x509 certificate") + return nil, fmt.Errorf("parse x509 certificate: %w", err) } pk, err := k.PublicKey() if err != nil { - return nil, errors.Wrap(err, "get public key") + return nil, fmt.Errorf("get public key: %w", err) } if cryptoutils.EqualKeys(pk, parsedCert.PublicKey) != nil { return nil, errors.New("public key in certificate does not match the provided public key") } pemBytes, err := cryptoutils.MarshalCertificateToPEM(parsedCert) if err != nil { - return nil, errors.Wrap(err, "marshaling certificate to PEM") + return nil, fmt.Errorf("marshaling certificate to PEM: %w", err) } if certSigner.Cert != nil { fmt.Fprintln(os.Stderr, "warning: overriding x509 certificate retrieved from the PKCS11 token") @@ -401,11 +401,11 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin // Accept only PEM encoded certificate chain certChainBytes, err := os.ReadFile(certChainPath) if err != nil { - return nil, errors.Wrap(err, "reading certificate chain from path") + return nil, fmt.Errorf("reading certificate chain from path: %w", err) } certChain, err := cryptoutils.LoadCertificatesFromPEM(bytes.NewReader(certChainBytes)) if err != nil { - return nil, errors.Wrap(err, "loading certificate chain") + return nil, fmt.Errorf("loading certificate chain: %w", err) } if len(certChain) == 0 { return nil, errors.New("no certificates in certificate chain") @@ -418,7 +418,7 @@ func signerFromKeyRef(ctx context.Context, certPath, certChainPath, keyRef strin subPool.AddCert(c) } if _, err := cosign.TrustedCert(leafCert, rootPool, subPool); err != nil { - return nil, errors.Wrap(err, "unable to validate certificate chain") + return nil, fmt.Errorf("unable to validate certificate chain: %w", err) } // Verify SCT if present in the leaf certificate. contains, err := ctl.ContainsSCT(leafCert.Raw) @@ -446,11 +446,11 @@ func keylessSigner(ctx context.Context, ko options.KeyOpts) (*SignerVerifier, er if ko.InsecureSkipFulcioVerify { if k, err = fulcio.NewSigner(ctx, ko); err != nil { - return nil, errors.Wrap(err, "getting key from Fulcio") + return nil, fmt.Errorf("getting key from Fulcio: %w", err) } } else { if k, err = fulcioverifier.NewSigner(ctx, ko); err != nil { - return nil, errors.Wrap(err, "getting key from Fulcio") + return nil, fmt.Errorf("getting key from Fulcio: %w", err) } } diff --git a/cmd/cosign/cli/sign/sign_blob.go b/cmd/cosign/cli/sign/sign_blob.go index 401922b21d1..f623613c78c 100644 --- a/cmd/cosign/cli/sign/sign_blob.go +++ b/cmd/cosign/cli/sign/sign_blob.go @@ -25,7 +25,6 @@ import ( "os" "path/filepath" - "github.com/pkg/errors" cbundle "github.com/sigstore/cosign/pkg/cosign/bundle" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -61,7 +60,7 @@ func SignBlobCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Re sig, err := sv.SignMessage(bytes.NewReader(payload), signatureoptions.WithContext(ctx)) if err != nil { - return nil, errors.Wrap(err, "signing blob") + return nil, fmt.Errorf("signing blob: %w", err) } signedPayload := cosign.LocalSignedPayload{} @@ -101,7 +100,7 @@ func SignBlobCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Re bts = []byte(base64.StdEncoding.EncodeToString(sig)) } if err := os.WriteFile(outputSignature, bts, 0600); err != nil { - return nil, errors.Wrap(err, "create signature file") + return nil, fmt.Errorf("create signature file: %w", err) } fmt.Printf("Signature wrote in the file %s\n", outputSignature) @@ -121,7 +120,7 @@ func SignBlobCmd(ro *options.RootOptions, ko options.KeyOpts, regOpts options.Re bts = []byte(base64.StdEncoding.EncodeToString(rekorBytes)) } if err := os.WriteFile(outputCertificate, bts, 0600); err != nil { - return nil, errors.Wrap(err, "create certificate file") + return nil, fmt.Errorf("create certificate file: %w", err) } fmt.Printf("Certificate wrote in the file %s\n", outputCertificate) } diff --git a/cmd/cosign/cli/signblob.go b/cmd/cosign/cli/signblob.go index 8e80b6f7b12..e6bea6d1924 100644 --- a/cmd/cosign/cli/signblob.go +++ b/cmd/cosign/cli/signblob.go @@ -19,7 +19,6 @@ import ( "fmt" "os" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/generate" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/cmd/cosign/cli/sign" @@ -91,7 +90,7 @@ func SignBlob() *cobra.Command { o.OutputSignature = o.Output } if _, err := sign.SignBlobCmd(ro, ko, o.Registry, blob, o.Base64Output, o.OutputSignature, o.OutputCertificate); err != nil { - return errors.Wrapf(err, "signing %s", blob) + return fmt.Errorf("signing %s: %w", blob, err) } } return nil diff --git a/cmd/cosign/cli/triangulate/triangulate.go b/cmd/cosign/cli/triangulate/triangulate.go index b223d128518..00828575e4e 100644 --- a/cmd/cosign/cli/triangulate/triangulate.go +++ b/cmd/cosign/cli/triangulate/triangulate.go @@ -20,7 +20,6 @@ import ( "fmt" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/options" "github.com/sigstore/cosign/pkg/cosign" ociremote "github.com/sigstore/cosign/pkg/oci/remote" @@ -34,7 +33,7 @@ func MungeCmd(ctx context.Context, regOpts options.RegistryOptions, imageRef str ociremoteOpts, err := regOpts.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } var dstRef name.Tag diff --git a/cmd/cosign/cli/verify.go b/cmd/cosign/cli/verify.go index 6f180e7c549..7a365cfd158 100644 --- a/cmd/cosign/cli/verify.go +++ b/cmd/cosign/cli/verify.go @@ -16,7 +16,8 @@ package cli import ( - "github.com/pkg/errors" + "fmt" + "github.com/spf13/cobra" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -258,7 +259,7 @@ The blob may be specified as a path to a file or - for stdin.`, if err := verify.VerifyBlobCmd(cmd.Context(), ko, o.CertVerify.Cert, o.CertVerify.CertEmail, o.CertVerify.CertOidcIssuer, o.CertVerify.CertChain, o.Signature, args[0], o.CertVerify.EnforceSCT); err != nil { - return errors.Wrapf(err, "verifying blob %s", args) + return fmt.Errorf("verifying blob %s: %w", args, err) } return nil }, diff --git a/cmd/cosign/cli/verify/verify.go b/cmd/cosign/cli/verify/verify.go index 7c2f8f526cb..e7d524c9332 100644 --- a/cmd/cosign/cli/verify/verify.go +++ b/cmd/cosign/cli/verify/verify.go @@ -22,12 +22,12 @@ import ( "crypto/x509" "encoding/base64" "encoding/json" + "errors" "flag" "fmt" "os" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -89,7 +89,7 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { } ociremoteOpts, err := c.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } co := &cosign.CheckOpts{ Annotations: c.Annotations.Annotations, @@ -106,7 +106,7 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { if c.RekorURL != "" { rekorClient, err := rekor.NewClient(c.RekorURL) if err != nil { - return errors.Wrap(err, "creating Rekor client") + return fmt.Errorf("creating Rekor client: %w", err) } co.RekorClient = rekorClient } @@ -122,7 +122,7 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { case keyRef != "": pubKey, err = sigs.PublicKeyFromKeyRefWithHashAlgo(ctx, keyRef, c.HashAlgorithm) if err != nil { - return errors.Wrap(err, "loading public key") + return fmt.Errorf("loading public key: %w", err) } pkcs11Key, ok := pubKey.(*pkcs11key.Key) if ok { @@ -131,12 +131,12 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { case c.Sk: sk, err := pivkey.GetKeyWithSlot(c.Slot) if err != nil { - return errors.Wrap(err, "opening piv token") + return fmt.Errorf("opening piv token: %w", err) } defer sk.Close() pubKey, err = sk.Verifier() if err != nil { - return errors.Wrap(err, "initializing piv token verifier") + return fmt.Errorf("initializing piv token verifier: %w", err) } case certRef != "": cert, err := loadCertFromFileOrURL(c.CertRef) @@ -184,11 +184,11 @@ func (c *VerifyCommand) Exec(ctx context.Context, images []string) (err error) { } else { ref, err := name.ParseReference(img) if err != nil { - return errors.Wrap(err, "parsing reference") + return fmt.Errorf("parsing reference: %w", err) } ref, err = sign.GetAttachedImageRef(ref, c.Attachment, ociremoteOpts...) if err != nil { - return errors.Wrapf(err, "resolving attachment type %s for image %s", c.Attachment, img) + return fmt.Errorf("resolving attachment type %s for image %s: %w", c.Attachment, img, err) } verified, bundleVerified, err := cosign.VerifyImageSignatures(ctx, ref, co) diff --git a/cmd/cosign/cli/verify/verify_attestation.go b/cmd/cosign/cli/verify/verify_attestation.go index c32fc120095..ac645e4e3e6 100644 --- a/cmd/cosign/cli/verify/verify_attestation.go +++ b/cmd/cosign/cli/verify/verify_attestation.go @@ -18,13 +18,13 @@ package verify import ( "context" "crypto" + "errors" "flag" "fmt" "os" "path/filepath" "github.com/google/go-containerregistry/pkg/name" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/pkcs11key" "github.com/sigstore/cosign/pkg/cosign/rego" "github.com/sigstore/cosign/pkg/oci" @@ -72,7 +72,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e ociremoteOpts, err := c.ClientOpts(ctx) if err != nil { - return errors.Wrap(err, "constructing client options") + return fmt.Errorf("constructing client options: %w", err) } co := &cosign.CheckOpts{ RegistryClientOpts: ociremoteOpts, @@ -87,7 +87,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e if c.RekorURL != "" { rekorClient, err := rekor.NewClient(c.RekorURL) if err != nil { - return errors.Wrap(err, "creating Rekor client") + return fmt.Errorf("creating Rekor client: %w", err) } co.RekorClient = rekorClient } @@ -101,7 +101,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e case keyRef != "": co.SigVerifier, err = sigs.PublicKeyFromKeyRef(ctx, keyRef) if err != nil { - return errors.Wrap(err, "loading public key") + return fmt.Errorf("loading public key: %w", err) } pkcs11Key, ok := co.SigVerifier.(*pkcs11key.Key) if ok { @@ -110,17 +110,17 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e case c.Sk: sk, err := pivkey.GetKeyWithSlot(c.Slot) if err != nil { - return errors.Wrap(err, "opening piv token") + return fmt.Errorf("opening piv token: %w", err) } defer sk.Close() co.SigVerifier, err = sk.Verifier() if err != nil { - return errors.Wrap(err, "initializing piv token verifier") + return fmt.Errorf("initializing piv token verifier: %w", err) } case c.CertRef != "": cert, err := loadCertFromFileOrURL(c.CertRef) if err != nil { - return errors.Wrap(err, "loading certificate from reference") + return fmt.Errorf("loading certificate from reference: %w", err) } if c.CertChain == "" { err = cosign.CheckCertificatePolicy(cert, co) @@ -129,7 +129,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e } co.SigVerifier, err = signature.LoadVerifier(cert.PublicKey, crypto.SHA256) if err != nil { - return errors.Wrap(err, "creating certificate verifier") + return fmt.Errorf("creating certificate verifier: %w", err) } } else { // Verify certificate with chain @@ -139,7 +139,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e } co.SigVerifier, err = cosign.ValidateAndUnpackCertWithChain(cert, chain, co) if err != nil { - return errors.Wrap(err, "creating certificate verifier") + return fmt.Errorf("creating certificate verifier: %w", err) } } } @@ -189,7 +189,7 @@ func (c *VerifyAttestationCommand) Exec(ctx context.Context, images []string) (e for _, vp := range verified { payload, err := policy.AttestationToPayloadJSON(ctx, c.PredicateType, vp) if err != nil { - return errors.Wrap(err, "converting to consumable policy validation") + return fmt.Errorf("converting to consumable policy validation: %w", err) } if len(payload) == 0 { // This is not the predicate type we're looking for. diff --git a/cmd/cosign/cli/verify/verify_blob.go b/cmd/cosign/cli/verify/verify_blob.go index ccdc27b3d99..b64119f0705 100644 --- a/cmd/cosign/cli/verify/verify_blob.go +++ b/cmd/cosign/cli/verify/verify_blob.go @@ -24,13 +24,13 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" "time" "github.com/go-openapi/runtime" - "github.com/pkg/errors" ssldsse "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -84,7 +84,7 @@ func VerifyBlobCmd(ctx context.Context, ko options.KeyOpts, certRef, certEmail, case ko.KeyRef != "": verifier, err = sigs.PublicKeyFromKeyRef(ctx, ko.KeyRef) if err != nil { - return errors.Wrap(err, "loading public key") + return fmt.Errorf("loading public key: %w", err) } pkcs11Key, ok := verifier.(*pkcs11key.Key) if ok { @@ -93,12 +93,12 @@ func VerifyBlobCmd(ctx context.Context, ko options.KeyOpts, certRef, certEmail, case ko.Sk: sk, err := pivkey.GetKeyWithSlot(ko.Slot) if err != nil { - return errors.Wrap(err, "opening piv token") + return fmt.Errorf("opening piv token: %w", err) } defer sk.Close() verifier, err = sk.Verifier() if err != nil { - return errors.Wrap(err, "loading public key from token") + return fmt.Errorf("loading public key from token: %w", err) } case certRef != "": cert, err = loadCertFromFileOrURL(certRef) @@ -356,7 +356,7 @@ func verifyRekorBundle(ctx context.Context, bundlePath string, cert *x509.Certif } publicKeys, err := cosign.GetRekorPubs(ctx) if err != nil { - return errors.Wrap(err, "retrieving rekor public key") + return fmt.Errorf("retrieving rekor public key: %w", err) } pubKey, ok := publicKeys[b.Bundle.Payload.LogID] From bdb5b54c587edaadb710104b181a4f2afd7a5c54 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 03:19:20 +0900 Subject: [PATCH 02/11] cmd/sget/cli: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- cmd/sget/cli/commands.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/sget/cli/commands.go b/cmd/sget/cli/commands.go index 8d86df7f1c5..e0be33878ed 100644 --- a/cmd/sget/cli/commands.go +++ b/cmd/sget/cli/commands.go @@ -17,10 +17,10 @@ package cli import ( "bytes" + "errors" "io" "os" - "github.com/pkg/errors" "github.com/spf13/cobra" "sigs.k8s.io/release-utils/version" From 45b4f88160e26a17021c8fc2ef85996300579cba Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 03:20:32 +0900 Subject: [PATCH 03/11] internal/pkg/cosign/ephemeral: remove dependency on pkg/errors Signed-off-by: Koichi Shiraishi --- internal/pkg/cosign/ephemeral/signer.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/pkg/cosign/ephemeral/signer.go b/internal/pkg/cosign/ephemeral/signer.go index 2367213d223..d23c144c2c7 100644 --- a/internal/pkg/cosign/ephemeral/signer.go +++ b/internal/pkg/cosign/ephemeral/signer.go @@ -19,9 +19,9 @@ import ( "context" "crypto" "encoding/base64" + "fmt" "io" - "github.com/pkg/errors" icosign "github.com/sigstore/cosign/internal/pkg/cosign" "github.com/sigstore/cosign/pkg/cosign" "github.com/sigstore/cosign/pkg/oci" @@ -39,7 +39,7 @@ var _ icosign.Signer = ephemeralSigner{} func (ks ephemeralSigner) Sign(ctx context.Context, payload io.Reader) (oci.Signature, crypto.PublicKey, error) { pub, err := ks.signer.PublicKey() if err != nil { - return nil, nil, errors.Wrap(err, "retrieving the static public key somehow failed") + return nil, nil, fmt.Errorf("retrieving the static public key somehow failed: %w", err) } payloadBytes, err := io.ReadAll(payload) @@ -65,11 +65,11 @@ func (ks ephemeralSigner) Sign(ctx context.Context, payload io.Reader) (oci.Sign func NewSigner() (icosign.Signer, error) { priv, err := cosign.GeneratePrivateKey() if err != nil { - return nil, errors.Wrap(err, "generating cert") + return nil, fmt.Errorf("generating cert: %w", err) } s, err := signature.LoadECDSASignerVerifier(priv, crypto.SHA256) if err != nil { - return nil, errors.Wrap(err, "creating a SignerVerifier from ephemeral key") + return nil, fmt.Errorf("creating a SignerVerifier from ephemeral key: %w", err) } return ephemeralSigner{ signer: s, From 24b1428860e67096788a280e1a35c1e6a947cbe1 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:09:30 +0900 Subject: [PATCH 04/11] 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" From 87f6c9040d82dfe3e397bc95f83026206f5d0134 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:13:52 +0900 Subject: [PATCH 05/11] pkg/oci: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- pkg/oci/internal/signature/layer.go | 3 +-- pkg/oci/internal/signature/layer_test.go | 2 +- pkg/oci/layout/write.go | 15 ++++++++------- pkg/oci/mutate/signature.go | 4 ++-- pkg/oci/remote/digest_test.go | 2 +- pkg/oci/remote/options.go | 4 ++-- pkg/oci/remote/options_test.go | 2 +- pkg/oci/remote/remote_test.go | 2 +- pkg/oci/remote/signatures.go | 2 +- pkg/oci/remote/signatures_test.go | 2 +- pkg/oci/remote/write.go | 15 ++++++++------- pkg/oci/signature/layer.go | 3 +-- pkg/oci/signature/layer_test.go | 2 +- 13 files changed, 29 insertions(+), 29 deletions(-) diff --git a/pkg/oci/internal/signature/layer.go b/pkg/oci/internal/signature/layer.go index e042ce1a7db..3a815d3c64f 100644 --- a/pkg/oci/internal/signature/layer.go +++ b/pkg/oci/internal/signature/layer.go @@ -23,7 +23,6 @@ import ( "strings" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/sigstore/pkg/cryptoutils" @@ -112,7 +111,7 @@ func (s *sigLayer) Bundle() (*bundle.RekorBundle, error) { } var b bundle.RekorBundle if err := json.Unmarshal([]byte(val), &b); err != nil { - return nil, errors.Wrap(err, "unmarshaling bundle") + return nil, fmt.Errorf("unmarshaling bundle: %w", err) } return &b, nil } diff --git a/pkg/oci/internal/signature/layer_test.go b/pkg/oci/internal/signature/layer_test.go index a3ea0d80353..929dd975601 100644 --- a/pkg/oci/internal/signature/layer_test.go +++ b/pkg/oci/internal/signature/layer_test.go @@ -18,6 +18,7 @@ package signature import ( "bytes" "encoding/base64" + "errors" "fmt" "testing" @@ -25,7 +26,6 @@ import ( v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/random" "github.com/google/go-containerregistry/pkg/v1/types" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" ) diff --git a/pkg/oci/layout/write.go b/pkg/oci/layout/write.go index ff807665895..2bc1f7f9811 100644 --- a/pkg/oci/layout/write.go +++ b/pkg/oci/layout/write.go @@ -16,10 +16,11 @@ package layout import ( + "fmt" + v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/empty" "github.com/google/go-containerregistry/pkg/v1/layout" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/oci" ) @@ -32,7 +33,7 @@ func WriteSignedImage(path string, si oci.SignedImage) error { } // write the image if err := appendImage(layoutPath, si, imageAnnotation); err != nil { - return errors.Wrap(err, "appending signed image") + return fmt.Errorf("appending signed image: %w", err) } return writeSignedEntity(layoutPath, si) } @@ -48,7 +49,7 @@ func WriteSignedImageIndex(path string, si oci.SignedImageIndex) error { if err := layoutPath.AppendIndex(si, layout.WithAnnotations( map[string]string{kindAnnotation: imageIndexAnnotation}, )); err != nil { - return errors.Wrap(err, "appending signed image index") + return fmt.Errorf("appending signed image index: %w", err) } return writeSignedEntity(layoutPath, si) } @@ -57,22 +58,22 @@ func writeSignedEntity(path layout.Path, se oci.SignedEntity) error { // write the signatures sigs, err := se.Signatures() if err != nil { - return errors.Wrap(err, "getting signatures") + return fmt.Errorf("getting signatures: %w", err) } if !isEmpty(sigs) { if err := appendImage(path, sigs, sigsAnnotation); err != nil { - return errors.Wrap(err, "appending signatures") + return fmt.Errorf("appending signatures: %w", err) } } // write attestations atts, err := se.Attestations() if err != nil { - return errors.Wrap(err, "getting atts") + return fmt.Errorf("getting atts") } if !isEmpty(atts) { if err := appendImage(path, atts, attsAnnotation); err != nil { - return errors.Wrap(err, "appending atts") + return fmt.Errorf("appending atts: %w", err) } } // TODO (priyawadhwa@) and attachments diff --git a/pkg/oci/mutate/signature.go b/pkg/oci/mutate/signature.go index dd2a7ab6808..ed07f4540ff 100644 --- a/pkg/oci/mutate/signature.go +++ b/pkg/oci/mutate/signature.go @@ -18,11 +18,11 @@ import ( "bytes" "crypto/x509" "encoding/json" + "fmt" "io" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/types" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/cosign/pkg/oci/static" @@ -132,7 +132,7 @@ func Signature(original oci.Signature, opts ...SignatureOption) (oci.Signature, so := makeSignatureOption(opts...) oldAnn, err := original.Annotations() if err != nil { - return nil, errors.Wrap(err, "could not get annotations from signature to mutate") + return nil, fmt.Errorf("could not get annotations from signature to mutate: %w", err) } var newAnn map[string]string diff --git a/pkg/oci/remote/digest_test.go b/pkg/oci/remote/digest_test.go index 8dc44a4f495..f89415bdcde 100644 --- a/pkg/oci/remote/digest_test.go +++ b/pkg/oci/remote/digest_test.go @@ -15,12 +15,12 @@ package remote import ( + "errors" "testing" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" ) func TestResolveDigest(t *testing.T) { diff --git a/pkg/oci/remote/options.go b/pkg/oci/remote/options.go index f807eb43264..6cd5a1e3725 100644 --- a/pkg/oci/remote/options.go +++ b/pkg/oci/remote/options.go @@ -16,12 +16,12 @@ package remote import ( + "fmt" "os" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" ) const ( @@ -127,7 +127,7 @@ func WithTargetRepository(repo name.Repository) Option { func GetEnvTargetRepository() (name.Repository, error) { if ro := os.Getenv(RepoOverrideEnvKey); ro != "" { repo, err := name.NewRepository(ro) - return repo, errors.Wrap(err, "parsing $"+RepoOverrideEnvKey) + return repo, fmt.Errorf("parsing $"+RepoOverrideEnvKey+": %w", err) } return name.Repository{}, nil } diff --git a/pkg/oci/remote/options_test.go b/pkg/oci/remote/options_test.go index e2fc4a36abf..cea1b026dc9 100644 --- a/pkg/oci/remote/options_test.go +++ b/pkg/oci/remote/options_test.go @@ -16,6 +16,7 @@ package remote import ( + "errors" "os" "reflect" "testing" @@ -23,7 +24,6 @@ import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" ) func TestOptions(t *testing.T) { diff --git a/pkg/oci/remote/remote_test.go b/pkg/oci/remote/remote_test.go index 885a5e1b8ec..6e855f3dad3 100644 --- a/pkg/oci/remote/remote_test.go +++ b/pkg/oci/remote/remote_test.go @@ -16,12 +16,12 @@ package remote import ( + "errors" "testing" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" ) func TestTagMethods(t *testing.T) { diff --git a/pkg/oci/remote/signatures.go b/pkg/oci/remote/signatures.go index 9f535a8d9ff..172d7f6f5a4 100644 --- a/pkg/oci/remote/signatures.go +++ b/pkg/oci/remote/signatures.go @@ -16,12 +16,12 @@ package remote import ( + "errors" "net/http" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/cosign/pkg/oci/empty" "github.com/sigstore/cosign/pkg/oci/internal/signature" diff --git a/pkg/oci/remote/signatures_test.go b/pkg/oci/remote/signatures_test.go index b8b334c84fc..c90b5777aa1 100644 --- a/pkg/oci/remote/signatures_test.go +++ b/pkg/oci/remote/signatures_test.go @@ -16,6 +16,7 @@ package remote import ( + "errors" "net/http" "testing" @@ -23,7 +24,6 @@ import ( v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/remote/transport" - "github.com/pkg/errors" ) func TestSignaturesErrors(t *testing.T) { diff --git a/pkg/oci/remote/write.go b/pkg/oci/remote/write.go index f089b63ebe4..603ff6eeb50 100644 --- a/pkg/oci/remote/write.go +++ b/pkg/oci/remote/write.go @@ -16,10 +16,11 @@ package remote import ( + "fmt" + "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/oci" ) @@ -34,22 +35,22 @@ func WriteSignedImageIndexImages(ref name.Reference, sii oci.SignedImageIndex, o // write the image index if there is one ii, err := sii.SignedImageIndex(v1.Hash{}) if err != nil { - return errors.Wrap(err, "signed image index") + return fmt.Errorf("signed image index: %w", err) } if ii != nil { if err := remote.WriteIndex(ref, ii, o.ROpt...); err != nil { - return errors.Wrap(err, "writing index") + return fmt.Errorf("writing index: %w", err) } } // write the image if there is one si, err := sii.SignedImage(v1.Hash{}) if err != nil { - return errors.Wrap(err, "signed image") + return fmt.Errorf("signed image: %w", err) } if si != nil { if err := remoteWrite(ref, si, o.ROpt...); err != nil { - return errors.Wrap(err, "remote write") + return fmt.Errorf("remote write: %w", err) } } @@ -61,7 +62,7 @@ func WriteSignedImageIndexImages(ref name.Reference, sii oci.SignedImageIndex, o if sigs != nil { // will be nil if there are no associated signatures sigsTag, err := SignatureTag(ref, opts...) if err != nil { - return errors.Wrap(err, "sigs tag") + return fmt.Errorf("sigs tag: %w", err) } if err := remoteWrite(sigsTag, sigs, o.ROpt...); err != nil { return err @@ -76,7 +77,7 @@ func WriteSignedImageIndexImages(ref name.Reference, sii oci.SignedImageIndex, o if atts != nil { // will be nil if there are no associated attestations attsTag, err := AttestationTag(ref, opts...) if err != nil { - return errors.Wrap(err, "sigs tag") + return fmt.Errorf("sigs tag: %w", err) } return remoteWrite(attsTag, atts, o.ROpt...) } diff --git a/pkg/oci/signature/layer.go b/pkg/oci/signature/layer.go index e042ce1a7db..3a815d3c64f 100644 --- a/pkg/oci/signature/layer.go +++ b/pkg/oci/signature/layer.go @@ -23,7 +23,6 @@ import ( "strings" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/sigstore/pkg/cryptoutils" @@ -112,7 +111,7 @@ func (s *sigLayer) Bundle() (*bundle.RekorBundle, error) { } var b bundle.RekorBundle if err := json.Unmarshal([]byte(val), &b); err != nil { - return nil, errors.Wrap(err, "unmarshaling bundle") + return nil, fmt.Errorf("unmarshaling bundle: %w", err) } return &b, nil } diff --git a/pkg/oci/signature/layer_test.go b/pkg/oci/signature/layer_test.go index a3ea0d80353..929dd975601 100644 --- a/pkg/oci/signature/layer_test.go +++ b/pkg/oci/signature/layer_test.go @@ -18,6 +18,7 @@ package signature import ( "bytes" "encoding/base64" + "errors" "fmt" "testing" @@ -25,7 +26,6 @@ import ( v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/random" "github.com/google/go-containerregistry/pkg/v1/types" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/cosign/bundle" ) From 5088ff00c5028d10afd7423eb1a1353e594af0c2 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:15:02 +0900 Subject: [PATCH 06/11] pkg/policy: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- pkg/policy/attestation.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/pkg/policy/attestation.go b/pkg/policy/attestation.go index 44808201283..0a10bf2a194 100644 --- a/pkg/policy/attestation.go +++ b/pkg/policy/attestation.go @@ -22,7 +22,6 @@ import ( "fmt" "github.com/in-toto/in-toto-golang/in_toto" - "github.com/pkg/errors" "github.com/sigstore/cosign/pkg/oci" "github.com/sigstore/cosign/cmd/cosign/cli/options" @@ -49,19 +48,19 @@ func AttestationToPayloadJSON(ctx context.Context, predicateType string, verifie p, err := verifiedAttestation.Payload() if err != nil { - return nil, errors.Wrap(err, "getting payload") + return nil, fmt.Errorf("getting payload: %w", err) } err = json.Unmarshal(p, &payloadData) if err != nil { - return nil, errors.Wrap(err, "unmarshaling payload data") + return nil, fmt.Errorf("unmarshaling payload data") } var decodedPayload []byte if val, ok := payloadData["payload"]; ok { decodedPayload, err = base64.StdEncoding.DecodeString(val.(string)) if err != nil { - return nil, errors.Wrap(err, "decoding payload") + return nil, fmt.Errorf("decoding payload: %w", err) } } else { return nil, fmt.Errorf("could not find payload in payload data") @@ -85,43 +84,43 @@ func AttestationToPayloadJSON(ctx context.Context, predicateType string, verifie case options.PredicateCustom: payload, err = json.Marshal(statement) if err != nil { - return nil, errors.Wrap(err, "generating CosignStatement") + return nil, fmt.Errorf("generating CosignStatement: %w", err) } case options.PredicateLink: var linkStatement in_toto.LinkStatement if err := json.Unmarshal(decodedPayload, &linkStatement); err != nil { - return nil, errors.Wrap(err, "unmarshaling LinkStatement") + return nil, fmt.Errorf("unmarshaling LinkStatement: %w", err) } payload, err = json.Marshal(linkStatement) if err != nil { - return nil, errors.Wrap(err, "marshaling LinkStatement") + return nil, fmt.Errorf("marshaling LinkStatement: %w", err) } case options.PredicateSLSA: var slsaProvenanceStatement in_toto.ProvenanceStatement if err := json.Unmarshal(decodedPayload, &slsaProvenanceStatement); err != nil { - return nil, errors.Wrap(err, "unmarshaling ProvenanceStatement") + return nil, fmt.Errorf("unmarshaling ProvenanceStatement): %w", err) } payload, err = json.Marshal(slsaProvenanceStatement) if err != nil { - return nil, errors.Wrap(err, "marshaling ProvenanceStatement") + return nil, fmt.Errorf("marshaling ProvenanceStatement: %w", err) } case options.PredicateSPDX: var spdxStatement in_toto.SPDXStatement if err := json.Unmarshal(decodedPayload, &spdxStatement); err != nil { - return nil, errors.Wrap(err, "unmarshaling SPDXStatement") + return nil, fmt.Errorf("unmarshaling SPDXStatement: %w", err) } payload, err = json.Marshal(spdxStatement) if err != nil { - return nil, errors.Wrap(err, "marshaling SPDXStatement") + return nil, fmt.Errorf("marshaling SPDXStatement: %w", err) } case options.PredicateVuln: var vulnStatement attestation.CosignVulnStatement if err := json.Unmarshal(decodedPayload, &vulnStatement); err != nil { - return nil, errors.Wrap(err, "unmarshaling CosignVulnStatement") + return nil, fmt.Errorf("unmarshaling CosignVulnStatement: %w", err) } payload, err = json.Marshal(vulnStatement) if err != nil { - return nil, errors.Wrap(err, "marshaling CosignVulnStatement") + return nil, fmt.Errorf("marshaling CosignVulnStatement: %w", err) } default: return nil, fmt.Errorf("unsupported predicate type: %s", predicateType) From 27b11b5b2907dff207935599932d65f66fb5c856 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:15:25 +0900 Subject: [PATCH 07/11] pkg/sget: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- pkg/sget/sget.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/sget/sget.go b/pkg/sget/sget.go index 2eba346d96f..ff96db1f85c 100644 --- a/pkg/sget/sget.go +++ b/pkg/sget/sget.go @@ -17,12 +17,12 @@ package sget import ( "context" + "errors" "io" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/v1/remote" - "github.com/pkg/errors" "github.com/sigstore/cosign/cmd/cosign/cli/fulcio" "github.com/sigstore/cosign/cmd/cosign/cli/options" From 39ffcaf7ee49ad0e54ebd1f121a169035eb9774a Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:16:17 +0900 Subject: [PATCH 08/11] pkg/signature: remove dependency on deprecated github.com/pkg/errors Signed-off-by: Koichi Shiraishi --- pkg/signature/keys.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/pkg/signature/keys.go b/pkg/signature/keys.go index 610d0c25b3a..90d3e6d1991 100644 --- a/pkg/signature/keys.go +++ b/pkg/signature/keys.go @@ -18,11 +18,10 @@ import ( "context" "crypto" "crypto/x509" + "errors" "fmt" "strings" - "github.com/pkg/errors" - "github.com/sigstore/cosign/pkg/blob" "github.com/sigstore/cosign/pkg/cosign" "github.com/sigstore/cosign/pkg/cosign/git" @@ -77,7 +76,7 @@ func VerifierForKeyRef(ctx context.Context, keyRef string, hashAlgorithm crypto. // 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, hashAlgorithm) @@ -103,7 +102,7 @@ func LoadPublicKeyRaw(raw []byte, hashAlgorithm crypto.Hash) (signature.Verifier // PEM encoded file. ed, err := cosign.PemToECDSAKey(raw) if err != nil { - return nil, errors.Wrap(err, "pem to ecdsa") + return nil, fmt.Errorf("pem to ecdsa: %w", err) } return signature.LoadECDSAVerifier(ed, hashAlgorithm) } @@ -118,19 +117,19 @@ func SignerVerifierFromKeyRef(ctx context.Context, keyRef string, pf cosign.Pass pkcs11UriConfig := pkcs11key.NewPkcs11UriConfig() err := pkcs11UriConfig.Parse(keyRef) if err != nil { - return nil, errors.Wrap(err, "parsing pkcs11 uri") + return nil, fmt.Errorf("parsing pkcs11 uri: %w", err) } // Since we'll be signing, we need to set askForPinIsNeeded to true // because we need access to the private key. sk, err := pkcs11key.GetKeyWithURIConfig(pkcs11UriConfig, true) if err != nil { - return nil, errors.Wrap(err, "opening pkcs11 token key") + return nil, fmt.Errorf("opening pkcs11 token key: %w", err) } sv, err := sk.SignerVerifier() if err != nil { - return nil, errors.Wrap(err, "initializing pkcs11 token signer verifier") + return nil, fmt.Errorf("initializing pkcs11 token signer verifier: %w", err) } return sv, nil @@ -200,19 +199,19 @@ func PublicKeyFromKeyRefWithHashAlgo(ctx context.Context, keyRef string, hashAlg pkcs11UriConfig := pkcs11key.NewPkcs11UriConfig() err := pkcs11UriConfig.Parse(keyRef) if err != nil { - return nil, errors.Wrap(err, "parsing pkcs11 uri") + return nil, fmt.Errorf("parsing pkcs11 uri): %w", err) } // Since we'll be verifying a signature, we do not need to set askForPinIsNeeded to true // because we only need access to the public key. sk, err := pkcs11key.GetKeyWithURIConfig(pkcs11UriConfig, false) if err != nil { - return nil, errors.Wrap(err, "opening pkcs11 token key") + return nil, fmt.Errorf("opening pkcs11 token key: %w", err) } v, err := sk.Verifier() if err != nil { - return nil, errors.Wrap(err, "initializing pkcs11 token verifier") + return nil, fmt.Errorf("initializing pkcs11 token verifier: %w", err) } return v, nil From 706b081b194128bd1e67c0e20daf16691985780c Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 04:16:43 +0900 Subject: [PATCH 09/11] go.mod: go mod tidy Signed-off-by: Koichi Shiraishi --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index bee359b890c..86e51c611db 100644 --- a/go.mod +++ b/go.mod @@ -54,7 +54,6 @@ require ( github.com/oklog/run v1.1.0 github.com/open-policy-agent/opa v0.35.0 github.com/pierrec/lz4 v2.6.1+incompatible - github.com/pkg/errors v0.9.1 github.com/ryanuber/go-glob v1.0.0 github.com/secure-systems-lab/go-securesystemslib v0.3.1 github.com/sigstore/fulcio v0.1.2-0.20220114150912-86a2036f9bc7 @@ -236,6 +235,7 @@ require ( github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/pelletier/go-toml/v2 v2.0.0-beta.8 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_golang v1.12.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect From 3284ba9f04c74a6f655096a9c581000385952fdf Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 05:52:52 +0900 Subject: [PATCH 10/11] pkg/cosign/kubernetes/webhook: remove unnecessary fmt.Sprintf Signed-off-by: Koichi Shiraishi --- pkg/cosign/kubernetes/webhook/validator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/cosign/kubernetes/webhook/validator.go b/pkg/cosign/kubernetes/webhook/validator.go index c2f92c673f5..34efe16fee6 100644 --- a/pkg/cosign/kubernetes/webhook/validator.go +++ b/pkg/cosign/kubernetes/webhook/validator.go @@ -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, fmt.Errorf(fmt.Sprintf("failed to validate public keys with authority %s for %s: %w", name, ref.Name()), err) + return nil, fmt.Errorf("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 From 80ab7efc8751bd1b8c04b14f1e16cbcf4eb1ca43 Mon Sep 17 00:00:00 2001 From: Koichi Shiraishi Date: Tue, 17 May 2022 05:53:15 +0900 Subject: [PATCH 11/11] pkg/oci/remote: should handle error on name.NewRepository Signed-off-by: Koichi Shiraishi --- pkg/oci/remote/options.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/oci/remote/options.go b/pkg/oci/remote/options.go index 6cd5a1e3725..ed0747c28f9 100644 --- a/pkg/oci/remote/options.go +++ b/pkg/oci/remote/options.go @@ -127,7 +127,10 @@ func WithTargetRepository(repo name.Repository) Option { func GetEnvTargetRepository() (name.Repository, error) { if ro := os.Getenv(RepoOverrideEnvKey); ro != "" { repo, err := name.NewRepository(ro) - return repo, fmt.Errorf("parsing $"+RepoOverrideEnvKey+": %w", err) + if err != nil { + return name.Repository{}, fmt.Errorf("parsing $"+RepoOverrideEnvKey+": %w", err) + } + return repo, nil } return name.Repository{}, nil }