From 5cf5e3a00f047ba764193b8d79e176b4569e57eb Mon Sep 17 00:00:00 2001 From: Daisuke Maki Date: Thu, 24 Oct 2024 14:57:30 +0900 Subject: [PATCH] tweak jwt error --- Changes-v3.md | 3 +++ jwt/errors.go | 10 ++++++++++ jwt/jwt.go | 12 +----------- jwt/jwt_test.go | 2 +- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/Changes-v3.md b/Changes-v3.md index 276cba02..17ebbaca 100644 --- a/Changes-v3.md +++ b/Changes-v3.md @@ -32,6 +32,9 @@ These are changes that are incompatible with the v2.x.x version. * Validation used to work for `iat`, `nbf`, `exp` fields where these fields were set to the explicit time.Time{} zero value, but now the _presence_ of these fields matter. +* `jwt.ErrInvalidJWT` has been renamed to `jwt.UnknownPayloadTypeError` to better reflect + what the error means + ## JWS * Iterators have been completely removed. diff --git a/jwt/errors.go b/jwt/errors.go index 12b4107a..b0fcd7fa 100644 --- a/jwt/errors.go +++ b/jwt/errors.go @@ -1,9 +1,19 @@ package jwt import ( + "errors" "fmt" ) +var errUnknownPayloadType = errors.New(`unknown payload type (payload is not JWT?)`) + +// UnknownPayloadTypeError returns the opaque error value that is returned when +// `jwt.Parse` fails due to not being able to deduce the format of +// the incoming buffer +func UnknownPayloadTypeError() error { + return errUnknownPayloadType +} + type parseError struct { error } diff --git a/jwt/jwt.go b/jwt/jwt.go index 248f8fcc..3e14e9ef 100644 --- a/jwt/jwt.go +++ b/jwt/jwt.go @@ -6,7 +6,6 @@ package jwt import ( "bytes" - "errors" "fmt" "io" "sync/atomic" @@ -17,15 +16,6 @@ import ( "github.com/lestrrat-go/jwx/v3/jwt/internal/types" ) -var errInvalidJWT = errors.New(`invalid JWT`) - -// ErrInvalidJWT returns the opaque error value that is returned when -// `jwt.Parse` fails due to not being able to deduce the format of -// the incoming buffer -func ErrInvalidJWT() error { - return errInvalidJWT -} - // Settings controls global settings that are specific to JWTs. func Settings(options ...GlobalOption) { var flattenAudience bool @@ -295,7 +285,7 @@ OUTER: break OUTER case jwx.InvalidFormat: - return nil, ErrInvalidJWT() + return nil, UnknownPayloadTypeError() case jwx.UnknownFormat: // "Unknown" may include invalid JWTs, for example, those who lack "aud" // claim. We could be pedantic and reject these diff --git a/jwt/jwt_test.go b/jwt/jwt_test.go index fbea6289..d2dc884f 100644 --- a/jwt/jwt_test.go +++ b/jwt/jwt_test.go @@ -1452,7 +1452,7 @@ func TestGH850(t *testing.T) { var testToken = `eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWF0IjoxNjY2MDkxMzczLCJmb28iOiJiYXIifQ.3GWevx1z2_uCBB9Vj-D0rsT_CMsMeP9GP2rEqGDWpesoG8nHEjAXJOEQV1jOVkkCtTnS18JhcQdb7dW4i-zmqg.trailing-rubbish` _, err := jwt.Parse([]byte(testToken), jwt.WithVerify(false)) - require.True(t, errors.Is(err, jwt.ErrInvalidJWT())) + require.True(t, errors.Is(err, jwt.UnknownPayloadTypeError())) } func TestGH888(t *testing.T) {