Skip to content

Commit

Permalink
Use fmt for error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
aidantwoods committed Aug 8, 2022
1 parent c83c227 commit 61d967e
Show file tree
Hide file tree
Showing 16 changed files with 97 additions and 94 deletions.
30 changes: 9 additions & 21 deletions claims.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package paseto

import (
"crypto/subtle"
"errors"
"fmt"
"time"
)

Expand All @@ -21,10 +21,7 @@ func ForAudience(audience string) Rule {
}

if subtle.ConstantTimeCompare([]byte(tAud), []byte(audience)) == 0 {
return errors.New(
"this token is not intended for `" +
audience + "`. `" + tAud + "` found",
)
return fmt.Errorf("this token is not intended for `%s'. `%s' found", audience, tAud)
}

return nil
Expand All @@ -41,10 +38,7 @@ func IdentifiedBy(identifier string) Rule {
}

if subtle.ConstantTimeCompare([]byte(tJti), []byte(identifier)) == 0 {
return errors.New(
"this token is not identified by `" +
identifier + "`. `" + tJti + "` found",
)
return fmt.Errorf("this token is not identified by `%s'. `%s' found", identifier, tJti)
}

return nil
Expand All @@ -63,10 +57,7 @@ func IssuedBy(issuer string) Rule {
issBytes := []byte(issuer)

if subtle.ConstantTimeCompare(tIssBytes, issBytes) == 0 {
return errors.New(
"this token is not issued by `" +
issuer + "`. `" + tIss + "` found",
)
return fmt.Errorf("this token is not issued by `%s'. `%s' found", issuer, tIss)
}

return nil
Expand All @@ -85,7 +76,7 @@ func NotExpired() Rule {
}

if time.Now().After(exp) {
return errors.New("this token has expired")
return fmt.Errorf("this token has expired")
}

return nil
Expand All @@ -101,10 +92,7 @@ func Subject(subject string) Rule {
}

if subtle.ConstantTimeCompare([]byte(tSub), []byte(subject)) == 0 {
return errors.New(
"this token is not related to `" +
subject + "`. `" + tSub + "` found",
)
return fmt.Errorf("this token is not related to `%s'. `%s' found", subject, tSub)
}

return nil
Expand All @@ -121,23 +109,23 @@ func ValidAt(t time.Time) Rule {
return err
}
if t.Before(iat) {
return errors.New("the ValidAt time is before this token was issued")
return fmt.Errorf("the ValidAt time is before this token was issued")
}

nbf, err := token.GetNotBefore()
if err != nil {
return err
}
if t.Before(nbf) {
return errors.New("the ValidAt time is before this token's not before time")
return fmt.Errorf("the ValidAt time is before this token's not before time")
}

exp, err := token.GetExpiration()
if err != nil {
return err
}
if t.After(exp) {
return errors.New("the ValidAt time is after this token expires")
return fmt.Errorf("the ValidAt time is after this token expires")
}

return nil
Expand Down
39 changes: 39 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package paseto

import "fmt"

func errorKeyLength(expected, given int) error {
return fmt.Errorf("key length incorrect (%d), expected %d", given, expected)
}

func errorSeedLength(expected, given int) error {
return fmt.Errorf("seed length incorrect (%d), expected %d", given, expected)
}

func errorMessageParts(given int) error {
return fmt.Errorf("invalid number of message parts in token (%d)", given)
}

func errorMessageHeader(expected Protocol, givenHeader string) error {
return fmt.Errorf("message header `%s' is not valid, expected `%s'", givenHeader, expected.Header())
}

func errorMessageHeaderDecrypt(expected Protocol, givenHeader string) error {
return fmt.Errorf("cannot decrypt message: %w", errorMessageHeader(expected, givenHeader))
}

func errorMessageHeaderVerify(expected Protocol, givenHeader string) error {
return fmt.Errorf("cannot verify message: %w", errorMessageHeader(expected, givenHeader))
}

var unsupportedPasetoVersion = fmt.Errorf("unsupported PASETO version")
var unsupportedPasetoPurpose = fmt.Errorf("unsupported PASETO purpose")
var unsupportedPayload = fmt.Errorf("unsupported payload")

var errorPayloadShort = fmt.Errorf("payload is not long enough to be a valid PASETO message")
var errorBadSignature = fmt.Errorf("bad signature")
var errorBadMAC = fmt.Errorf("bad message authentication code")

func errorDecrypt(err error) error {
return fmt.Errorf("the message could not be decrypted: %w", err)
}
5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ module aidanwoods.dev/go-paseto
go 1.17

require (
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
)
10 changes: 4 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898 h1:SLP7Q4Di66FONjDJbCYrCRrh97focO6sLogHO7/g8F0=
golang.org/x/crypto v0.0.0-20220518034528-6f7dac969898/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c=
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 h1:9vYwv7OjYaky/tlAeD7C4oC9EsPTlaFl1H2jS++V+ME=
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
Expand Down
5 changes: 2 additions & 3 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"strings"

"aidanwoods.dev/go-paseto/internal/encoding"
"github.com/pkg/errors"
)

// Message is a building block type, only use if you need to use Paseto
Expand All @@ -25,7 +24,7 @@ func newMessage(protocol Protocol, token string) (message, error) {
}

if header != protocol.Header() {
return message{}, errors.Errorf("Message header is not valid with the given purpose, expected %s got %s", protocol.Header(), header)
return message{}, errorMessageHeader(protocol, header)
}

payloadBytes, err := encoding.Decode(encodedPayload)
Expand Down Expand Up @@ -82,7 +81,7 @@ func deconstructToken(token string) (header string, encodedPayload string, encod

partsLen := len(parts)
if partsLen != 3 && partsLen != 4 {
err = errors.New("Invalid number of message parts in token")
err = errorMessageParts(len(parts))
return
}

Expand Down
19 changes: 9 additions & 10 deletions paseto.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package paseto

import (
"errors"
"fmt"
)

Expand Down Expand Up @@ -53,11 +52,11 @@ type Protocol struct {
func NewProtocol(version Version, purpose Purpose) (Protocol, error) {
switch version {
default:
return Protocol{}, errors.New("Unsupported PASETO version")
return Protocol{}, unsupportedPasetoVersion
case Version2:
switch purpose {
default:
return Protocol{}, errors.New("Unsupported PASETO purpose")
return Protocol{}, unsupportedPasetoPurpose
case Local:
return V2Local, nil
case Public:
Expand All @@ -66,7 +65,7 @@ func NewProtocol(version Version, purpose Purpose) (Protocol, error) {
case Version3:
switch purpose {
default:
return Protocol{}, errors.New("Unsupported PASETO purpose")
return Protocol{}, unsupportedPasetoPurpose
case Local:
return V3Local, nil
case Public:
Expand All @@ -75,7 +74,7 @@ func NewProtocol(version Version, purpose Purpose) (Protocol, error) {
case Version4:
switch purpose {
default:
return Protocol{}, errors.New("Unsupported PASETO purpose")
return Protocol{}, unsupportedPasetoPurpose
case Local:
return V4Local, nil
case Public:
Expand All @@ -102,11 +101,11 @@ func (p Protocol) Purpose() Purpose {
func (p Protocol) newPayload(bytes []byte) (payload, error) {
switch p.version {
default:
return nil, errors.New("Unsupported PASETO version")
return nil, unsupportedPasetoVersion
case Version2:
switch p.purpose {
default:
return nil, errors.New("Unsupported PASETO purpose")
return nil, unsupportedPasetoPurpose
case Local:
return newV2LocalPayload(bytes)
case Public:
Expand All @@ -115,7 +114,7 @@ func (p Protocol) newPayload(bytes []byte) (payload, error) {
case Version3:
switch p.purpose {
default:
return nil, errors.New("Unsupported PASETO purpose")
return nil, unsupportedPasetoPurpose
case Local:
return newV3LocalPayload(bytes)
case Public:
Expand All @@ -124,7 +123,7 @@ func (p Protocol) newPayload(bytes []byte) (payload, error) {
case Version4:
switch p.purpose {
default:
return nil, errors.New("Unsupported PASETO purpose")
return nil, unsupportedPasetoPurpose
case Local:
return newV4LocalPayload(bytes)
case Public:
Expand All @@ -140,7 +139,7 @@ type payload interface {
func protocolForPayload(payload payload) (Protocol, error) {
switch payload.(type) {
default:
return Protocol{}, errors.New("Unsupported Payload")
return Protocol{}, unsupportedPayload
case v2LocalPayload:
return V2Local, nil
case v2PublicPayload:
Expand Down
7 changes: 3 additions & 4 deletions token.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ package paseto

import (
"encoding/json"
"fmt"
"time"

"github.com/pkg/errors"
)

// Token is a set of paseto claims, and a footer
Expand Down Expand Up @@ -50,7 +49,7 @@ func NewTokenFromClaimsJSON(claimsData []byte, footer []byte) (*Token, error) {
func (t *Token) Set(key string, value interface{}) error {
v, err := newTokenValue(value)
if err != nil {
return errors.Wrapf(err, "could not set key `%s`", key)
return fmt.Errorf("could not set key `%s': %w", key, err)
}

t.claims[key] = *v
Expand All @@ -63,7 +62,7 @@ func (t *Token) Set(key string, value interface{}) error {
func (t Token) Get(key string, output interface{}) (err error) {
v, ok := t.claims[key]
if !ok {
return errors.Errorf("value for key `%s' not present in claims", key)
return fmt.Errorf("value for key `%s' not present in claims", key)
}

if err := json.Unmarshal(v.rawValue, &output); err != nil {
Expand Down
9 changes: 4 additions & 5 deletions v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"aidanwoods.dev/go-paseto/internal/encoding"
"aidanwoods.dev/go-paseto/internal/hashing"
"aidanwoods.dev/go-paseto/internal/random"
"github.com/pkg/errors"
"golang.org/x/crypto/chacha20poly1305"
)

Expand All @@ -31,7 +30,7 @@ func v2PublicSign(packet packet, key V2AsymmetricSecretKey) message {
func v2PublicVerify(msg message, key V2AsymmetricPublicKey) (packet, error) {
payload, ok := msg.p.(v2PublicPayload)
if msg.header() != V2Public.Header() || !ok {
return packet{}, errors.Errorf("Cannot decrypt message with header: %s", msg.header())
return packet{}, errorMessageHeaderVerify(V2Public, msg.header())
}

header, footer := []byte(msg.header()), msg.footer
Expand All @@ -40,7 +39,7 @@ func v2PublicVerify(msg message, key V2AsymmetricPublicKey) (packet, error) {
m2 := encoding.Pae(header, data, footer)

if !ed25519.Verify(key.material, m2, payload.signature[:]) {
return packet{}, errors.Errorf("Bad signature")
return packet{}, errorBadSignature
}

return packet{data, footer}, nil
Expand Down Expand Up @@ -70,7 +69,7 @@ func v2LocalEncrypt(p packet, key V2SymmetricKey, unitTestNonce []byte) message
func v2LocalDecrypt(msg message, key V2SymmetricKey) (packet, error) {
payload, ok := msg.p.(v2LocalPayload)
if msg.header() != V2Local.Header() || !ok {
return packet{}, errors.Errorf("Cannot decrypt message with header: %s", msg.header())
return packet{}, errorMessageHeaderDecrypt(V2Local, msg.header())
}

nonce, cipherText := payload.nonce, payload.cipherText
Expand All @@ -86,7 +85,7 @@ func v2LocalDecrypt(msg message, key V2SymmetricKey) (packet, error) {

plainText, err := cipher.Open(nil, nonce[:], cipherText, preAuth)
if err != nil {
return packet{}, errors.Errorf("The message could not be decrypted. %s", err)
return packet{}, errorDecrypt(err)
}

return packet{plainText, msg.footer}, nil
Expand Down
9 changes: 4 additions & 5 deletions v2_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/hex"

"aidanwoods.dev/go-paseto/internal/random"
"github.com/pkg/errors"
)

// V2AsymmetricPublicKey V2 public public key
Expand All @@ -30,7 +29,7 @@ func NewV2AsymmetricPublicKeyFromBytes(publicKey []byte) (V2AsymmetricPublicKey,
if len(publicKey) != 32 {
// even though we return error, return a random key here rather than
// a nil key
return NewV2AsymmetricSecretKey().Public(), errors.New("Key incorrect length")
return NewV2AsymmetricSecretKey().Public(), errorKeyLength(32, len(publicKey))
}

return V2AsymmetricPublicKey{publicKey}, nil
Expand Down Expand Up @@ -108,7 +107,7 @@ func NewV2AsymmetricSecretKeyFromBytes(privateKey []byte) (V2AsymmetricSecretKey
if len(privateKey) != 64 {
// even though we return error, return a random key here rather than
// a nil key
return NewV2AsymmetricSecretKey(), errors.New("Key incorrect length")
return NewV2AsymmetricSecretKey(), errorKeyLength(64, len(privateKey))
}

return V2AsymmetricSecretKey{privateKey}, nil
Expand All @@ -127,7 +126,7 @@ func NewV2AsymmetricSecretKeyFromSeed(hexEncoded string) (V2AsymmetricSecretKey,
if len(seedBytes) != 32 {
// even though we return error, return a random key here rather than
// a nil key
return NewV2AsymmetricSecretKey(), errors.New("Key incorrect length")
return NewV2AsymmetricSecretKey(), errorSeedLength(32, len(seedBytes))
}

return V2AsymmetricSecretKey{ed25519.NewKeyFromSeed(seedBytes)}, nil
Expand Down Expand Up @@ -173,7 +172,7 @@ func V2SymmetricKeyFromBytes(bytes []byte) (V2SymmetricKey, error) {
if len(bytes) != 32 {
// even though we return error, return a random key here rather than
// a nil key
return NewV2SymmetricKey(), errors.New("Key incorrect length")
return NewV2SymmetricKey(), errorKeyLength(32, len(bytes))
}

var material [32]byte
Expand Down
Loading

0 comments on commit 61d967e

Please sign in to comment.