From 1a8b763fae288e1412ae4d9104bc56a57d559ee5 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Fri, 7 Mar 2014 14:43:11 -0800 Subject: [PATCH 1/4] updated parsing errors to provide more feedback --- jwt.go | 89 ++++++++++++++++++++++++++++++++++++----------------- jwt_test.go | 66 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 122 insertions(+), 33 deletions(-) diff --git a/jwt.go b/jwt.go index 32925ef..69754a4 100644 --- a/jwt.go +++ b/jwt.go @@ -84,67 +84,100 @@ func (t *Token) SigningString() (string, error) { // Parse, validate, and return a token. // keyFunc will receive the parsed token and should return the key for validating. // If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (token *Token, err error) { +func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { parts := strings.Split(tokenString, ".") if len(parts) == 3 { - token = &Token{Raw: tokenString} + var err error + token := &Token{Raw: tokenString} // parse Header var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { - return + return token, &ValidationError{err: err.Error(), Malformed: true} } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return + return token, &ValidationError{err: err.Error(), Malformed: true} } // parse Claims var claimBytes []byte if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return + return token, &ValidationError{err: err.Error(), Malformed: true} } if err = json.Unmarshal(claimBytes, &token.Claims); err != nil { - return + return token, &ValidationError{err: err.Error(), Malformed: true} } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { - err = errors.New("Signing method (alg) is unavailable.") - return + return token, &ValidationError{err: "Signing method (alg) is unavailable.", Unverifiable: true} } } else { - err = errors.New("Signing method (alg) is unspecified.") - return - } - - // Check expiration times - now := TimeFunc().Unix() - if exp, ok := token.Claims["exp"].(float64); ok { - if now > int64(exp) { - err = errors.New("Token is expired") - } - } - if nbf, ok := token.Claims["nbf"].(float64); ok { - if now < int64(nbf) { - err = errors.New("Token is not valid yet") - } + return token, &ValidationError{err: "Signing method (alg) is unspecified.", Unverifiable: true} } // Lookup key var key []byte if key, err = keyFunc(token); err != nil { - return + return token, &ValidationError{err: err.Error(), Unverifiable: true} + } + + // Check expiration times + vErr := &ValidationError{} + now := TimeFunc().Unix() + if exp, ok := token.Claims["exp"].(float64); ok { + if now > int64(exp) { + vErr.err = "Token is expired" + vErr.Expired = true + } + } + if nbf, ok := token.Claims["nbf"].(float64); ok { + if now < int64(nbf) { + vErr.err = "Token is not valid yet" + vErr.NotValidYet = true + } } // Perform validation - if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err == nil { - token.Valid = true + if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil { + vErr.err = err.Error() + vErr.SignatureInvalid = true } + if vErr.Valid() { + token.Valid = true + return token, nil + } + + return token, vErr + } else { - err = errors.New("Token contains an invalid number of segments") + return nil, &ValidationError{err: "Token contains an invalid number of segments", Malformed: true} } - return +} + +type ValidationError struct { + err string + Malformed bool //Token is malformed + Unverifiable bool // Token could not be verified because of signing problems + SignatureInvalid bool // Signature validation failed + Expired bool // Exp validation failed + NotValidYet bool // NBF validation failed +} + +func (e *ValidationError) Error() string { + if e.err == "" { + return "Token is invalid" + } + return e.err +} + +// No errors +func (e *ValidationError) Valid() bool { + if e.Malformed || e.Unverifiable || e.SignatureInvalid || e.Expired || e.NotValidYet { + return false + } + return true } // Try to find the token in an http.Request. diff --git a/jwt_test.go b/jwt_test.go index 11b366e..c5f0a0a 100644 --- a/jwt_test.go +++ b/jwt_test.go @@ -8,28 +8,64 @@ import ( "os" "reflect" "testing" + "time" ) var jwtTestData = []struct { - name string - tokenString string - claims map[string]interface{} - valid bool + name string + tokenString string + claims map[string]interface{} + valid bool + validationError *ValidationError }{ { "basic", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", map[string]interface{}{"foo": "bar"}, true, + nil, + }, + { + "basic expired", + "", // autogen + map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, + false, + &ValidationError{Expired: true}, + }, + { + "basic nbf", + "", // autogen + map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, + false, + &ValidationError{NotValidYet: true}, }, { "basic invalid", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", map[string]interface{}{"foo": "bar"}, false, + &ValidationError{SignatureInvalid: true}, }, } +func makeSample(c map[string]interface{}) string { + file, _ := os.Open("test/sample_key") + buf := new(bytes.Buffer) + io.Copy(buf, file) + key := buf.Bytes() + file.Close() + + token := New(GetSigningMethod("RS256")) + token.Claims = c + s, e := token.SignedString(key) + + if e != nil { + panic(e.Error()) + } + + return s +} + func TestJWT(t *testing.T) { file, _ := os.Open("test/sample_key.pub") buf := new(bytes.Buffer) @@ -38,17 +74,33 @@ func TestJWT(t *testing.T) { file.Close() for _, data := range jwtTestData { + if data.tokenString == "" { + data.tokenString = makeSample(data.claims) + } + token, err := Parse(data.tokenString, func(t *Token) ([]byte, error) { return key, nil }) if !reflect.DeepEqual(data.claims, token.Claims) { t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) } if data.valid && err != nil { - t.Errorf("[%v] Error while verifying token: %v", data.name, err) + t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err) } if !data.valid && err == nil { t.Errorf("[%v] Invalid token passed validation", data.name) } + if data.validationError != nil { + if err == nil { + t.Errorf("[%v] Expecting error. Didn't get one.", data.name) + } else { + // perform deep equal without the string bit + err.(*ValidationError).err = "" + if !reflect.DeepEqual(data.validationError, err) { + t.Errorf("[%v] Errors don't match expectation", data.name) + } + + } + } } } @@ -61,6 +113,10 @@ func TestParseRequest(t *testing.T) { // Bearer token request for _, data := range jwtTestData { + if data.tokenString == "" { + data.tokenString = makeSample(data.claims) + } + r, _ := http.NewRequest("GET", "/", nil) r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString)) token, err := ParseFromRequest(r, func(t *Token) ([]byte, error) { return key, nil }) From aa7f010b16b928935be3371903bbc304134f738c Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Fri, 7 Mar 2014 14:46:27 -0800 Subject: [PATCH 2/4] documentation fix --- jwt.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/jwt.go b/jwt.go index 69754a4..c26e8ba 100644 --- a/jwt.go +++ b/jwt.go @@ -144,7 +144,7 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { vErr.SignatureInvalid = true } - if vErr.Valid() { + if vErr.valid() { token.Valid = true return token, nil } @@ -156,6 +156,7 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { } } +// The error from Parse if token is not valid type ValidationError struct { err string Malformed bool //Token is malformed @@ -165,6 +166,7 @@ type ValidationError struct { NotValidYet bool // NBF validation failed } +// Validation error is an error type func (e *ValidationError) Error() string { if e.err == "" { return "Token is invalid" @@ -173,7 +175,7 @@ func (e *ValidationError) Error() string { } // No errors -func (e *ValidationError) Valid() bool { +func (e *ValidationError) valid() bool { if e.Malformed || e.Unverifiable || e.SignatureInvalid || e.Expired || e.NotValidYet { return false } From a796f21fd52a87fb584ee285dc541ca29b3f3ba6 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Sun, 9 Mar 2014 12:24:51 -0700 Subject: [PATCH 3/4] switched error details to bitfield --- jwt.go | 40 ++++++++++++++++++++++------------------ jwt_test.go | 13 ++++++++++--- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/jwt.go b/jwt.go index c26e8ba..85e3b13 100644 --- a/jwt.go +++ b/jwt.go @@ -92,34 +92,34 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { // parse Header var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { - return token, &ValidationError{err: err.Error(), Malformed: true} + return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, &ValidationError{err: err.Error(), Malformed: true} + return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} } // parse Claims var claimBytes []byte if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, &ValidationError{err: err.Error(), Malformed: true} + return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} } if err = json.Unmarshal(claimBytes, &token.Claims); err != nil { - return token, &ValidationError{err: err.Error(), Malformed: true} + return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed} } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { - return token, &ValidationError{err: "Signing method (alg) is unavailable.", Unverifiable: true} + return token, &ValidationError{err: "Signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable} } } else { - return token, &ValidationError{err: "Signing method (alg) is unspecified.", Unverifiable: true} + return token, &ValidationError{err: "Signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable} } // Lookup key var key []byte if key, err = keyFunc(token); err != nil { - return token, &ValidationError{err: err.Error(), Unverifiable: true} + return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable} } // Check expiration times @@ -128,20 +128,20 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { if exp, ok := token.Claims["exp"].(float64); ok { if now > int64(exp) { vErr.err = "Token is expired" - vErr.Expired = true + vErr.Errors |= ValidationErrorExpired } } if nbf, ok := token.Claims["nbf"].(float64); ok { if now < int64(nbf) { vErr.err = "Token is not valid yet" - vErr.NotValidYet = true + vErr.Errors |= ValidationErrorNotValidYet } } // Perform validation if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil { vErr.err = err.Error() - vErr.SignatureInvalid = true + vErr.Errors |= ValidationErrorSignatureInvalid } if vErr.valid() { @@ -152,18 +152,22 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { return token, vErr } else { - return nil, &ValidationError{err: "Token contains an invalid number of segments", Malformed: true} + return nil, &ValidationError{err: "Token contains an invalid number of segments", Errors: ValidationErrorMalformed} } } +const ( + ValidationErrorMalformed uint32 = 1 << iota // Token is malformed + ValidationErrorUnverifiable // Token could not be verified because of signing problems + ValidationErrorSignatureInvalid // Signature validation failed + ValidationErrorExpired // Exp validation failed + ValidationErrorNotValidYet // NBF validation failed +) + // The error from Parse if token is not valid type ValidationError struct { - err string - Malformed bool //Token is malformed - Unverifiable bool // Token could not be verified because of signing problems - SignatureInvalid bool // Signature validation failed - Expired bool // Exp validation failed - NotValidYet bool // NBF validation failed + err string + Errors uint32 // bitfield. see ValidationError... constants } // Validation error is an error type @@ -176,7 +180,7 @@ func (e *ValidationError) Error() string { // No errors func (e *ValidationError) valid() bool { - if e.Malformed || e.Unverifiable || e.SignatureInvalid || e.Expired || e.NotValidYet { + if e.Errors > 0 { return false } return true diff --git a/jwt_test.go b/jwt_test.go index c5f0a0a..8039bd2 100644 --- a/jwt_test.go +++ b/jwt_test.go @@ -30,21 +30,28 @@ var jwtTestData = []struct { "", // autogen map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, false, - &ValidationError{Expired: true}, + &ValidationError{Errors: ValidationErrorExpired}, }, { "basic nbf", "", // autogen map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, false, - &ValidationError{NotValidYet: true}, + &ValidationError{Errors: ValidationErrorNotValidYet}, + }, + { + "expired and nbf", + "", // autogen + map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, + false, + &ValidationError{Errors: ValidationErrorNotValidYet | ValidationErrorExpired}, }, { "basic invalid", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", map[string]interface{}{"foo": "bar"}, false, - &ValidationError{SignatureInvalid: true}, + &ValidationError{Errors: ValidationErrorSignatureInvalid}, }, } From aeec1afe95567d48d5b90804e405ef68b9a0b66b Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Sun, 9 Mar 2014 12:26:36 -0700 Subject: [PATCH 4/4] documentation --- jwt.go | 1 + 1 file changed, 1 insertion(+) diff --git a/jwt.go b/jwt.go index 85e3b13..3b36c98 100644 --- a/jwt.go +++ b/jwt.go @@ -156,6 +156,7 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { } } +// The errors that might occur when parsing and validating a token const ( ValidationErrorMalformed uint32 = 1 << iota // Token is malformed ValidationErrorUnverifiable // Token could not be verified because of signing problems