From 4dd7fb1c0d035ea28867cd7612af1f8b193d1b5e Mon Sep 17 00:00:00 2001 From: Jason Hall Date: Wed, 18 May 2022 05:29:35 -0400 Subject: [PATCH] Remove use of github.com/pkg/errors (#4696) This package is deprecated, archived, and in maintenance mode, since Go errors support wrapping natively. For #2152. Signed-off-by: Jason Hall --- ast/location/location.go | 2 +- ast/parser.go | 3 +- ast/parser_ext.go | 9 +++-- bundle/bundle.go | 23 ++++++------ bundle/file.go | 11 +++--- bundle/verify.go | 6 ++-- bundle/verify_test.go | 34 +++++++++--------- cmd/sign.go | 3 +- compile/compile.go | 5 ++- download/download.go | 7 ++-- internal/compiler/wasm/wasm.go | 5 ++- internal/jwx/buffer/buffer.go | 11 +++--- internal/jwx/jwa/key_type.go | 12 +++---- internal/jwx/jwa/signature.go | 12 +++---- internal/jwx/jwk/ecdsa.go | 18 +++++----- internal/jwx/jwk/headers.go | 20 +++++------ internal/jwx/jwk/jwk.go | 24 ++++++------- internal/jwx/jwk/rsa.go | 18 +++++----- internal/jwx/jwk/symmetric.go | 4 +-- internal/jwx/jws/headers.go | 20 +++++------ internal/jwx/jws/jws.go | 36 +++++++++---------- internal/jwx/jws/sign/ecdsa.go | 12 +++---- internal/jwx/jws/verify/hmac.go | 10 +++--- internal/runtime/init/init.go | 10 +++--- internal/wasm/encoding/reader.go | 36 +++++++++---------- plugins/status/plugin.go | 3 +- server/server.go | 18 +++++----- .../test-jwtencodesignheadererrors-0380.yaml | 4 +-- test/wasm/cmd/wasm-rego-testgen/main.go | 5 ++- topdown/tokens.go | 9 +++-- 30 files changed, 185 insertions(+), 205 deletions(-) diff --git a/ast/location/location.go b/ast/location/location.go index 13ae6e35d7..5bdce013c8 100644 --- a/ast/location/location.go +++ b/ast/location/location.go @@ -39,7 +39,7 @@ func (loc *Location) Errorf(f string, a ...interface{}) error { // Wrapf returns a new error value that wraps an existing error with a message formatted // to include the location info (e.g., line, column, filename, etc.) func (loc *Location) Wrapf(err error, f string, a ...interface{}) error { - return errors.Wrap(err, loc.Format(f, a...)) + return fmt.Errorf(loc.Format(f, a...)+": %w", err) } // Format returns a formatted string prefixed with the location information. diff --git a/ast/parser.go b/ast/parser.go index 1084341a20..f38f62fa80 100644 --- a/ast/parser.go +++ b/ast/parser.go @@ -16,7 +16,6 @@ import ( "strconv" "strings" - "github.com/pkg/errors" "gopkg.in/yaml.v2" "github.com/open-policy-agent/opa/ast/internal/scanner" @@ -2088,7 +2087,7 @@ func (b *metadataParser) Parse() (*Annotations, error) { case map[interface{}]interface{}: w, err := convertYAMLMapKeyTypes(v, nil) if err != nil { - return nil, errors.Wrap(err, "invalid schema definition") + return nil, fmt.Errorf("invalid schema definition: %w", err) } a.Definition = &w default: diff --git a/ast/parser_ext.go b/ast/parser_ext.go index da2b751589..77ff09b5a6 100644 --- a/ast/parser_ext.go +++ b/ast/parser_ext.go @@ -12,11 +12,10 @@ package ast import ( "bytes" + "errors" "fmt" "strings" "unicode" - - "github.com/pkg/errors" ) // MustParseBody returns a parsed body. @@ -464,7 +463,7 @@ func ParseBodyWithOpts(input string, popts ParserOptions) (Body, error) { func ParseExpr(input string) (*Expr, error) { body, err := ParseBody(input) if err != nil { - return nil, errors.Wrap(err, "failed to parse expression") + return nil, fmt.Errorf("failed to parse expression: %w", err) } if len(body) != 1 { return nil, fmt.Errorf("expected exactly one expression but got: %v", body) @@ -491,7 +490,7 @@ func ParsePackage(input string) (*Package, error) { func ParseTerm(input string) (*Term, error) { body, err := ParseBody(input) if err != nil { - return nil, errors.Wrap(err, "failed to parse term") + return nil, fmt.Errorf("failed to parse term: %w", err) } if len(body) != 1 { return nil, fmt.Errorf("expected exactly one term but got: %v", body) @@ -507,7 +506,7 @@ func ParseTerm(input string) (*Term, error) { func ParseRef(input string) (Ref, error) { term, err := ParseTerm(input) if err != nil { - return nil, errors.Wrap(err, "failed to parse ref") + return nil, fmt.Errorf("failed to parse ref: %w", err) } ref, ok := term.Value.(Ref) if !ok { diff --git a/bundle/bundle.go b/bundle/bundle.go index 41419ee35b..9ec1370099 100644 --- a/bundle/bundle.go +++ b/bundle/bundle.go @@ -11,6 +11,7 @@ import ( "compress/gzip" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "net/url" @@ -18,8 +19,6 @@ import ( "reflect" "strings" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/format" "github.com/open-policy-agent/opa/internal/file/archive" @@ -499,7 +498,7 @@ func (r *Reader) Read() (Bundle, error) { r.metrics.Timer(metrics.RegoDataParse).Stop() if err != nil { - return bundle, errors.Wrapf(err, "bundle load failed on %v", r.fullPath(path)) + return bundle, fmt.Errorf("bundle load failed on %v: %w", r.fullPath(path), err) } if err := insertValue(&bundle, path, value); err != nil { @@ -515,7 +514,7 @@ func (r *Reader) Read() (Bundle, error) { r.metrics.Timer(metrics.RegoDataParse).Stop() if err != nil { - return bundle, errors.Wrapf(err, "bundle load failed on %v", r.fullPath(path)) + return bundle, fmt.Errorf("bundle load failed on %v: %w", r.fullPath(path), err) } if err := insertValue(&bundle, path, value); err != nil { @@ -524,7 +523,7 @@ func (r *Reader) Read() (Bundle, error) { } else if strings.HasSuffix(path, ManifestExt) { if err := util.NewJSONDecoder(&buf).Decode(&bundle.Manifest); err != nil { - return bundle, errors.Wrap(err, "bundle load failed on manifest decode") + return bundle, fmt.Errorf("bundle load failed on manifest decode: %w", err) } } } @@ -577,18 +576,18 @@ func (r *Reader) Read() (Bundle, error) { b, err := json.Marshal(&bundle.Manifest) if err != nil { - return bundle, errors.Wrap(err, "bundle load failed on manifest marshal") + return bundle, fmt.Errorf("bundle load failed on manifest marshal: %w", err) } err = util.UnmarshalJSON(b, &metadata) if err != nil { - return bundle, errors.Wrap(err, "bundle load failed on manifest unmarshal") + return bundle, fmt.Errorf("bundle load failed on manifest unmarshal: %w", err) } // For backwards compatibility always write to the old unnamed manifest path // This will *not* be correct if >1 bundle is in use... if err := bundle.insertData(legacyManifestStoragePath, metadata); err != nil { - return bundle, errors.Wrapf(err, "bundle load failed on %v", legacyRevisionStoragePath) + return bundle, fmt.Errorf("bundle load failed on %v: %w", legacyRevisionStoragePath, err) } } @@ -1209,7 +1208,7 @@ func insertValue(b *Bundle, path string, value interface{}) error { key = strings.Split(dirpath, "/") } if err := b.insertData(key, value); err != nil { - return errors.Wrapf(err, "bundle load failed on %v", path) + return fmt.Errorf("bundle load failed on %v: %w", path, err) } return nil } @@ -1264,7 +1263,7 @@ func preProcessBundle(loader DirectoryLoader, skipVerify bool, sizeLimitBytes in } if err != nil { - return signatures, patch, nil, errors.Wrap(err, "bundle read failed") + return signatures, patch, nil, fmt.Errorf("bundle read failed: %w", err) } // check for the signatures file @@ -1275,7 +1274,7 @@ func preProcessBundle(loader DirectoryLoader, skipVerify bool, sizeLimitBytes in } if err := util.NewJSONDecoder(&buf).Decode(&signatures); err != nil { - return signatures, patch, nil, errors.Wrap(err, "bundle load failed on signatures decode") + return signatures, patch, nil, fmt.Errorf("bundle load failed on signatures decode: %w", err) } } else if !strings.HasSuffix(f.Path(), SignaturesFile) { descriptors = append(descriptors, f) @@ -1292,7 +1291,7 @@ func preProcessBundle(loader DirectoryLoader, skipVerify bool, sizeLimitBytes in } if err := util.NewJSONDecoder(&buf).Decode(&patch); err != nil { - return signatures, patch, nil, errors.Wrap(err, "bundle load failed on patch decode") + return signatures, patch, nil, fmt.Errorf("bundle load failed on patch decode: %w", err) } f.reader = &b diff --git a/bundle/file.go b/bundle/file.go index 040c0af3f8..d5d26c408d 100644 --- a/bundle/file.go +++ b/bundle/file.go @@ -4,14 +4,13 @@ import ( "archive/tar" "bytes" "compress/gzip" + "fmt" "io" "os" "path" "path/filepath" "strings" "sync" - - "github.com/pkg/errors" ) // Descriptor contains information about a file and @@ -43,7 +42,7 @@ func (f *lazyFile) Read(b []byte) (int, error) { if f.file == nil { if f.file, err = os.Open(f.path); err != nil { - return 0, errors.Wrapf(err, "failed to open file %s", f.path) + return 0, fmt.Errorf("failed to open file %s: %w", f.path, err) } } @@ -154,7 +153,7 @@ func (d *dirLoader) NextFile() (*Descriptor, error) { return nil }) if err != nil { - return nil, errors.Wrap(err, "failed to list files") + return nil, fmt.Errorf("failed to list files: %w", err) } } @@ -220,7 +219,7 @@ func (t *tarballLoader) NextFile() (*Descriptor, error) { if t.tr == nil { gr, err := gzip.NewReader(t.r) if err != nil { - return nil, errors.Wrap(err, "archive read failed") + return nil, fmt.Errorf("archive read failed: %w", err) } t.tr = tar.NewReader(gr) @@ -245,7 +244,7 @@ func (t *tarballLoader) NextFile() (*Descriptor, error) { var buf bytes.Buffer if _, err := io.Copy(&buf, t.tr); err != nil { - return nil, errors.Wrapf(err, "failed to copy file %s", header.Name) + return nil, fmt.Errorf("failed to copy file %s: %w", header.Name, err) } f.reader = &buf diff --git a/bundle/verify.go b/bundle/verify.go index f76baf2c8e..e85be835be 100644 --- a/bundle/verify.go +++ b/bundle/verify.go @@ -16,8 +16,6 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jws" "github.com/open-policy-agent/opa/internal/jwx/jws/verify" "github.com/open-policy-agent/opa/util" - - "github.com/pkg/errors" ) const defaultVerifierID = "_default" @@ -92,12 +90,12 @@ func verifyJWTSignature(token string, bvc *VerificationConfig) (*DecodedSignatur var decodedHeader []byte if decodedHeader, err = base64.RawURLEncoding.DecodeString(parts[0]); err != nil { - return nil, errors.Wrap(err, "failed to base64 decode JWT headers") + return nil, fmt.Errorf("failed to base64 decode JWT headers: %w", err) } var hdr jws.StandardHeaders if err := json.Unmarshal(decodedHeader, &hdr); err != nil { - return nil, errors.Wrap(err, "failed to parse JWT headers") + return nil, fmt.Errorf("failed to parse JWT headers: %w", err) } payload, err := base64.RawURLEncoding.DecodeString(parts[1]) diff --git a/bundle/verify_test.go b/bundle/verify_test.go index 4021b4981f..fb4cd02c56 100644 --- a/bundle/verify_test.go +++ b/bundle/verify_test.go @@ -6,7 +6,7 @@ package bundle import ( "bytes" - "fmt" + "errors" "testing" ) @@ -24,20 +24,20 @@ func TestVerifyBundleSignature(t *testing.T) { wantErr bool err error }{ - "no_signatures": {SignaturesConfig{}, nil, true, fmt.Errorf(".signatures.json: missing JWT (expected exactly one)")}, - "multiple_signatures": {SignaturesConfig{Signatures: []string{signedTokenHS256, otherSignedTokenHS256}}, nil, true, fmt.Errorf(".signatures.json: multiple JWTs not supported (expected exactly one)")}, - "invalid_token": {SignaturesConfig{Signatures: []string{badToken}}, nil, true, fmt.Errorf("Failed to split compact serialization")}, + "no_signatures": {SignaturesConfig{}, nil, true, errors.New(".signatures.json: missing JWT (expected exactly one)")}, + "multiple_signatures": {SignaturesConfig{Signatures: []string{signedTokenHS256, otherSignedTokenHS256}}, nil, true, errors.New(".signatures.json: multiple JWTs not supported (expected exactly one)")}, + "invalid_token": {SignaturesConfig{Signatures: []string{badToken}}, nil, true, errors.New("failed to split compact serialization")}, "invalid_token_header_base64": { SignaturesConfig{Signatures: []string{badTokenHeaderBase64}}, NewVerificationConfig(nil, "", "", nil), - true, fmt.Errorf("failed to base64 decode JWT headers: illegal base64 data at input byte 50"), + true, errors.New("failed to base64 decode JWT headers: illegal base64 data at input byte 50"), }, "invalid_token_header_json": { SignaturesConfig{Signatures: []string{badTokenHeaderJSON}}, NewVerificationConfig(nil, "", "", nil), - true, fmt.Errorf("failed to parse JWT headers: unexpected end of JSON input"), + true, errors.New("failed to parse JWT headers: unexpected end of JSON input"), }, - "bad_token_payload": {SignaturesConfig{Signatures: []string{badTokenPayload}}, nil, true, fmt.Errorf("json: cannot unmarshal object into Go struct field DecodedSignature.files of type []bundle.FileInfo")}, + "bad_token_payload": {SignaturesConfig{Signatures: []string{badTokenPayload}}, nil, true, errors.New("json: cannot unmarshal object into Go struct field DecodedSignature.files of type []bundle.FileInfo")}, "valid_token_and_scope": { SignaturesConfig{Signatures: []string{signedTokenHS256}}, NewVerificationConfig(map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "", "write", nil), @@ -46,7 +46,7 @@ func TestVerifyBundleSignature(t *testing.T) { "valid_token_and_scope_mismatch": { SignaturesConfig{Signatures: []string{signedTokenHS256}}, NewVerificationConfig(map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "", "bad_scope", nil), - true, fmt.Errorf("scope mismatch"), + true, errors.New("scope mismatch"), }, } @@ -158,8 +158,8 @@ yQjtQ8mbDOsiLLvh7wIDAQAB== wantErr bool err error }{ - "no_public_key_id": {signedNoKeyIDTokenHS256, map[string]*KeyConfig{}, "", "", true, fmt.Errorf("verification key ID is empty")}, - "actual_public_key_missing": {signedTokenHS256, map[string]*KeyConfig{}, "", "", true, fmt.Errorf("verification key corresponding to ID foo not found")}, + "no_public_key_id": {signedNoKeyIDTokenHS256, map[string]*KeyConfig{}, "", "", true, errors.New("verification key ID is empty")}, + "actual_public_key_missing": {signedTokenHS256, map[string]*KeyConfig{}, "", "", true, errors.New("verification key corresponding to ID foo not found")}, "deprecated_key_id_claim": { signedTokenWithDeprecatedKidClaimHS256, map[string]*KeyConfig{"foo": {Key: "secret", Algorithm: "HS256"}}, "", "write", // check valid keyId in deprecated claim is used @@ -168,7 +168,7 @@ yQjtQ8mbDOsiLLvh7wIDAQAB== "bad_public_key_algorithm": { signedTokenHS256, map[string]*KeyConfig{"foo": {Key: "somekey", Algorithm: "RS007"}}, "", "", - true, fmt.Errorf("unsupported signature algorithm: RS007"), + true, errors.New("unsupported signature algorithm: RS007"), }, "public_key_with_valid_HS256_sign": { signedTokenWithBarKidHS256, @@ -178,7 +178,7 @@ yQjtQ8mbDOsiLLvh7wIDAQAB== "public_key_with_invalid_HS256_sign": { signedTokenHS256, map[string]*KeyConfig{"foo": {Key: "bad_secret", Algorithm: "HS256"}}, "", "", - true, fmt.Errorf("Failed to verify message: failed to match hmac signature"), + true, errors.New("failed to verify message: failed to match hmac signature"), }, "public_key_with_valid_RS256_sign": { signedTokenRS256, @@ -188,12 +188,12 @@ yQjtQ8mbDOsiLLvh7wIDAQAB== "public_key_with_invalid_RS256_sign": { signedTokenRS256, map[string]*KeyConfig{"foo": {Key: publicKeyInvalid, Algorithm: "RS256"}}, "", "", - true, fmt.Errorf("Failed to verify message: crypto/rsa: verification error"), + true, errors.New("failed to verify message: crypto/rsa: verification error"), }, "public_key_with_bad_cert_RS256": { signedTokenRS256, map[string]*KeyConfig{"foo": {Key: publicKeyBad, Algorithm: "RS256"}}, "foo", "", - true, fmt.Errorf("failed to parse PEM block containing the key"), + true, errors.New("failed to parse PEM block containing the key"), }, } @@ -242,7 +242,7 @@ func TestVerifyBundleFile(t *testing.T) { "file_not_found": { [][2]string{{"/.manifest", `{"revision": "quickbrownfaux"}`}}, map[string]FileInfo{}, - true, fmt.Errorf("file /.manifest not included in bundle signature"), + true, errors.New("file /.manifest not included in bundle signature"), }, "bad_hashing_algorithm": { [][2]string{{"/.manifest", `{"revision": "quickbrownfaux"}`}}, @@ -251,7 +251,7 @@ func TestVerifyBundleFile(t *testing.T) { Hash: "e7dc95e14ad6cd75d044c13d52ee3ab1", Algorithm: "MD6", }}, - true, fmt.Errorf("unsupported hashing algorithm: MD6"), + true, errors.New("unsupported hashing algorithm: MD6"), }, "bad_digest": { [][2]string{{"/.manifest", `{"revision": "quickbrownfaux"}`}}, @@ -260,7 +260,7 @@ func TestVerifyBundleFile(t *testing.T) { Hash: "874984d68515ba2439c04dddf5b21574", Algorithm: MD5.String(), }}, - true, fmt.Errorf("/.manifest: digest mismatch (want: 874984d68515ba2439c04dddf5b21574, got: a005c38a509dc2d5a7407b9494efb2ad)"), + true, errors.New("/.manifest: digest mismatch (want: 874984d68515ba2439c04dddf5b21574, got: a005c38a509dc2d5a7407b9494efb2ad)"), }, } diff --git a/cmd/sign.go b/cmd/sign.go index 8b9f3a1ae3..fd1f90ba63 100644 --- a/cmd/sign.go +++ b/cmd/sign.go @@ -15,7 +15,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/open-policy-agent/opa/bundle" @@ -192,7 +191,7 @@ func readBundleFiles(loaders []initload.BundleLoader, h bundle.SignatureHasher) } if err != nil { - return files, errors.Wrap(err, "bundle read failed") + return files, fmt.Errorf("bundle read failed: %w", err) } // skip existing signatures file diff --git a/compile/compile.go b/compile/compile.go index 39713ef54a..e878243214 100644 --- a/compile/compile.go +++ b/compile/compile.go @@ -9,14 +9,13 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "regexp" "sort" "strings" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/bundle" "github.com/open-policy-agent/opa/internal/compiler/wasm" @@ -315,7 +314,7 @@ func (c *Compiler) initBundle() error { load, err := initload.LoadPaths(c.paths, c.filter, c.asBundle, c.bvc, false) if err != nil { - return errors.Wrap(err, "load error") + return fmt.Errorf("load error: %w", err) } if c.asBundle { diff --git a/download/download.go b/download/download.go index f1517d2a10..353ccdeb91 100644 --- a/download/download.go +++ b/download/download.go @@ -18,13 +18,10 @@ import ( "sync" "time" - "github.com/open-policy-agent/opa/plugins" - - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/bundle" "github.com/open-policy-agent/opa/logging" "github.com/open-policy-agent/opa/metrics" + "github.com/open-policy-agent/opa/plugins" "github.com/open-policy-agent/opa/plugins/rest" "github.com/open-policy-agent/opa/util" ) @@ -285,7 +282,7 @@ func (d *Downloader) download(ctx context.Context, m metrics.Metrics) (*download resp, err := d.client.Do(ctx, "GET", d.path) m.Timer(metrics.BundleRequest).Stop() if err != nil { - return nil, errors.Wrap(err, "request failed") + return nil, fmt.Errorf("request failed: %w", err) } defer util.Close(resp) diff --git a/internal/compiler/wasm/wasm.go b/internal/compiler/wasm/wasm.go index c5198f2f76..c6f2cecb90 100644 --- a/internal/compiler/wasm/wasm.go +++ b/internal/compiler/wasm/wasm.go @@ -8,11 +8,10 @@ package wasm import ( "bytes" "encoding/binary" + "errors" "fmt" "io" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/compiler/wasm/opa" "github.com/open-policy-agent/opa/internal/debug" @@ -852,7 +851,7 @@ func (c *Compiler) compileFunc(fn *ir.Func) error { for i := range fn.Blocks { instrs, err := c.compileBlock(fn.Blocks[i]) if err != nil { - return errors.Wrapf(err, "block %d", i) + return fmt.Errorf("block %d: %w", i, err) } if i < len(fn.Blocks)-1 { // not the last block: wrap in `block` instr if withControlInstr(instrs) { // unless we don't need to diff --git a/internal/jwx/buffer/buffer.go b/internal/jwx/buffer/buffer.go index ca4ac419b9..c383ff3b54 100644 --- a/internal/jwx/buffer/buffer.go +++ b/internal/jwx/buffer/buffer.go @@ -7,8 +7,7 @@ import ( "encoding/base64" "encoding/binary" "encoding/json" - - "github.com/pkg/errors" + "fmt" ) // Buffer wraps `[]byte` and provides functions that are often used in @@ -35,7 +34,7 @@ func FromUint(v uint64) Buffer { func FromBase64(v []byte) (Buffer, error) { b := Buffer{} if err := b.Base64Decode(v); err != nil { - return Buffer(nil), errors.Wrap(err, "failed to decode from base64") + return Buffer(nil), fmt.Errorf("failed to decode from base64: %w", err) } return b, nil @@ -85,7 +84,7 @@ func (b *Buffer) Base64Decode(v []byte) error { out := make([]byte, enc.DecodedLen(len(v))) n, err := enc.Decode(out, v) if err != nil { - return errors.Wrap(err, "failed to decode from base64") + return fmt.Errorf("failed to decode from base64: %w", err) } out = out[:n] *b = Buffer(out) @@ -97,7 +96,7 @@ func (b *Buffer) Base64Decode(v []byte) error { func (b Buffer) MarshalJSON() ([]byte, error) { v, err := b.Base64Encode() if err != nil { - return nil, errors.Wrap(err, "failed to encode to base64") + return nil, fmt.Errorf("failed to encode to base64: %w", err) } return json.Marshal(string(v)) } @@ -107,7 +106,7 @@ func (b Buffer) MarshalJSON() ([]byte, error) { func (b *Buffer) UnmarshalJSON(data []byte) error { var x string if err := json.Unmarshal(data, &x); err != nil { - return errors.Wrap(err, "failed to unmarshal JSON") + return fmt.Errorf("failed to unmarshal JSON: %w", err) } return b.Base64Decode([]byte(x)) } diff --git a/internal/jwx/jwa/key_type.go b/internal/jwx/jwa/key_type.go index 076bd39ed7..98f0cc42e2 100644 --- a/internal/jwx/jwa/key_type.go +++ b/internal/jwx/jwa/key_type.go @@ -1,9 +1,9 @@ package jwa import ( + "errors" + "fmt" "strconv" - - "github.com/pkg/errors" ) // KeyType represents the key type ("kty") that are supported @@ -29,11 +29,11 @@ func (keyType *KeyType) Accept(value interface{}) error { case KeyType: tmp = x default: - return errors.Errorf(`invalid type for jwa.KeyType: %T`, value) + return fmt.Errorf("invalid type for jwa.KeyType: %T", value) } _, ok := keyTypeAlg[tmp.String()] if !ok { - return errors.Errorf("Unknown Key Type algorithm") + return errors.New("unknown Key Type algorithm") } *keyType = tmp @@ -53,14 +53,14 @@ func (keyType *KeyType) UnmarshalJSON(data []byte) error { var err error quoted, err = strconv.Unquote(string(data)) if err != nil { - return errors.Wrap(err, "Failed to process signature algorithm") + return fmt.Errorf("failed to process signature algorithm: %w", err) } } else { quoted = string(data) } _, ok := keyTypeAlg[quoted] if !ok { - return errors.Errorf("Unknown signature algorithm") + return errors.New("unknown signature algorithm") } *keyType = KeyType(quoted) return nil diff --git a/internal/jwx/jwa/signature.go b/internal/jwx/jwa/signature.go index a0988ecabf..4329408db4 100644 --- a/internal/jwx/jwa/signature.go +++ b/internal/jwx/jwa/signature.go @@ -1,9 +1,9 @@ package jwa import ( + "errors" + "fmt" "strconv" - - "github.com/pkg/errors" ) // SignatureAlgorithm represents the various signature algorithms as described in https://tools.ietf.org/html/rfc7518#section-3.1 @@ -39,11 +39,11 @@ func (signature *SignatureAlgorithm) Accept(value interface{}) error { case SignatureAlgorithm: tmp = x default: - return errors.Errorf(`invalid type for jwa.SignatureAlgorithm: %T`, value) + return fmt.Errorf("invalid type for jwa.SignatureAlgorithm: %T", value) } _, ok := signatureAlg[tmp.String()] if !ok { - return errors.Errorf("Unknown signature algorithm") + return errors.New("unknown signature algorithm") } *signature = tmp return nil @@ -62,14 +62,14 @@ func (signature *SignatureAlgorithm) UnmarshalJSON(data []byte) error { var err error quoted, err = strconv.Unquote(string(data)) if err != nil { - return errors.Wrap(err, "Failed to process signature algorithm") + return fmt.Errorf("failed to process signature algorithm: %w", err) } } else { quoted = string(data) } _, ok := signatureAlg[quoted] if !ok { - return errors.Errorf("Unknown signature algorithm") + return errors.New("unknown signature algorithm") } *signature = SignatureAlgorithm(quoted) return nil diff --git a/internal/jwx/jwk/ecdsa.go b/internal/jwx/jwk/ecdsa.go index 30bee46b4b..b46689f037 100644 --- a/internal/jwx/jwk/ecdsa.go +++ b/internal/jwx/jwk/ecdsa.go @@ -3,10 +3,10 @@ package jwk import ( "crypto/ecdsa" "crypto/elliptic" + "errors" + "fmt" "math/big" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -15,7 +15,7 @@ func newECDSAPublicKey(key *ecdsa.PublicKey) (*ECDSAPublicKey, error) { var hdr StandardHeaders err := hdr.Set(KeyTypeKey, jwa.EC) if err != nil { - return nil, errors.Wrapf(err, "Failed to set Key Type") + return nil, fmt.Errorf("failed to set Key Type: %w", err) } return &ECDSAPublicKey{ @@ -29,7 +29,7 @@ func newECDSAPrivateKey(key *ecdsa.PrivateKey) (*ECDSAPrivateKey, error) { var hdr StandardHeaders err := hdr.Set(KeyTypeKey, jwa.EC) if err != nil { - return nil, errors.Wrapf(err, "Failed to set Key Type") + return nil, fmt.Errorf("failed to set Key Type: %w", err) } return &ECDSAPrivateKey{ @@ -54,7 +54,7 @@ func (k *ECDSAPublicKey) GenerateKey(keyJSON *RawKeyJSON) error { var x, y big.Int if keyJSON.X == nil || keyJSON.Y == nil || keyJSON.Crv == "" { - return errors.Errorf("Missing mandatory key parameters X, Y or Crv") + return errors.New("missing mandatory key parameters X, Y or Crv") } x.SetBytes(keyJSON.X.Bytes()) @@ -69,7 +69,7 @@ func (k *ECDSAPublicKey) GenerateKey(keyJSON *RawKeyJSON) error { case jwa.P521: curve = elliptic.P521() default: - return errors.Errorf(`invalid curve name %s`, keyJSON.Crv) + return fmt.Errorf("invalid curve name %s", keyJSON.Crv) } *k = ECDSAPublicKey{ @@ -87,12 +87,12 @@ func (k *ECDSAPublicKey) GenerateKey(keyJSON *RawKeyJSON) error { func (k *ECDSAPrivateKey) GenerateKey(keyJSON *RawKeyJSON) error { if keyJSON.D == nil { - return errors.Errorf("Missing mandatory key parameter D") + return errors.New("missing mandatory key parameter D") } eCDSAPublicKey := &ECDSAPublicKey{} err := eCDSAPublicKey.GenerateKey(keyJSON) if err != nil { - return errors.Wrap(err, `failed to generate public key`) + return fmt.Errorf("failed to generate public key: %w", err) } dBytes := keyJSON.D.Bytes() // The length of this octet string MUST be ceiling(log-base-2(n)/8) @@ -106,7 +106,7 @@ func (k *ECDSAPrivateKey) GenerateKey(keyJSON *RawKeyJSON) error { n := eCDSAPublicKey.key.Params().N octetLength := (new(big.Int).Sub(n, big.NewInt(1)).BitLen() + 7) >> 3 if octetLength-len(dBytes) != 0 { - return errors.Errorf("Failed to generate private key. Incorrect D value") + return errors.New("failed to generate private key. Incorrect D value") } privateKey := &ecdsa.PrivateKey{ PublicKey: *eCDSAPublicKey.key, diff --git a/internal/jwx/jwk/headers.go b/internal/jwx/jwk/headers.go index cf700ee864..b0fd51e901 100644 --- a/internal/jwx/jwk/headers.go +++ b/internal/jwx/jwk/headers.go @@ -1,7 +1,7 @@ package jwk import ( - "github.com/pkg/errors" + "fmt" "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -122,7 +122,7 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { case AlgorithmKey: var acceptor jwa.SignatureAlgorithm if err := acceptor.Accept(value); err != nil { - return errors.Wrapf(err, `invalid value for %s key`, AlgorithmKey) + return fmt.Errorf("invalid value for %s key: %w", AlgorithmKey, err) } h.Algorithm = &acceptor return nil @@ -131,15 +131,15 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { h.KeyID = v return nil } - return errors.Errorf("invalid value for %s key: %T", KeyIDKey, value) + return fmt.Errorf("invalid value for %s key: %T", KeyIDKey, value) case KeyOpsKey: if err := h.KeyOps.Accept(value); err != nil { - return errors.Wrapf(err, "invalid value for %s key", KeyOpsKey) + return fmt.Errorf("invalid value for %s key: %w", KeyOpsKey, err) } return nil case KeyTypeKey: if err := h.KeyType.Accept(value); err != nil { - return errors.Wrapf(err, "invalid value for %s key", KeyTypeKey) + return fmt.Errorf("invalid value for %s key: %w", KeyTypeKey, err) } return nil case KeyUsageKey: @@ -147,15 +147,15 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { h.KeyUsage = v return nil } - return errors.Errorf("invalid value for %s key: %T", KeyUsageKey, value) + return fmt.Errorf("invalid value for %s key: %T", KeyUsageKey, value) case PrivateParamsKey: if v, ok := value.(map[string]interface{}); ok { h.PrivateParams = v return nil } - return errors.Errorf("invalid value for %s key: %T", PrivateParamsKey, value) + return fmt.Errorf("invalid value for %s key: %T", PrivateParamsKey, value) default: - return errors.Errorf(`invalid key: %s`, name) + return fmt.Errorf("invalid key: %s", name) } } @@ -164,14 +164,14 @@ func (h StandardHeaders) Walk(f func(string, interface{}) error) error { for _, key := range []string{AlgorithmKey, KeyIDKey, KeyOpsKey, KeyTypeKey, KeyUsageKey, PrivateParamsKey} { if v, ok := h.Get(key); ok { if err := f(key, v); err != nil { - return errors.Wrapf(err, `walk function returned error for %s`, key) + return fmt.Errorf("walk function returned error for %s: %w", key, err) } } } for k, v := range h.PrivateParams { if err := f(k, v); err != nil { - return errors.Wrapf(err, `walk function returned error for %s`, k) + return fmt.Errorf("walk function returned error for %s: %w", k, err) } } return nil diff --git a/internal/jwx/jwk/jwk.go b/internal/jwx/jwk/jwk.go index 22ccf8dfc6..d68c814c65 100644 --- a/internal/jwx/jwk/jwk.go +++ b/internal/jwx/jwk/jwk.go @@ -5,8 +5,8 @@ import ( "crypto/ecdsa" "crypto/rsa" "encoding/json" - - "github.com/pkg/errors" + "errors" + "fmt" "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -17,7 +17,7 @@ import ( // public key cannot be deduced, an error is returned func GetPublicKey(key interface{}) (interface{}, error) { if key == nil { - return nil, errors.New(`jwk.New requires a non-nil key`) + return nil, errors.New("jwk.New requires a non-nil key") } switch v := key.(type) { @@ -32,7 +32,7 @@ func GetPublicKey(key interface{}) (interface{}, error) { case []byte: return v, nil default: - return nil, errors.Errorf(`invalid key type %T`, key) + return nil, fmt.Errorf("invalid key type %T", key) } } @@ -54,7 +54,7 @@ func GetKeyTypeFromKey(key interface{}) jwa.KeyType { // New creates a jwk.Key from the given key. func New(key interface{}) (Key, error) { if key == nil { - return nil, errors.New(`jwk.New requires a non-nil key`) + return nil, errors.New("jwk.New requires a non-nil key") } switch v := key.(type) { @@ -69,7 +69,7 @@ func New(key interface{}) (Key, error) { case []byte: return newSymmetricKey(v) default: - return nil, errors.Errorf(`invalid key type %T`, key) + return nil, fmt.Errorf("invalid key type %T", key) } } @@ -80,7 +80,7 @@ func parse(jwkSrc string) (*Set, error) { rawKeySetJSON := &RawKeySetJSON{} err := json.Unmarshal([]byte(jwkSrc), rawKeySetJSON) if err != nil { - return nil, errors.Wrap(err, "Failed to unmarshal JWK Set") + return nil, fmt.Errorf("failed to unmarshal JWK Set: %w", err) } if len(rawKeySetJSON.Keys) == 0 { @@ -88,11 +88,11 @@ func parse(jwkSrc string) (*Set, error) { rawKeyJSON := &RawKeyJSON{} err := json.Unmarshal([]byte(jwkSrc), rawKeyJSON) if err != nil { - return nil, errors.Wrap(err, "Failed to unmarshal JWK") + return nil, fmt.Errorf("failed to unmarshal JWK: %w", err) } jwkKey, err = rawKeyJSON.GenerateKey() if err != nil { - return nil, errors.Wrap(err, "Failed to generate key") + return nil, fmt.Errorf("failed to generate key: %w", err) } // Add to set jwkKeySet.Keys = append(jwkKeySet.Keys, jwkKey) @@ -101,7 +101,7 @@ func parse(jwkSrc string) (*Set, error) { rawKeyJSON := rawKeySetJSON.Keys[i] jwkKey, err = rawKeyJSON.GenerateKey() if err != nil { - return nil, errors.Wrap(err, "Failed to generate key: %s") + return nil, fmt.Errorf("failed to generate key: %w", err) } jwkKeySet.Keys = append(jwkKeySet.Keys, jwkKey) } @@ -140,11 +140,11 @@ func (r *RawKeyJSON) GenerateKey() (Key, error) { case jwa.OctetSeq: key = &SymmetricKey{} default: - return nil, errors.Errorf(`Unrecognized key type`) + return nil, errors.New("unrecognized key type") } err := key.GenerateKey(r) if err != nil { - return nil, errors.Wrap(err, "Failed to generate key from JWK") + return nil, fmt.Errorf("failed to generate key from JWK: %w", err) } return key, nil } diff --git a/internal/jwx/jwk/rsa.go b/internal/jwx/jwk/rsa.go index 1a5cba47b6..11b8e3b56b 100644 --- a/internal/jwx/jwk/rsa.go +++ b/internal/jwx/jwk/rsa.go @@ -3,10 +3,10 @@ package jwk import ( "crypto/rsa" "encoding/binary" + "errors" + "fmt" "math/big" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -15,7 +15,7 @@ func newRSAPublicKey(key *rsa.PublicKey) (*RSAPublicKey, error) { var hdr StandardHeaders err := hdr.Set(KeyTypeKey, jwa.RSA) if err != nil { - return nil, errors.Wrapf(err, "Failed to set Key Type") + return nil, fmt.Errorf("failed to set Key Type: %w", err) } return &RSAPublicKey{ StandardHeaders: &hdr, @@ -28,7 +28,7 @@ func newRSAPrivateKey(key *rsa.PrivateKey) (*RSAPrivateKey, error) { var hdr StandardHeaders err := hdr.Set(KeyTypeKey, jwa.RSA) if err != nil { - return nil, errors.Wrapf(err, "Failed to set Key Type") + return nil, fmt.Errorf("failed to set Key Type: %w", err) } var algoParams jwa.AlgorithmParameters @@ -67,7 +67,7 @@ func newRSAPrivateKey(key *rsa.PrivateKey) (*RSAPrivateKey, error) { // Materialize returns the standard RSA Public Key representation stored in the internal representation func (k *RSAPublicKey) Materialize() (interface{}, error) { if k.key == nil { - return nil, errors.New(`key has no rsa.PublicKey associated with it`) + return nil, errors.New("key has no rsa.PublicKey associated with it") } return k.key, nil } @@ -75,7 +75,7 @@ func (k *RSAPublicKey) Materialize() (interface{}, error) { // Materialize returns the standard RSA Private Key representation stored in the internal representation func (k *RSAPrivateKey) Materialize() (interface{}, error) { if k.key == nil { - return nil, errors.New(`key has no rsa.PrivateKey associated with it`) + return nil, errors.New("key has no rsa.PrivateKey associated with it") } return k.key, nil } @@ -84,7 +84,7 @@ func (k *RSAPrivateKey) Materialize() (interface{}, error) { func (k *RSAPublicKey) GenerateKey(keyJSON *RawKeyJSON) error { if keyJSON.N == nil || keyJSON.E == nil { - return errors.Errorf("Missing mandatory key parameters N or E") + return errors.New("missing mandatory key parameters N or E") } rsaPublicKey := &rsa.PublicKey{ N: (&big.Int{}).SetBytes(keyJSON.N.Bytes()), @@ -101,11 +101,11 @@ func (k *RSAPrivateKey) GenerateKey(keyJSON *RawKeyJSON) error { rsaPublicKey := &RSAPublicKey{} err := rsaPublicKey.GenerateKey(keyJSON) if err != nil { - return errors.Wrap(err, "failed to generate public key") + return fmt.Errorf("failed to generate public key: %w", err) } if keyJSON.D == nil || keyJSON.P == nil || keyJSON.Q == nil { - return errors.Errorf("Missing mandatory key parameters D, P or Q") + return errors.New("missing mandatory key parameters D, P or Q") } privateKey := &rsa.PrivateKey{ PublicKey: *rsaPublicKey.key, diff --git a/internal/jwx/jwk/symmetric.go b/internal/jwx/jwk/symmetric.go index 8a07361556..e0cc0751e6 100644 --- a/internal/jwx/jwk/symmetric.go +++ b/internal/jwx/jwk/symmetric.go @@ -1,7 +1,7 @@ package jwk import ( - "github.com/pkg/errors" + "fmt" "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -11,7 +11,7 @@ func newSymmetricKey(key []byte) (*SymmetricKey, error) { err := hdr.Set(KeyTypeKey, jwa.OctetSeq) if err != nil { - return nil, errors.Wrapf(err, "Failed to set Key Type") + return nil, fmt.Errorf("failed to set Key Type: %w", err) } return &SymmetricKey{ StandardHeaders: &hdr, diff --git a/internal/jwx/jws/headers.go b/internal/jwx/jws/headers.go index 045e38fa1e..0c8b355087 100644 --- a/internal/jwx/jws/headers.go +++ b/internal/jwx/jws/headers.go @@ -1,7 +1,7 @@ package jws import ( - "github.com/pkg/errors" + "fmt" "github.com/open-policy-agent/opa/internal/jwx/jwa" ) @@ -103,7 +103,7 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { switch name { case AlgorithmKey: if err := h.Algorithm.Accept(value); err != nil { - return errors.Wrapf(err, `invalid value for %s key`, AlgorithmKey) + return fmt.Errorf("invalid value for %s key: %w", AlgorithmKey, err) } return nil case ContentTypeKey: @@ -111,44 +111,44 @@ func (h *StandardHeaders) Set(name string, value interface{}) error { h.ContentType = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, ContentTypeKey, value) + return fmt.Errorf("invalid value for %s key: %T", ContentTypeKey, value) case CriticalKey: if v, ok := value.([]string); ok { h.Critical = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, CriticalKey, value) + return fmt.Errorf("invalid value for %s key: %T", CriticalKey, value) case JWKKey: if v, ok := value.(string); ok { h.JWK = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, JWKKey, value) + return fmt.Errorf("invalid value for %s key: %T", JWKKey, value) case JWKSetURLKey: if v, ok := value.(string); ok { h.JWKSetURL = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, JWKSetURLKey, value) + return fmt.Errorf("invalid value for %s key: %T", JWKSetURLKey, value) case KeyIDKey: if v, ok := value.(string); ok { h.KeyID = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, KeyIDKey, value) + return fmt.Errorf("invalid value for %s key: %T", KeyIDKey, value) case PrivateParamsKey: if v, ok := value.(map[string]interface{}); ok { h.PrivateParams = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, PrivateParamsKey, value) + return fmt.Errorf("invalid value for %s key: %T", PrivateParamsKey, value) case TypeKey: if v, ok := value.(string); ok { h.Type = v return nil } - return errors.Errorf(`invalid value for %s key: %T`, TypeKey, value) + return fmt.Errorf("invalid value for %s key: %T", TypeKey, value) default: - return errors.Errorf(`invalid key: %s`, name) + return fmt.Errorf("invalid key: %s", name) } } diff --git a/internal/jwx/jws/jws.go b/internal/jwx/jws/jws.go index bfa498bb0f..c163a3bd5b 100644 --- a/internal/jwx/jws/jws.go +++ b/internal/jwx/jws/jws.go @@ -24,6 +24,8 @@ import ( "crypto/rand" "encoding/base64" "encoding/json" + "errors" + "fmt" "io" "strings" @@ -31,8 +33,6 @@ import ( "github.com/open-policy-agent/opa/internal/jwx/jwk" "github.com/open-policy-agent/opa/internal/jwx/jws/sign" "github.com/open-policy-agent/opa/internal/jwx/jws/verify" - - "github.com/pkg/errors" ) // SignLiteral generates a Signature for the given Payload and Headers, and serializes @@ -50,7 +50,7 @@ func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, hd ) signer, err := sign.New(alg) if err != nil { - return nil, errors.Wrap(err, `failed to create signer`) + return nil, fmt.Errorf("failed to create signer: %w", err) } var signature []byte @@ -61,7 +61,7 @@ func SignLiteral(payload []byte, alg jwa.SignatureAlgorithm, key interface{}, hd signature, err = signer.Sign([]byte(signingInput), key) } if err != nil { - return nil, errors.Wrap(err, `failed to sign Payload`) + return nil, fmt.Errorf("failed to sign Payload: %w", err) } encodedSignature := base64.RawURLEncoding.EncodeToString(signature) compactSerialization := strings.Join( @@ -83,12 +83,12 @@ func SignWithOption(payload []byte, alg jwa.SignatureAlgorithm, key interface{}) err := headers.Set(AlgorithmKey, alg) if err != nil { - return nil, errors.Wrap(err, "Failed to set alg value") + return nil, fmt.Errorf("failed to set alg value: %w", err) } hdrBuf, err := json.Marshal(headers) if err != nil { - return nil, errors.Wrap(err, `failed to marshal Headers`) + return nil, fmt.Errorf("failed to marshal Headers: %w", err) } // NOTE(sr): we don't use SignWithOption -- if we did, this rand.Reader // should come from the BuiltinContext's Seed, too. @@ -104,7 +104,7 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte verifier, err := verify.New(alg) if err != nil { - return nil, errors.Wrap(err, "failed to create verifier") + return nil, fmt.Errorf("failed to create verifier: %w", err) } buf = bytes.TrimSpace(buf) @@ -114,7 +114,7 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte parts, err := SplitCompact(string(buf[:])) if err != nil { - return nil, errors.Wrap(err, `failed extract from compact serialization format`) + return nil, fmt.Errorf("failed extract from compact serialization format: %w", err) } signingInput := strings.Join( @@ -126,16 +126,16 @@ func Verify(buf []byte, alg jwa.SignatureAlgorithm, key interface{}) (ret []byte decodedSignature, err := base64.RawURLEncoding.DecodeString(parts[2]) if err != nil { - return nil, errors.Wrap(err, "Failed to decode signature") + return nil, fmt.Errorf("failed to decode signature: %w", err) } if err := verifier.Verify([]byte(signingInput), decodedSignature, key); err != nil { - return nil, errors.Wrap(err, "Failed to verify message") + return nil, fmt.Errorf("failed to verify message: %w", err) } if decodedPayload, err := base64.RawURLEncoding.DecodeString(parts[1]); err == nil { return decodedPayload, nil } - return nil, errors.Wrap(err, "Failed to decode Payload") + return nil, fmt.Errorf("failed to decode Payload: %w", err) } // VerifyWithJWK verifies the JWS message using the specified JWK @@ -143,7 +143,7 @@ func VerifyWithJWK(buf []byte, key jwk.Key) (payload []byte, err error) { keyVal, err := key.Materialize() if err != nil { - return nil, errors.Wrap(err, "Failed to materialize key") + return nil, fmt.Errorf("failed to materialize key: %w", err) } return Verify(buf, key.GetAlgorithm(), keyVal) } @@ -179,7 +179,7 @@ func SplitCompact(jwsCompact string) ([]string, error) { parts := strings.Split(jwsCompact, ".") if len(parts) < 3 { - return nil, errors.New("Failed to split compact serialization") + return nil, errors.New("failed to split compact serialization") } return parts, nil } @@ -190,24 +190,24 @@ func parseCompact(str string) (m *Message, err error) { var decodedHeader, decodedPayload, decodedSignature []byte parts, err := SplitCompact(str) if err != nil { - return nil, errors.Wrap(err, `invalid compact serialization format`) + return nil, fmt.Errorf("invalid compact serialization format: %w", err) } if decodedHeader, err = base64.RawURLEncoding.DecodeString(parts[0]); err != nil { - return nil, errors.Wrap(err, `failed to decode Headers`) + return nil, fmt.Errorf("failed to decode Headers: %w", err) } var hdr StandardHeaders if err := json.Unmarshal(decodedHeader, &hdr); err != nil { - return nil, errors.Wrap(err, `failed to parse JOSE Headers`) + return nil, fmt.Errorf("failed to parse JOSE Headers: %w", err) } if decodedPayload, err = base64.RawURLEncoding.DecodeString(parts[1]); err != nil { - return nil, errors.Wrap(err, `failed to decode Payload`) + return nil, fmt.Errorf("failed to decode Payload: %w", err) } if len(parts) > 2 { if decodedSignature, err = base64.RawURLEncoding.DecodeString(parts[2]); err != nil { - return nil, errors.Wrap(err, `failed to decode Signature`) + return nil, fmt.Errorf("failed to decode Signature: %w", err) } } diff --git a/internal/jwx/jws/sign/ecdsa.go b/internal/jwx/jws/sign/ecdsa.go index 62af72b6c1..db1aadec67 100644 --- a/internal/jwx/jws/sign/ecdsa.go +++ b/internal/jwx/jws/sign/ecdsa.go @@ -4,11 +4,11 @@ import ( "crypto" "crypto/ecdsa" "crypto/rand" + "errors" + "fmt" "io" "github.com/open-policy-agent/opa/internal/jwx/jwa" - - "github.com/pkg/errors" ) var ecdsaSignFuncs = map[jwa.SignatureAlgorithm]ecdsaSignFunc{} @@ -37,7 +37,7 @@ func makeECDSASignFunc(hash crypto.Hash) ecdsaSignFunc { h.Write(payload) r, s, err := ecdsa.Sign(rnd, key, h.Sum(nil)) if err != nil { - return nil, errors.Wrap(err, "failed to sign payload using ecdsa") + return nil, fmt.Errorf("failed to sign payload using ecdsa: %w", err) } rBytes := r.Bytes() @@ -56,7 +56,7 @@ func makeECDSASignFunc(hash crypto.Hash) ecdsaSignFunc { func newECDSA(alg jwa.SignatureAlgorithm) (*ECDSASigner, error) { signfn, ok := ecdsaSignFuncs[alg] if !ok { - return nil, errors.Errorf(`unsupported algorithm while trying to create ECDSA signer: %s`, alg) + return nil, fmt.Errorf("unsupported algorithm while trying to create ECDSA signer: %s", alg) } return &ECDSASigner{ @@ -74,12 +74,12 @@ func (s ECDSASigner) Algorithm() jwa.SignatureAlgorithm { // source (such as `rand.Reader`). func (s ECDSASigner) SignWithRand(payload []byte, key interface{}, r io.Reader) ([]byte, error) { if key == nil { - return nil, errors.New(`missing private key while signing payload`) + return nil, errors.New("missing private key while signing payload") } privateKey, ok := key.(*ecdsa.PrivateKey) if !ok { - return nil, errors.Errorf(`invalid key type %T. *ecdsa.PrivateKey is required`, key) + return nil, fmt.Errorf("invalid key type %T. *ecdsa.PrivateKey is required", key) } return s.sign(payload, privateKey, r) } diff --git a/internal/jwx/jws/verify/hmac.go b/internal/jwx/jws/verify/hmac.go index 77e45887ae..1f8d04984c 100644 --- a/internal/jwx/jws/verify/hmac.go +++ b/internal/jwx/jws/verify/hmac.go @@ -2,18 +2,18 @@ package verify import ( "crypto/hmac" - - "github.com/pkg/errors" + "fmt" "github.com/open-policy-agent/opa/internal/jwx/jwa" "github.com/open-policy-agent/opa/internal/jwx/jws/sign" + "github.com/pkg/errors" ) func newHMAC(alg jwa.SignatureAlgorithm) (*HMACVerifier, error) { s, err := sign.New(alg) if err != nil { - return nil, errors.Wrap(err, `failed to generate HMAC signer`) + return nil, fmt.Errorf("failed to generate HMAC signer: %w", err) } return &HMACVerifier{signer: s}, nil } @@ -23,11 +23,11 @@ func (v HMACVerifier) Verify(signingInput, signature []byte, key interface{}) (e expected, err := v.signer.Sign(signingInput, key) if err != nil { - return errors.Wrap(err, `failed to generated signature`) + return fmt.Errorf("failed to generated signature: %w", err) } if !hmac.Equal(signature, expected) { - return errors.New(`failed to match hmac signature`) + return errors.New("failed to match hmac signature") } return nil } diff --git a/internal/runtime/init/init.go b/internal/runtime/init/init.go index 1f88e1e218..819e2a321c 100644 --- a/internal/runtime/init/init.go +++ b/internal/runtime/init/init.go @@ -7,11 +7,10 @@ package init import ( "context" + "fmt" "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/bundle" storedversion "github.com/open-policy-agent/opa/internal/version" @@ -39,10 +38,9 @@ type InsertAndCompileResult struct { // InsertAndCompile writes data and policy into the store and returns a compiler for the // store contents. func InsertAndCompile(ctx context.Context, opts InsertAndCompileOptions) (*InsertAndCompileResult, error) { - if len(opts.Files.Documents) > 0 { if err := opts.Store.Write(ctx, opts.Txn, storage.AddOp, storage.Path{}, opts.Files.Documents); err != nil { - return nil, errors.Wrap(err, "storage error") + return nil, fmt.Errorf("storage error: %w", err) } } @@ -77,13 +75,13 @@ func InsertAndCompile(ctx context.Context, opts InsertAndCompileOptions) (*Inser // modules loaded outside of bundles will need to be added manually. for id, parsed := range opts.Files.Modules { if err := opts.Store.UpsertPolicy(ctx, opts.Txn, id, parsed.Raw); err != nil { - return nil, errors.Wrap(err, "storage error") + return nil, fmt.Errorf("storage error: %w", err) } } // Set the version in the store last to prevent data files from overwriting. if err := storedversion.Write(ctx, opts.Store, opts.Txn); err != nil { - return nil, errors.Wrap(err, "storage error") + return nil, fmt.Errorf("storage error: %w", err) } return &InsertAndCompileResult{Compiler: compiler, Metrics: m}, nil diff --git a/internal/wasm/encoding/reader.go b/internal/wasm/encoding/reader.go index 1ec2651260..9c9c391a58 100644 --- a/internal/wasm/encoding/reader.go +++ b/internal/wasm/encoding/reader.go @@ -11,8 +11,6 @@ import ( "io" "io/ioutil" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/internal/leb128" "github.com/open-policy-agent/opa/internal/wasm/constant" "github.com/open-policy-agent/opa/internal/wasm/instruction" @@ -27,7 +25,7 @@ func ReadModule(r io.Reader) (*module.Module, error) { wr := &reader{r: r, n: 0} module, err := readModule(wr) if err != nil { - return nil, errors.Wrapf(err, "offset 0x%x", wr.n) + return nil, fmt.Errorf("offset 0x%x: %w", wr.n, err) } return module, nil @@ -39,7 +37,7 @@ func ReadCodeEntry(r io.Reader) (*module.CodeEntry, error) { wr := &reader{r: r, n: 0} entry, err := readCodeEntry(wr) if err != nil { - return nil, errors.Wrapf(err, "offset 0x%x", wr.n) + return nil, fmt.Errorf("offset 0x%x: %w", wr.n, err) } return entry, nil @@ -97,7 +95,7 @@ func readCodeEntry(r io.Reader) (*module.CodeEntry, error) { var entry module.CodeEntry if err := readLocals(r, &entry.Func.Locals); err != nil { - return nil, errors.Wrapf(err, "local declarations") + return nil, fmt.Errorf("local declarations: %w", err) } return &entry, readExpr(r, &entry.Func.Expr) @@ -145,61 +143,61 @@ func readSections(r io.Reader, m *module.Module) error { switch id { case constant.StartSectionID: if err := readStartSection(bufr, &m.Start); err != nil { - return errors.Wrap(err, "start section") + return fmt.Errorf("start section: %w", err) } case constant.CustomSectionID: var name string if err := readByteVectorString(bufr, &name); err != nil { - return errors.Wrap(err, "read custom section type") + return fmt.Errorf("read custom section type: %w", err) } if name == "name" { if err := readCustomNameSections(bufr, &m.Names); err != nil { - return errors.Wrap(err, "custom 'name' section") + return fmt.Errorf("custom 'name' section: %w", err) } } else { if err := readCustomSection(bufr, name, &m.Customs); err != nil { - return errors.Wrap(err, "custom section") + return fmt.Errorf("custom section: %w", err) } } case constant.TypeSectionID: if err := readTypeSection(bufr, &m.Type); err != nil { - return errors.Wrap(err, "type section") + return fmt.Errorf("type section: %w", err) } case constant.ImportSectionID: if err := readImportSection(bufr, &m.Import); err != nil { - return errors.Wrap(err, "import section") + return fmt.Errorf("import section: %w", err) } case constant.TableSectionID: if err := readTableSection(bufr, &m.Table); err != nil { - return errors.Wrap(err, "table section") + return fmt.Errorf("table section: %w", err) } case constant.MemorySectionID: if err := readMemorySection(bufr, &m.Memory); err != nil { - return errors.Wrap(err, "memory section") + return fmt.Errorf("memory section: %w", err) } case constant.GlobalSectionID: if err := readGlobalSection(bufr, &m.Global); err != nil { - return errors.Wrap(err, "global section") + return fmt.Errorf("global section: %w", err) } case constant.FunctionSectionID: if err := readFunctionSection(bufr, &m.Function); err != nil { - return errors.Wrap(err, "function section") + return fmt.Errorf("function section: %w", err) } case constant.ExportSectionID: if err := readExportSection(bufr, &m.Export); err != nil { - return errors.Wrap(err, "export section") + return fmt.Errorf("export section: %w", err) } case constant.ElementSectionID: if err := readElementSection(bufr, &m.Element); err != nil { - return errors.Wrap(err, "element section") + return fmt.Errorf("element section: %w", err) } case constant.DataSectionID: if err := readDataSection(bufr, &m.Data); err != nil { - return errors.Wrap(err, "data section") + return fmt.Errorf("data section: %w", err) } case constant.CodeSectionID: if err := readRawCodeSection(bufr, &m.Code); err != nil { - return errors.Wrap(err, "code section") + return fmt.Errorf("code section: %w", err) } default: return fmt.Errorf("illegal section id") diff --git a/plugins/status/plugin.go b/plugins/status/plugin.go index 7ababd6c31..c457b44cb7 100644 --- a/plugins/status/plugin.go +++ b/plugins/status/plugin.go @@ -12,7 +12,6 @@ import ( "net/http" "reflect" - "github.com/pkg/errors" prom "github.com/prometheus/client_golang/prometheus" "github.com/open-policy-agent/opa/logging" @@ -111,7 +110,7 @@ func (c *Config) validateAndInjectDefaults(services []string, pluginsList []stri t, err := plugins.ValidateAndInjectDefaultsForTriggerMode(trigger, c.Trigger) if err != nil { - return errors.Wrap(err, "invalid status config") + return fmt.Errorf("invalid status config: %w", err) } c.Trigger = t diff --git a/server/server.go b/server/server.go index e52bc40d9a..893d817011 100644 --- a/server/server.go +++ b/server/server.go @@ -10,6 +10,7 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" + "errors" "fmt" "html/template" "io" @@ -25,7 +26,6 @@ import ( "time" "github.com/gorilla/mux" - "github.com/pkg/errors" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" @@ -901,7 +901,7 @@ func (s *Server) v0QueryPath(w http.ResponseWriter, r *http.Request, urlPath str input, err := readInputV0(r) if err != nil { - writer.ErrorString(w, http.StatusBadRequest, types.CodeInvalidParameter, errors.Wrapf(err, "unexpected parse error for input")) + writer.ErrorString(w, http.StatusBadRequest, types.CodeInvalidParameter, fmt.Errorf("unexpected parse error for input: %w", err)) return } @@ -909,7 +909,7 @@ func (s *Server) v0QueryPath(w http.ResponseWriter, r *http.Request, urlPath str if input != nil { x, err := ast.JSON(input) if err != nil { - writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, errors.Wrapf(err, "could not marshal input")) + writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, fmt.Errorf("could not marshal input: %w", err)) return } goInput = &x @@ -1323,7 +1323,7 @@ func (s *Server) v1DataGet(w http.ResponseWriter, r *http.Request) { if input != nil { x, err := ast.JSON(input) if err != nil { - writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, errors.Wrapf(err, "could not marshal input")) + writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, fmt.Errorf("could not marshal input: %w", err)) return } goInput = &x @@ -1551,7 +1551,7 @@ func (s *Server) v1DataPost(w http.ResponseWriter, r *http.Request) { if input != nil { x, err := ast.JSON(input) if err != nil { - writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, errors.Wrapf(err, "could not marshal input")) + writer.ErrorString(w, http.StatusInternalServerError, types.CodeInvalidParameter, fmt.Errorf("could not marshal input: %w", err)) return } goInput = &x @@ -2680,7 +2680,7 @@ func readInputV0(r *http.Request) (ast.Value, error) { func readInputGetV1(str string) (ast.Value, error) { var input interface{} if err := util.UnmarshalJSON([]byte(str), &input); err != nil { - return nil, errors.Wrapf(err, "parameter contains malformed input document") + return nil, fmt.Errorf("parameter contains malformed input document: %w", err) } return ast.InterfaceToValue(input) } @@ -2713,10 +2713,10 @@ func readInputPostV1(r *http.Request) (ast.Value, error) { // anything related if strings.Contains(ct, "yaml") { if err := util.Unmarshal(bs, &request); err != nil { - return nil, errors.Wrapf(err, "body contains malformed input document") + return nil, fmt.Errorf("body contains malformed input document: %w", err) } } else if err := util.UnmarshalJSON(bs, &request); err != nil { - return nil, errors.Wrapf(err, "body contains malformed input document") + return nil, fmt.Errorf("body contains malformed input document: %w", err) } if request.Input == nil { @@ -2880,7 +2880,7 @@ func (l decisionLogger) Log(ctx context.Context, txn storage.Transaction, decisi if l.logger != nil { if err := l.logger(ctx, info); err != nil { - return errors.Wrap(err, "decision_logs") + return fmt.Errorf("decision_logs: %w", err) } } diff --git a/test/cases/testdata/jwtencodesignheadererrors/test-jwtencodesignheadererrors-0380.yaml b/test/cases/testdata/jwtencodesignheadererrors/test-jwtencodesignheadererrors-0380.yaml index 3add5b9f77..41eb28baa4 100644 --- a/test/cases/testdata/jwtencodesignheadererrors/test-jwtencodesignheadererrors-0380.yaml +++ b/test/cases/testdata/jwtencodesignheadererrors/test-jwtencodesignheadererrors-0380.yaml @@ -89,8 +89,8 @@ cases: p = x { io.jwt.encode_sign_raw("{\"alg\":\"dummy\"}", "{\"iss\":\"joe\",\r\n \"exp\":1300819380,\r\n \"http://example.com/is_root\":true}", "{\n\"kty\":\"oct\",\n\"k\":\"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow\"\n}", x) } - note: jwtencodesignheadererrors/Unknown signature algorithm + note: jwtencodesignheadererrors/unknown signature algorithm query: data.generated.p = x - want_error: Unknown signature algorithm + want_error: unknown signature algorithm want_error_code: eval_builtin_error strict_error: true diff --git a/test/wasm/cmd/wasm-rego-testgen/main.go b/test/wasm/cmd/wasm-rego-testgen/main.go index 4a0d9a934b..53d2f6b218 100644 --- a/test/wasm/cmd/wasm-rego-testgen/main.go +++ b/test/wasm/cmd/wasm-rego-testgen/main.go @@ -17,7 +17,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/open-policy-agent/opa/rego" @@ -177,10 +176,10 @@ func run(params params) error { return writeFile(tw, dst, bs) }() if err != nil { - return errors.Wrap(err, files[i].Name()) + return fmt.Errorf("%s: %w", files[i].Name(), err) } } else if err != nil { - return errors.Wrap(err, files[i].Name()) + return fmt.Errorf("%s: %w", files[i].Name(), err) } } diff --git a/topdown/tokens.go b/topdown/tokens.go index 64828831fd..394dcfbada 100644 --- a/topdown/tokens.go +++ b/topdown/tokens.go @@ -15,13 +15,12 @@ import ( "encoding/hex" "encoding/json" "encoding/pem" + "errors" "fmt" "hash" "math/big" "strings" - "github.com/pkg/errors" - "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/internal/jwx/jwk" "github.com/open-policy-agent/opa/internal/jwx/jws" @@ -280,7 +279,7 @@ func getKeyFromCertOrJWK(certificate string) ([]interface{}, error) { if block.Type == blockTypeCertificate { cert, err := x509.ParseCertificate(block.Bytes) if err != nil { - return nil, errors.Wrap(err, "failed to parse a PEM certificate") + return nil, fmt.Errorf("failed to parse a PEM certificate: %w", err) } return []interface{}{cert.PublicKey}, nil @@ -289,7 +288,7 @@ func getKeyFromCertOrJWK(certificate string) ([]interface{}, error) { if block.Type == "PUBLIC KEY" { key, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { - return nil, errors.Wrap(err, "failed to parse a PEM public key") + return nil, fmt.Errorf("failed to parse a PEM public key: %w", err) } return []interface{}{key}, nil @@ -300,7 +299,7 @@ func getKeyFromCertOrJWK(certificate string) ([]interface{}, error) { jwks, err := jwk.ParseString(certificate) if err != nil { - return nil, errors.Wrap(err, "failed to parse a JWK key (set)") + return nil, fmt.Errorf("failed to parse a JWK key (set): %w", err) } var keys []interface{}